Pidoku

Why Inference Is Not Normal Backend Engineering

Module 1 Lesson 1.c 1h Difficulty 2/5

Prerequisites 1.a, 1.b


Before you start#

This lesson compares an LLM service with an ordinary web service. It uses a few terms that later lessons explain in full; here you only need the plain meaning:

WordPlain meaningFull lesson
KV cacheMemory on the GPU where the model keeps its work on everything a request has read and written so far, so it never recomputes it. It grows with every token and is freed when the request ends.12.e
BatchThe group of requests the GPU works on together in one step.2.d
TTFT / ITLTime to first token; inter-token latency — the gap between tokens (1.a).2.c
ReplicaOne running copy of the model server. A service usually has several.20.a
Stateless serviceA server that keeps nothing between requests, so any replica can handle any request. Most web services are built this way.—

1. What is it?#

Every instinct a good backend engineer has — stateless services, scale out by adding copies, requests cost about the same, retries are cheap, autoscale on CPU — is wrong or dangerously incomplete for serving language models.

This lesson lists the differences systematically, so that when your instinct fires you know whether to trust it. Later modules teach the fix for each one.


2. Why does it exist?#

Because the failure is subtle. A team builds an LLM service the way it builds every other service. It works in testing. It works at launch. Then traffic grows 3x and it collapses in a way no runbook covers: latency climbs to 30 seconds, autoscaling adds replicas that take eight minutes to become useful, client retries multiply the load, and GPU memory runs out.

Every one of those symptoms comes from an assumption that holds for ordinary web services and does not hold here. Reasoning models and agents (1.e) make each difference sharper: requests get longer, more variable and more numerous.


3. Simple analogy#

A normal web service is a supermarket checkout. LLM inference is an operating theatre.

At a checkout, customers take roughly similar time, you open another lane when the queue grows, a lane opens in seconds, and if a payment fails you just run it again.

In an operating theatre, procedures take anywhere from twenty minutes to nine hours with no way to know in advance, you cannot open a new theatre in under a day, the theatre is occupied for the whole procedure, resources (blood, ICU beds) are used up gradually and can run out halfway through, and you cannot “just retry”.

Every difference below is a version of that.


4. Tiny example#

The retry storm — the shortest illustration of why intuition fails. This is perfectly reasonable code for calling an ordinary service:

Go
// Perfectly reasonable backend code
func callModel(ctx context.Context, prompt string) (resp *http.Response, err error) {
	for attempt := 0; attempt < 3; attempt++ {
		ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
		defer cancel()
		req, _ := http.NewRequestWithContext(ctx, "POST", modelURL, strings.NewReader(prompt))
		if resp, err = http.DefaultClient.Do(req); err == nil {
			return resp, nil
		}
		time.Sleep(time.Second << attempt) // exponential backoff
	}
	return nil, err
}

On an ordinary service under load, a request times out, you retry, it succeeds. A retry costs about as much as the original — a few milliseconds of CPU.

On an LLM service under load:

t=0    request arrives, gets KV cache memory, starts generating
t=30s  client times out and retries
       ...but the original request is STILL RUNNING: still holding its KV cache,
          still using the GPU, still generating tokens nobody will read
t=30s  retry #1 joins the back of the queue
t=60s  retry #1 times out; the original may still be running; retry #2 joins

You have tripled the load on a system that was already overloaded, and the engine cannot throw any of it away because it does not know the client left. This is a metastable failure: the system cannot recover even after traffic returns to normal, because it is busy serving abandoned work.

The fixes are specific to inference: pass the client’s disconnect through to the engine so it stops the request, give retries a budget, reject new work early instead of queueing it forever (20.c, 20.e), and never retry a request that may still be running.


5. Technical explanation#

Eleven differences#

1. Requests are not alike — their cost varies by 1,000x or more.

Request A: 20-token prompt,      10-token answer    →  ~30 tokens of work
Request B: 100k-token prompt,  4,000-token answer   →  ~104,000 tokens of work
Request C: 2k-token prompt,   20,000-token reasoning trace and answer

So: round-robin load balancing is wrong; limiting requests per second is wrong (limit tokens); “requests in flight” is a poor measure of load (use tokens per second or KV cache usage); and a p99 latency without grouping by length means little.

