How LLM inference and serving work
Serving a language model is a different problem from serving a web page. This guide explains tokens, the two phases of generation, the metrics that matter, how to scale, how to estimate capacity and cost, and which optimisations pay off.
Inference and serving in 60 seconds
- Tokens are the unit of work and of cost. Both the input and the output are counted in tokens.
- Two phases: prefill reads the whole prompt in parallel; decode writes the answer one token at a time. They stress different resources.
- Four numbers to watch: time to first token, tokens per second, throughput, and cost per token.
- Batching is the main lever. Serving many requests together makes a GPU far more efficient, and continuous batching keeps it full.
- Estimate before you buy. A short calculation from users, tokens, and per-GPU speed tells you the order of magnitude of the hardware or the bill.
Tokens: the unit everything is measured in
A model does not read letters or words. It reads tokens, which are common fragments of text. In English, a token is on average a little under a word: a rough rule is that 1,000 tokens is about 750 words. Other languages and code often use more tokens for the same meaning. A provider charges by the token, a model has a maximum number of tokens it can read at once, and speed is measured in tokens per second. Count tokens with the model's own tokenizer, because different models split text differently.
Two phases: prefill and decode
Generating an answer happens in two stages that behave very differently, and most serving design follows from the difference.
- Prefill: the model processes every token of the prompt in one parallel pass and builds the KV cache that decode will use. It does a lot of arithmetic at once, so it is limited by compute. Its duration grows with prompt length and sets the time to first token.
- Decode: the model produces one token, appends it, and repeats. Each step does little arithmetic but must read the full model weights and the KV cache from memory, so it is limited by memory bandwidth. Its speed sets the tokens per second the user sees.
This is why a long prompt with a short answer is expensive at the start and quick afterwards, and why a short prompt with a long answer feels slow for a long time. It is also why some systems run prefill and decode on separate machines, so that a burst of long prompts does not slow down the answers already streaming. Splitting the two is called prefill-decode disaggregation, and it is worth considering only at larger scale.
The four numbers to watch
| Metric | What it measures | What the user feels | What drives it |
|---|---|---|---|
| Time to first token (TTFT) | Delay from request to the first output token | How quickly the answer starts | Queueing, prompt length, prefill speed |
| Tokens per second (per request) | Speed of the streamed answer | How fast the text appears | Model size, memory bandwidth, batch size |
| Throughput (per server) | Total tokens per second across all requests | Nothing directly; it sets cost and capacity | Batching, hardware, model size |
| Cost per token | Money per million tokens | Nothing directly; it sets price and margin | Hardware cost and utilisation |
These pull against each other. Packing more requests into a batch raises throughput and lowers cost per token, but each request gets a smaller share, so per-request speed can fall. A product must pick its position: a chat interface cares most about TTFT and smooth streaming, while a nightly document-processing job cares only about throughput and cost.
Hardware in one page
Large models run on accelerators that do many multiplications at once. A GPU is the general choice, with a mature software ecosystem. A TPU is Google's accelerator, designed around matrix arithmetic. Newer designs, sometimes called LPUs, trade flexibility for very high token speed on specific workloads. What matters when you choose is not the name but three numbers: memory size (the model and the KV cache must fit), memory bandwidth (decode speed depends on it), and the cost per hour for the whole machine.
A rule of thumb for memory: the weights of a model take roughly the number of parameters times the bytes per parameter. A 70-billion-parameter model in 16-bit numbers needs about 140 GB for the weights alone, before any KV cache. Quantisation to 8-bit halves that, and to 4-bit roughly quarters it, at some cost in quality that you should measure.
Batching: how a GPU stays busy
Decoding one request uses a small part of a GPU. Decoding thirty-two requests together costs little more time per step, so the GPU does thirty-two times the useful work. That is why serving engines batch requests. Early systems waited for a batch to fill and ran it to the end, so short requests waited behind long ones. Continuous batching instead lets requests join and leave the batch at every step: when one finishes, a waiting request takes its place immediately. This is the main reason modern inference engines reach several times the throughput of a naive server.
The cache memory limits the batch. Each active request holds a KV cache, so the number of requests in a batch is bounded by free GPU memory after the weights are loaded. Engines allocate this memory in small blocks and release it as requests end, which reduces waste.
Scaling a model server
When one GPU is not enough, there are two separate questions: how to fit one model across several GPUs, and how to handle more requests.
- Vertical scaling: use a larger GPU or more GPUs in one machine. Simple, and fast links between the GPUs keep communication cheap.
- Horizontal scaling (replicas): run more copies of the whole model behind a load balancer. This handles more requests and adds fault tolerance, and each replica needs its own full copy of the weights.
- Tensor parallelism: split each layer's arithmetic across several GPUs that work on the same token together. It lets a model larger than one GPU's memory run, and it needs very fast links between GPUs because they communicate at every layer.
- Pipeline parallelism: place different layers on different GPUs and pass the activations along. It communicates less than tensor parallelism, so it suits machines with slower links, but it needs enough requests in flight to keep every stage busy.
A practical order of operations: pick the smallest model that meets your quality bar, use quantisation if the quality allows, fit it on as few GPUs as possible (using tensor parallelism inside one machine if needed), and then scale out with replicas. Crossing machines with tensor parallelism is usually a last resort because of the communication cost.
Load balancing for model servers
Round-robin works poorly here, because requests are very unequal: one may need ten output tokens and another two thousand. A server that happens to receive several long requests becomes slow while others sit idle. Better strategies look at the actual load.
- Least outstanding tokens: send the request to the replica with the fewest tokens in flight, which tracks real work better than a count of requests.
- Prefix-aware routing: send requests that share a long prompt prefix to the replica that already holds that prefix in its cache, so the prefill is skipped.
- Sticky sessions: keep one conversation on one replica so its cached history is reused. Combine with a fallback, so a failed replica does not strand the user.
Back-of-the-envelope estimation
Before you choose hardware or sign a contract, estimate the load. Start from users and work down to tokens per second. The numbers below are illustrative assumptions, not benchmarks. Replace them with your own measurements.
# Illustrative: every number here is an assumption to replace with measurements.
daily_users = 50_000
requests_per_user = 6
input_tokens = 800 # prompt tokens per request (system prompt + context + question)
output_tokens = 300 # generated tokens per request
daily_input = daily_users * requests_per_user * input_tokens # 240,000,000
daily_output = daily_users * requests_per_user * output_tokens # 90,000,000
avg_output_tps = daily_output / 86_400 # about 1,042 tokens per second on average
peak_factor = 5 # traffic is bursty; use your own peak-to-average ratio
peak_output_tps = avg_output_tps * peak_factor # about 5,200
server_output_tps = 2_500 # assumed sustained output speed of one server with batching
servers_needed = -(-peak_output_tps // server_output_tps) # ceiling division: 3
servers_with_headroom = servers_needed + 1 # one spare for failures and deploys
# Cost if you pay a provider per million tokens (placeholder prices):
price_in, price_out = 0.50, 1.50 # dollars per million tokens
monthly = 30 * (daily_input / 1e6 * price_in + daily_output / 1e6 * price_out)
print(servers_with_headroom, round(monthly))
The calculation shows three things quickly. Output tokens drive speed and are usually priced higher, so shorter answers save money. Peak traffic, not the average, sets the hardware. And a provider's per-token price can be compared with the cost of running your own servers at realistic utilisation. Owning hardware only wins when you keep it busy.
Optimisations that pay off
Each of these trades some complexity or quality for speed or cost. Apply them in the order of the benefit you measure.
| Technique | What it does | Benefit | Watch for |
|---|---|---|---|
| Continuous batching | Requests join and leave the batch each step | Large throughput gain | Needs an engine that supports it |
| Quantisation | Stores weights in fewer bits | Less memory, faster decode | Quality loss; test on your tasks |
| Prefix and KV caching | Reuses work on shared prompt parts | Lower TTFT and cost for repeated prefixes | Prefix must match exactly |
| Speculative decoding | A small model drafts tokens, the large model verifies them | Faster decode with the same output quality | Gain depends on how often drafts are accepted |
| Flash attention | Computes attention with less memory traffic | Faster prefill and longer contexts | Mostly built into engines already |
| Mixture of experts | Uses only part of the model for each token | Large capacity at lower compute per token | All experts still need memory |
| Distillation | Trains a small model to imitate a large one | Cheaper model for a narrow task | Needs training data and evaluation |
| Grouped-query attention | Shares key and value heads across query heads | Smaller KV cache, larger batches | A model design choice, not a setting |
Streaming and long tasks
Because decode produces tokens one by one, you can send each token to the user as it is produced, which makes a slow answer feel fast. Two transports are common: server-sent events, a simple one-way stream over HTTP that suits most chat features, and WebSockets, a two-way connection that suits voice and interactive tools. For tasks that take minutes, such as summarising a large document, do not hold a request open. Accept the job, return an ID, process it from a queue, and let the client poll or receive a callback.
# Illustrative: send each token as soon as the model produces it.
# model.stream() is a placeholder for an engine's streaming call; framework details vary.
def sse_response(prompt):
def events():
try:
for token in model.stream(prompt):
yield f'data: {json_escape(token)}\n\n'
yield 'event: done\ndata: {}\n\n'
except Exception:
yield 'event: error\ndata: {"message": "generation failed"}\n\n'
return Response(events(), content_type='text/event-stream',
headers={'Cache-Control': 'no-cache'})
Choosing an inference engine
You can call a hosted model through a provider's API, or run an open model on your own hardware with an inference engine. Several open-source engines exist, and they differ in features and in the hardware they favour. Judge a candidate on what you need: support for your model, continuous batching, prefix caching, quantisation formats, streaming, observability, and how active the project is. Run your own benchmark with your own prompts and lengths, because published numbers depend heavily on their test conditions. A hosted API is the right start for most teams; self-hosting makes sense when volume is high and steady, data cannot leave your network, or you need custom models.
How to approach a serving design
- State the product need: interactive or batch, the acceptable time to first token, expected answer length.
- Estimate load: users to requests to tokens, and use a peak factor.
- Choose the model size that meets the quality bar, then test quantisation.
- Start with a hosted API to learn real traffic, then compare with self-hosting at that volume.
- Add the cheap wins first: shared prefixes, short outputs, caching, and routing easy requests to a smaller model.
- Measure continuously: TTFT, tokens per second, queue depth, GPU memory, errors, and cost per request.
What this means for your role
Common mistakes
Further reading
- Types of caching in AI systems, including the KV cache and prefix cache used by serving engines.
- Load balancing, the general technique behind routing to replicas.
- Rate limiting, including token-based limits.
- Message queues, for long-running AI jobs.
Serving is a numbers game. Measure tokens, watch the four metrics, and let the estimates guide the design before the invoice does.