← AI Explained

What happens between your API request and the first token: LLM inference explained

Every API call runs the same pipeline: tokenise, prefill the prompt, then decode one token at a time while the server streams events back. Knowing which stage you are paying for, in milliseconds and in dollars, is the fastest way to make an LLM feature cheaper and quicker.

THE LIFE OF ONE STREAMED REQUEST (SIMPLIFIED)JSON requesttoken idsadmitKV cachenew tokenseventsYour appHTTPS, stream: trueAPI gatewayauth, limits, tokeniseSchedulerbatch slot + KV blocksGPU prefillwhole prompt, one passDecode loopone token per stepSSE streamtext_delta events
A generic serving path, not any one provider's internals. Prefill sets time to first token; the decode loop sets how fast text keeps arriving. The KV cache is the hand-off between them, and it is what disaggregated serving moves between machines.

The life of a request, step by step

An API request is text and settings in a JSON body. Before any GPU work starts, the serving stack checks your key and rate limits, applies the chat template (the markers that separate system, user and assistant turns) and turns the text into tokens, integer ids from the model's vocabulary. That CPU step is cheap: in a September 2026 vLLM guide, IBM Research's Martin Hickey measured about 15 ms to template and tokenise a 9,000-token prompt.

Token counts depend on the model. Anthropic's docs say Claude 4.7 and later models use a newer tokeniser that produces about 30 percent more tokens for the same text. The /v1/messages/count_tokens endpoint is free (rate limited) and returns an estimate, so use it for budgeting, not billing reconciliation.

A scheduler then gives the request a slot in the running batch and reserves memory for its KV cache. The GPU runs prefill over the whole prompt, then decodes one token per step until it hits a stop sequence, the end-of-turn token or max_tokens. Each token is detokenised and sent to you as a server-sent event (SSE).

Prefill and decode are two different workloads

The vLLM guide puts it simply: prefill reads the whole prompt in one pass and is limited by compute, which sets time to first token (TTFT); decode produces one token at a time and is limited by memory bandwidth, which sets inter-token latency (ITL). Decode does very little arithmetic per byte, because every step must read the weights (all of them, for a dense model) and the sequence's KV cache out of HBM, the GPU's high-bandwidth memory, to produce one token per sequence.

That is why serving engines batch decode steps from many users together: one read of the weights then serves dozens of sequences. It is also why the two phases fight. The guide notes that when both share a GPU, every decode stream waits while a long prefill runs, which users see as a stutter mid-answer.

TTFT is queueing plus prefill, so it grows with prompt length and drops sharply on a cache hit. Tokens per second for one stream is roughly one divided by ITL and barely depends on prompt length until the KV cache gets large. A dashboard that reports only total latency hides which one to fix.

Why output tokens cost more than input tokens

All three models compared in this piece charge five times more for output than input: Claude Opus 5.5 is $4 input and $20 output per million tokens (MTok), gpt-6.1-sol is $2 and $10, and gemini-4-argon is $2 and $10 through 30 November 2026, rising to $4 and $20 from 1 December. We think the ratio tracks the two phases: an input token is one of thousands processed in a single parallel prefill pass, while each output token needs its own sequential decode step and keeps its KV cache resident for the whole answer. Providers do not publish their cost models, so treat that as an explanation, not a fact.

The KV cache: why long context costs memory

During prefill, every attention layer computes a key and a value vector for every token. Storing them means each decode step computes keys and values only for the newest token and attends over the stored ones. This store is the KV cache, and it grows linearly with tokens in the context window.

It is large. The vLLM guide gives Llama-3.1-70B in BF16 at 320 KiB of KV per token, so a 10,000-token prompt holds about 3 GB. At that rate a single 128K-token (131,072-token) conversation needs about 43 GB of KV on top of the weights, more than the entire free KV pool in the illustrative setup below.

ILLUSTRATIVE: 70B MODEL ON 2 X 80 GB GPUSWeights (BF16)140 GB = 70B x 2 bytesActivations, buffers~4 GB (assumed)KV cache pool~16 GB = ~49k tokens
Illustrative numbers, not a measured deployment: 140 GB is 70 billion parameters at 2 bytes each, the 4 GB overhead is an assumption, and real engines also reserve headroom. At 320 KiB per token, the leftover 16 GB holds about 49,000 tokens shared by every user on those GPUs.
KV CACHE PER REQUEST, LLAMA-3.1-70B BF168K-token request2.7 GB32K-token request10.7 GBFree pool (illustrative)16 GB128K-token request42.9 GB
Calculated: 320 KiB per token (vLLM guide, September 2026) times context length, with K = 1,024 tokens and GB = 10^9 bytes. One long-context user can need more KV memory than the whole illustrative pool, which is why long prompts reduce how many users a server can batch.