2. Requests are long-lived and hold state.

A request keeps its KV cache on one GPU for its entire generation — seconds to minutes. That state cannot simply move to another replica. So inference replicas are stateful in practice, which breaks graceful-drain assumptions, blue/green deployments and anything that assumes a request can be rerouted halfway.

3. Capacity is set by memory and ends at a cliff.

Ordinary services degrade gradually: more load, more latency. LLM servers degrade gradually until KV cache memory runs out; then they reject requests, pause and swap some out (big latency spikes), or crash. The change is abrupt.

 latency
   ^                                   ┃ ← KV cache memory full
   |                                   ┃
   |                            ______/┃
   |          _________________/        (preemption / rejection / crash)
   |_________/
   +--------------------------------------> requests running at once

4. Adding capacity takes minutes, not seconds.

Pull the container image (tens of GB)       30–120 s
Load the weights (e.g. 140 GB)              60–600 s   ← limited by storage bandwidth
GPU initialisation, compilation, warm-up    20–120 s
──────────────────────────────────────────────────────
Cold start                                  2–12 minutes

The traffic spike is over before the new replica is ready. So you keep spare capacity running instead of relying on reactive autoscaling, which changes the cost model. Newer techniques shorten this — streaming weights straight from storage to GPU, copying them GPU-to-GPU from a running replica (NVIDIA’s ModelExpress), snapshots of a warmed-up server — and lessons 3.g, 20.g and 23.d cover them.

5. The unit of work is a token, not a request.

Metrics, rate limits, quotas, billing and load balancing should all count tokens. Teams that build request-counting systems rebuild them within a year.

6. Each unit of work costs 100–1,000x more.

A web request costs millionths of a dollar; an LLM request can cost cents, and an agent task dollars. That changes what is worth engineering: caching a response worth $0.00001 is not worth the complexity, while reusing a long prompt prefix worth $0.02 on every agent turn absolutely is (12.m).

7. Output is not repeatable by default.

The same input can give a different output — because the model samples randomly (12.o), and because GPU arithmetic can give slightly different results depending on how many other requests are in the batch. So cache keys must include sampling settings, “reproduce the bug” is hard, A/B tests need bigger samples, and tests that compare exact output strings will be flaky.

8. Correctness is a matter of degree.

There is no HTTP 500 for “the answer got worse”. A quality drop from a quantization change or a new kernel is invisible to normal monitoring. You need evaluation suites in your release pipeline and in production (23.g, 23.h).

9. Streaming changes the request lifecycle.

Once the first token is sent you cannot return an error status; you can only stop mid-stream. Load balancers must not buffer responses, timeouts must watch the gap between tokens rather than the whole request, and connections stay open for a long time (12.p, 20.b).

10. Throughput and latency are set by the same knob.

In an ordinary service, more capacity improves both. Here a bigger batch raises throughput and worsens latency at the same moment, and the engine’s scheduler — not a config file — makes that choice every few milliseconds (2.d, 12.j).

11. The hardware is scarce and expensive.

You cannot add 200 GPUs next Tuesday. Capacity has lead times of months, and power for new data centers is now a constraint in its own right (7.l). Efficiency work is strategic, not optional.

The translation table#

Backend instinctLLM realityLesson
Stateless servicesStateful for each request’s lifetime (KV cache)12.e
Autoscale on CPU %Autoscale on KV cache usage, queue wait or token rate23.d
Scale out in secondsMinutes; keep headroom warm20.g
Retry on timeoutCancel first; uncontrolled retries cause collapse20.e
Round-robin load balancingLoad-aware and prefix-aware routing20.f, 21.h
Requests per secondTokens per second, plus a concurrency limit set by memory12.q
One p99 latency targetSeparate TTFT and ITL targets, grouped by length23.a
Rate limit by requestsRate limit by tokens, input and output separately23.j
Graceful drain in secondsWait for or cancel long-running generations20.h
Cache the responseReuse the prompt’s KV cache — far more valuable12.m
Errors are 4xx/5xxErrors include “the answer is subtly worse”23.g

6. Under the hood#

