Serving and inference economics
Where a reply’s seconds go, why decode waits on memory, what the KV cache costs, and the price of one support conversation worked out turn by turn.
The assistant went into a pilot with a few thousand customers. Two complaints arrived in the first week. Customers said the assistant “thinks for ages”: after sending a message they watched a spinner for five or six seconds before any reply appeared. And the finance team asked a question nobody had a ready answer for: if all 30,000 daily conversations went through the assistant, what would it cost per month?
Both questions have the same root. The previous chapter showed that producing a reply means running the model once per output token, over a sequence that includes everything before. This chapter follows that work onto real hardware. We will work out where a reply’s seconds go, why the second half of generation is limited by memory rather than arithmetic, what the KV cache costs, how batching changes the numbers, and what one support conversation costs through an API. The numbers use a mid-sized open model and a current datacentre GPU so that every figure can be computed; the reasoning carries over to hosted models whose internals we cannot see.
A reply has two phases with different costs
The pilot’s typical turn sends about 6,000 tokens to the model: a 1,500-token system prompt, 3,000 tokens of retrieved help-centre passages, 1,200 tokens of conversation history and a 300-token question. The reply is about 250 tokens.
Processing those 6,000 input tokens is called prefill. All 6,000 positions are known in advance, so the model processes them together, in one large parallel computation, and in doing so produces the first output token. The time until that first token appears is called time to first token, and prefill sets most of it.
Then comes decode. Each subsequent token depends on the one before it, so they are produced one at a time, each step running the model for a single new position. The speed of this phase is measured in tokens per second per conversation. If the hosted model the pilot used decodes at about 60 tokens per second, 250 tokens take about four seconds.
The spinner complaint now has a precise explanation. The pilot waited for the complete reply before showing anything: about one second of prefill and queueing, then four seconds of decode, then display. Streaming the tokens to the screen as they are produced changes what the customer experiences without changing the work. The first words appear after about one second, and the rest arrive faster than most people read. Total generation time is the same, but the time the customer spends staring at nothing drops by about 80%. It was the cheapest fix in this chapter and the team shipped it first.
Decode is limited by memory, not arithmetic
To see why decode is slow, take a model with 8 billion parameters stored as 16-bit numbers. The weights occupy 16 GB. A GPU of the H100 class can perform on the order of 1,000 trillion 16-bit operations per second and can read its own memory at about 3 TB per second.
One decode step for one conversation needs about 16 billion operations (two per parameter, from the previous chapter). At 1,000 trillion per second, that is 16 microseconds of arithmetic. But to perform those operations the GPU must read every weight from memory into its compute units: 16 GB at 3 TB per second is about 5.3 milliseconds. The arithmetic units spend more than 99% of the step waiting for data. The step takes 5.3 milliseconds, so a single conversation can decode at most about 190 tokens per second on this hardware, however fast the arithmetic is. Real systems reach a fraction of that ceiling.
Prefill is different. For a 6,000-token prompt, the weights are read once and used for all 6,000 positions, so the arithmetic finally dominates: 6,000 × 16 billion = 96 trillion operations, about a tenth of a second at peak and perhaps a quarter of a second at realistic utilisation. Prefill is limited by compute, decode by memory bandwidth. That asymmetry is why API providers charge several times more per output token than per input token: an output token occupies the hardware for a whole memory-bound step, while an input token shares its step with thousands of others.
The KV cache, and what it costs
At every decode step, the new token’s query must be compared with the keys of every earlier token, and their values mixed in. Recomputing those keys and values from scratch each step would repeat the whole prefill for every output token. Instead, the server stores them as they are computed, in the KV cache, and each step only computes the new token’s keys and values and appends them.
The cache is large. For each token, it holds a key and a value vector for every layer and every key-value head. A model shaped like common 8B open models has 32 layers, 8 key-value heads and 128 numbers per head, at 2 bytes each: 2 × 32 × 8 × 128 × 2 = 131,072 bytes, about 131 KB per token. A 6,000-token conversation therefore carries about 0.79 GB of cache. On an 80 GB GPU with 16 GB taken by weights, roughly 64 GB remains, enough for about 80 such conversations at once before anything else is accounted for. The cache, not the arithmetic, decides how many customers one GPU can serve concurrently.
The 8 key-value heads in that calculation are themselves a cost-saving design. Earlier models gave every one of their 32 attention heads its own keys and values, which would make the cache four times larger and cut concurrency to about 20. Sharing each key-value head among several query heads, called grouped-query attention, was adopted largely for this reason.
The team considers retrieving more passages, which would take the typical prompt from 6,000 to 12,000 tokens. On the self-hosted setup above, what happens to the number of concurrent conversations a GPU can hold, to time to first token, and to decode speed?
Show the worked answer
Concurrency roughly halves. Each conversation’s cache grows from 0.79 GB to about 1.57 GB, so the same 64 GB holds about 40 conversations instead of 80.
Time to first token roughly doubles, and slightly more than doubles, because prefill work grows in proportion to length plus a squared attention term that is starting to matter. Decode slows too, but less: each step still reads 16 GB of weights, and now also reads twice as much cache per conversation. At batch size 1 the extra cache read is under 0.3 milliseconds on a 5.3-millisecond step, barely noticeable. With many conversations batched together, as the next section shows, the cache read becomes the larger part of each step, and doubling it hurts.
Batching trades one customer’s speed for everyone’s throughput
If each decode step is dominated by reading 16 GB of weights, the obvious move is to serve many conversations in the same step. Read the weights once and apply them to 32 conversations’ new tokens. The arithmetic grows 32 times, from 16 microseconds to about half a millisecond, still small. The weight read stays 5.3 milliseconds. What does grow is the cache read, since each conversation’s attention must read its own cache.
With 6,000-token conversations, batch 32 reads 32 × 0.79 = 25 GB of cache per step, about 8.4 milliseconds, for a total step of about 13.7 milliseconds. Each conversation now decodes at about 73 tokens per second instead of 179, but the GPU produces about 2,340 tokens per second in total instead of 179. At batch 64 the step is about 22 milliseconds: 45 tokens per second each, about 2,900 in total. These are ceilings computed from bandwidth alone, and real servers reach perhaps half to three-quarters of them, but the shape holds.
Serving software for open models, vLLM and SGLang being widely used examples, adds three things on top of this. Continuous batching lets a conversation join the batch at the next step instead of waiting for the current batch to finish, and leave as soon as its reply is done. Paged KV cache allocates cache memory in small blocks as a conversation grows, rather than reserving room for the longest possible conversation up front, which can otherwise waste a large share of memory. And prefix caching keeps the cache for a shared opening sequence, such as our 1,500-token system prompt, and reuses it across conversations so that it is computed and stored once. Hosted APIs use the same ideas internally; prompt caching discounts are how some of the saving is passed on to customers.
What one support conversation costs
Now the finance question. Suppose the hosted model charges $1 per million input tokens, $5 per million output tokens, and $0.10 per million input tokens read from its prompt cache. These are illustrative prices; current price sheets vary widely by model, but the shape (output several times input, cached input a small fraction of input) is common.
A typical pilot conversation has four turns, and each turn sends the whole conversation again, because the model keeps no memory between calls. Turn one sends 1,500 system tokens, 3,000 retrieved, a 300-token question: 4,800 tokens. Each later turn adds the previous question and answer to the history, 550 tokens, and retrieves fresh passages. So the four turns send 4,800, 5,350, 5,900 and 6,450 tokens: 22,500 input tokens in all. The four replies total 1,000 output tokens.
Without caching, input costs 22,500 × $1 / 1M = $0.0225 and output costs 1,000 × $5 / 1M = $0.005, so a conversation costs about $0.0275. At 30,000 conversations a day that is about $825 a day, or roughly $25,000 a month. Note where the money goes: output tokens cost five times as much each, yet input is 82% of the bill, because the conversation resends its context every turn.
Caching depends on the order in which the prompt is assembled, because a cache can only reuse an identical prefix. The pilot assembled each turn as system prompt, then retrieved passages, then history, then question. The passages change every turn, so everything after the system prompt differed from the previous call and only 1,500 tokens per turn were cached. That gives 6,000 cached and 16,500 uncached input tokens per conversation, for $0.0221 in total. Reordering to system prompt, then history, then passages, then question makes the system prompt plus all previous turns a stable prefix: 1,500, 2,050, 2,600 and 3,150 cached tokens over the four turns, 9,300 in all, with 13,200 uncached. The total falls to $0.0191, about 30% below the uncached figure, from a change in concatenation order. Providers differ in the details (some charge extra to write the cache, entries usually expire after minutes of inactivity, and there is often a minimum prefix length), so the saving must be measured on the provider’s usage reports, not assumed.
The biggest remaining lever is the retrieved context. Cutting it from 3,000 to 1,500 tokens per turn, by retrieving fewer but better passages, removes 6,000 uncached tokens per conversation and saves $0.006, taking the total to about $0.013. Whether that is safe depends on retrieval quality, which the context chapter measures. One cost goes the other way: if the team switches to a model that reasons before answering, those reasoning tokens are usually billed as output. At 500 reasoning tokens per turn, that adds 2,000 output tokens, $0.01 per conversation, and at 60 tokens per second about eight seconds before each visible reply.
| Change | What it improves | What it costs or risks |
|---|---|---|
| Stream the reply | perceived wait falls to the time to first token | the interface must handle partial text and cancelled replies |
| Stable parts of the prompt first | cached input is billed at a fraction; prefill is shorter | ordering discipline in code; cache expiry under low traffic |
| Fewer, better retrieved passages | input cost and time to first token | a missing passage means a wrong or empty answer |
| Cap reply length | decode time and output cost | cut-off answers if the cap is set too low |
| Smaller model for easy intents | every per-token cost | a router to build; quality on hard questions must be measured |
| Quantise weights to 8 or 4 bits (self-hosted) | memory read per step, so decode speed and concurrency | some quality loss, measured on our own questions |
| Speculative decoding | decode latency: a small model drafts tokens, the large one checks several per step | complexity; gains depend on how often drafts are accepted |
The morning the queue fell over
A month into the pilot, the market fell sharply in the first minutes of trading. Here is how the assistant failed, in order, because the sequence is typical of capacity failures in any system and this one has an LLM-specific twist.
On a normal morning, the assistant handles about 3.3 turns per second at peak, each holding a slot for about five seconds. By Little’s Law (items in the system equal arrival rate times time in the system) that is about 17 turns in flight, and about 18,500 input tokens per second, a little over a million per minute. The provider account had a limit of 4 million tokens per minute, comfortable headroom.
At 9:16 traffic rose eightfold. Customers whose orders were rejected for insufficient margin all asked why at once. Input demand reached about 9 million tokens per minute, over twice the limit, and the provider began rejecting requests with rate-limit errors. The assistant’s client library retried each failed call immediately, up to three times, which turned one rejected call into as many as four, and pushed demand higher still. Customers who saw an error typed their question again, adding another conversation each. Within three minutes most calls were failing, and the few that succeeded waited in the provider’s queue long enough that time to first token passed ten seconds. Among the failed conversations were customers reporting trades they had not made.
The team made four changes. Retries now wait with exponential backoff and random jitter, and each conversation has a retry budget, so failures no longer multiply load. The assistant tracks its own token usage against the limit and, above 80% of it, stops starting new model conversations: new customers see a short message with a link to the market-status page and a button to raise a ticket, which costs no model tokens. Messages that the first chapter’s classifier scores as possible unauthorised activity skip the assistant entirely and go to the fraud desk, so they are never caught in a model queue. And under load, the assistant retrieves three passages instead of five and caps replies at 150 tokens, which cuts tokens per turn by about a fifth.
None of these is free. During spikes, some customers get a ticket instead of an answer, and the answers that do go out are shorter. The team also bought a reserved-capacity arrangement that raises the limit for market hours, which costs money on quiet days. The decision they wrote down was: “On volatile mornings we prefer fewer, shorter answers and a reliable ticket path over a slow, failing assistant, and fraud reports never wait on the model.”
Buying tokens or renting GPUs
The calculations above for a self-hosted 8B model make one question tempting: why pay per token? One GPU running that model can produce a couple of thousand output tokens per second and hold about 80 conversations. The answer for this team was utilisation. Broking support traffic is concentrated in market hours: about 70% of conversations arrive between 9:00 and 16:00, with a sharp peak at the open. A GPU sized for the 9:16 spike is mostly idle from late afternoon to the next morning and over weekends, but it is billed every hour. Per-token pricing charges nothing for idle hours.
Self-hosting starts to win when traffic is high and steady enough to keep GPUs busy, when data cannot leave the company’s infrastructure, when a smaller open model is shown by the team’s own evaluations to be good enough for the task, or when the latency the team needs cannot be bought. Each of those is a measurable claim, and the comparison must be made in cost per conversation at the utilisation the team will actually achieve, including the engineers who keep a serving stack running. For the assistant, none of the conditions held, and it stayed on a hosted model.
When this arithmetic is not worth doing
At pilot scale the bill was about $8 a day. A week of engineering time to save a third of that would take years to pay back. Before volume arrives, the only optimisation that clearly pays is streaming, because customers feel latency from the first conversation. Cost work becomes worthwhile when the monthly bill is large enough that a third of it is worth an engineer’s month, or when a latency target is being missed. The order of the levers above, prompt order before context size before model size, also reflects risk: the first changes no answer, the second changes what the model reads, and the third changes the model.
The next chapter, Prompting and structured output, looks inside the 1,500-token system prompt that every one of these conversations begins with: what it should say, what the model reliably does with it, and how to get replies the rest of the system can parse.