Serving engines manage this memory in fixed-size blocks, the idea known as paged attention. The Hugging Face Transformers docs describe a per-request block table pointing at physical cache blocks that need not be contiguous, which avoids fragmentation. When blocks run out, vLLM preempts requests and recomputes them later, which its docs say can hurt end-to-end latency. Long context therefore costs twice: more prefill compute per request and fewer requests per GPU.

Blocks also make reuse possible. vLLM hashes each full block from its own tokens plus the hash of the block before it, so requests with an identical prefix share blocks, and a single differing token breaks the match from that block onward. SGLang keeps the same reuse in a radix tree (RadixAttention). Hosted prompt caching works on the same principle.

How serving engines keep GPUs busy

Continuous batching and chunked prefill

Static batching waits for the longest sequence in a batch to finish. Continuous batching, as the Transformers docs define it, reschedules the batch at every generation step, so a finished request leaves and a queued one joins at once. vLLM adds chunked prefill: long prompts are split into chunks and batched with decode requests, with pending decodes scheduled first. Its docs say smaller max_num_batched_tokens values such as 2048 give better ITL and larger values give better TTFT.

Speculative decoding

Decode leaves compute idle while it waits on memory, so speculative decoding spends that spare compute: a small drafter proposes several tokens and the large model verifies them in one pass, keeping the ones it accepts. The figure that matters is acceptance length, the average number of draft tokens accepted per round. In a March 2026 vLLM post, Amazon and NVIDIA engineers introduced P-EAGLE, which drafts all K tokens in one forward pass instead of K; on one NVIDIA B200 with GPT-OSS 20B they report 1.05x to 1.69x speed-ups over EAGLE-3, supported from vLLM v0.16.0.

Look at where the gain lands: against EAGLE-3, the post reports 55 to 69 percent higher throughput at concurrency 1 but only 5 to 25 percent at concurrency 64. Speculation helps most on an underused GPU, such as a single agent waiting on a long answer, and least on a server already batching heavily.

Disaggregated prefill and decode

Because the two phases want different hardware behaviour, open-source serving stacks in 2026 can run them on separate workers and ship the KV cache between them. NVIDIA Dynamo's docs describe a frontend, prefill workers that compute the prompt's KV cache, and decode workers that receive it over a transport such as NIXL, with launch scripts for vLLM, SGLang and TensorRT-LLM. SGLang has its own --disaggregation-mode flag, and llm-d can route each request to the pod that already holds its prefix cache.

It is not free. In the vLLM guide's test on two L40S GPUs (PCIe, no NVLink) with Qwen2.5-7B and prompts of about 8,000 tokens, splitting the phases held p99 ITL at 29 ms against 169 ms collocated at 0.4 requests per second. But each prompt's KV took about 1.3 s to reach the decode worker, so at 0.2 requests per second median TTFT was 2.2 s against 0.7 s collocated. The guide's advice is to disaggregate when p99 ITL misses its target under load and KV transfer is fast (it estimates 3 GB at roughly 65 ms over a 400 Gb/s link, before overhead), and to stay collocated when TTFT is the binding constraint or traffic is low and bursty.

Prompt caching: what the three big APIs charge in November 2026

Hosted prompt caching keeps the KV cache (or an equivalent) for a prompt prefix so the next request with that prefix skips most of its prefill. Anthropic's docs say it generally improves time to first token for long documents and has no effect on the output. The billing rules differ by provider.

Anthropic (Claude Opus 5.5)OpenAI (gpt-6.1-sol)Google (gemini-4-argon)
How it turns onExplicit cache_control breakpoints (up to 4), or one top-level cache_control for automatic placementOn by default; optional explicit breakpoints on GPT-5.6 and laterImplicit by default; explicit caches not supported on Gemini 4 Argon
Minimum prefix512 tokens1,024 tokens (GPT-5.6 and later)4,096 tokens
Lifetime5 minutes (refreshed on each hit) or 1 hourprompt_cache_options.ttl: 30m (default) or 12h, documented for the Responses APINot stated on the caching page
Write cost1.25x input (5 min), 2x input (1 hour)1.25x input (30 min), 2.5x input (12 hours)No write charge listed (implicit only)
Read cost$0.20/MTok, 0.05x of $4 input$0.10/MTok, 0.05x of $2 input$0.10/MTok against $2 input (through 30 Nov)
Where to check hitsusage.cache_read_input_tokensusage.input_tokens_details.cached_tokensusage.total_cached_tokens
LIST PRICE PER MILLION INPUT TOKENS, STANDARD TIEROpus 5.5 cache write 5m$5.00Claude Opus 5.5 input$4.00Claude Opus 5.5 cached$0.20gpt-6.1-sol write 30m$2.50gpt-6.1-sol input$2.00gpt-6.1-sol cached$0.10gemini-4-argon input$2.00gemini-4-argon cached$0.10
From each provider's pricing page on 6 November 2026. All three price a cache hit at 5 percent of input, a 95 percent discount; Anthropic and OpenAI also charge 1.25x input to write the default cache. Gemini 4 Argon's prices double on 1 December 2026, and OpenAI's rates over 272K input tokens are higher.