Why is a replica effectively stateful? A request’s KV cache lives in that GPU’s memory, in blocks the engine tracks in a table (12.l). Moving the request means sending hundreds of megabytes to gigabytes over the network, or recomputing the prompt. Both are expensive, so systems do it only deliberately — which is exactly what disaggregated serving does, over fast networks built for it (9.e, 14.j).

Why is cold start so slow? Reading 140 GB from object storage at 1 GB/s takes 140 seconds; from a local NVMe drive at 5 GB/s, 28 seconds; and it must then be copied into GPU memory. The fixes — caching weights on local disks, loading shards in parallel, memory-mapped safetensors files read straight to the GPU, pre-built images, GPU-to-GPU weight copies, warm standby replicas — all trade money for time (3.g).


7. Performance implications#

  • Under load, queueing dominates time to first token, so admission control does more for tail latency than kernel tuning (20.c).
  • Cancellation is a performance feature. In chat products a meaningful share of generations are abandoned (users stop reading, agents move on). Freeing those immediately is free capacity — one of the highest-return fixes, and often missing.
  • One long prompt can stall everyone. A 100k-token prompt processed in one piece can freeze the token stream of every other request for a second or more. Chunked prefill (12.k) fixes it.

8. Production implications#

A checklist for any LLM service:

[ ] A client disconnect reaches the engine and stops the request
[ ] Timeouts detect stalls between tokens, not just total request time
[ ] Retries have a budget and never duplicate a generation that may still be running
[ ] Rate limits count tokens, input and output separately
[ ] Maximum input and output lengths are enforced at the gateway
[ ] Autoscaling uses KV cache usage or queue wait, not CPU or GPU utilisation
[ ] Warm headroom is sized for a spike plus the cold-start time
[ ] The load balancer does not buffer streamed responses
[ ] TTFT and ITL targets are separate and reported by prompt-length bucket
[ ] Admission control rejects explicitly instead of queueing without limit
[ ] Quality evaluation runs on the exact serving configuration before release
[ ] Shutdown drains in-flight generations with a deadline

Most LLM-serving incidents trace to a missing item on that list, not to a slow kernel.


9. Common mistakes#

Autoscaling on GPU utilisation. It reads near 100% whenever anything runs (22.d), so it says nothing. Use KV cache usage, queue depth or token throughput.

Putting the engine behind an ordinary load balancer. Without load awareness, one replica gets three 50k-token prompts and falls over while the others idle.

Unbounded queues. “We’ll queue and catch up later” produces answers that finish after the user gave up — pure waste. Bound the queue and reject early.

Copying a microservice rollout strategy. Rolling updates that assume ten-second drains kill in-flight generations.

Leaving quality out of the release pipeline. A change that halves latency and quietly worsens reasoning by 5% passes every conventional test.

Assuming calls are idempotent. Sampling makes LLM calls non-repeatable, and repeating them is not free.


10. Hands-on exercise#

A. Simulate a retry storm. Write a small simulator (any language): requests arrive at random, service times are long-tailed, there is a fixed concurrency limit, and clients retry after a 30 s timeout without cancelling the original. Increase the arrival rate until the system stops recovering after a spike ends. Then add cancellation and compare.

B. Measure a cold start. Start a real model server (16.b shows how with vLLM) and time each phase: image pull, weight load, initialisation, first request, steady state. What would you improve first?

C. The cost of a naive load balancer. Simulate four replicas with round-robin routing versus “fewest outstanding tokens”, using a long-tailed length distribution. Compare p99 time to first token.

D. Audit a service. Take any LLM service you can access (or a local vLLM) and go through the checklist in section 8. How many items pass?


11. Interview questions#

  1. Give five ways LLM serving breaks standard backend assumptions.
  2. Why is autoscaling on GPU utilisation wrong? What would you use instead?
  3. Explain a metastable failure in an LLM service and how to prevent it.
  4. Why are LLM replicas effectively stateful? What breaks as a result?
  5. A client disconnects mid-generation. What should happen, and what usually does?
  6. How would you rate-limit an LLM API fairly across tenants?
  7. The release pipeline is green but users say answers got worse. What was missing?

12. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in