Two details change how you design prompts. Anthropic builds the cache prefix in the order tools, system, then messages; modifying tool definitions invalidates the entire cache, while changing tool_choice, images or the thinking configuration invalidates the message blocks. OpenAI's guide lists similar breakers, such as changing tools or reasoning.effort. On lifetimes, Anthropic's pricing page says a 5-minute write pays for itself after one read and a 1-hour write after two.

What you control: streaming, caching, limits and batch

Streaming does not make the model faster; it moves the first visible character from the end of generation to roughly TTFT. Anthropic's streaming docs give the event order shown below and add two warnings: streams can include any number of ping events, and errors such as overloaded_error can arrive mid-stream, so your parser must handle an error after it has already shown text.

ONE STREAMED CLAUDE RESPONSE OVER SSEYour appMessages APIModel serverPOST /v1/messages, stream:true1prefill (cached prefix skipped)2message_start + input usage3decode steps emit tokens4content_block_delta: text_delta5ping (any number)6content_block_stop7message_delta: stop_reason, usage8message_stop9
Event names from Anthropic's streaming docs; the model-server steps are a simplified view. Usage in message_delta is cumulative, so read final token counts from the last one, not the first.

The minimal pattern below combines both levers: a long, stable system block marked for caching, streamed output and a usage check at the end. It follows the parameter names in Anthropic's current streaming and prompt caching docs, with claude-opus-5-5 as the example model id.

Python: streaming with a cached system block (example model id)
import anthropic

client = anthropic.Anthropic()
handbook = open("handbook.md").read()  # stable text, at least 512 tokens

with client.messages.stream(
    model="claude-opus-5-5",  # example model id
    max_tokens=1024,
    system=[
        {"type": "text", "text": "Answer questions using the handbook below."},
        {"type": "text", "text": handbook, "cache_control": {"type": "ephemeral"}},
    ],
    messages=[{"role": "user", "content": "What is our on-call escalation policy?"}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    final = stream.get_final_message()

u = final.usage
print("\nwrote:", u.cache_creation_input_tokens, "read:", u.cache_read_input_tokens, "uncached:", u.input_tokens)

Run it twice within five minutes. The first call should report tokens written to the cache and the second should report them as read. If the read count stays at zero, something before the breakpoint changed between calls.

Checklist to cut latency and cost

  1. Order prompts from most stable to least stable. Tools, system instructions and reference documents first, the user's turn last. Keep timestamps, request ids and user names out of the prefix, because one changed token breaks the match from there on.
  2. Freeze what invalidates the cache. Keep tool definitions, image placement and thinking settings identical across turns.
  3. Measure hits, do not assume them. Log cache_read_input_tokens on Claude and cached_tokens on OpenAI per request, and alert when the hit rate drops after a deploy.
  4. Pick the cache lifetime from your traffic. Keep the default for chat. Pay the 2x write for 1 hour on Claude, or 2.5x for a 12h ttl on OpenAI, only when the same prefix returns less often than the default lifetime.
  5. Stream every user-facing response and track TTFT and ITL separately, so you know whether to fix the prompt (prefill) or the output length (decode).
  6. Set max_tokens to a real ceiling. Output is the 5x line on the bill and every token is a sequential decode step.
  7. Send anything not interactive to a batch API. All three providers price batch at 50 percent of standard, and Anthropic says its caching multipliers stack with the batch discount.
  8. Recount tokens when you change models. Moving from a Claude model before 4.7 to a later one adds about 30 percent more tokens for the same text.
  9. Buy speed explicitly when it matters. Claude Opus 5.5 fast mode costs $8 input and $40 output per MTok, double the standard rate.
  10. If you self-host, tune before you split. Adjust chunked prefill and max_num_batched_tokens first, and disaggregate only when p99 ITL misses its target under load and your interconnect can move gigabytes of KV in tens of milliseconds.

For where inference sits between the chips, the cloud and your app, read the four layers of the AI stack.