Architecting a Streaming LLM Chat Backend at Scale
System DesignModel answerLast updated
Design a backend that streams model-generated tokens to many concurrent users, covering the API, GPU inference fleet, KV-cache memory management, autoscaling and multi-turn session state.
Build a Streaming Chat Backend for a Large Language Model
You are asked to design the server side of a conversational assistant. Users type a prompt, and the system streams the reply back token by token. A very large number of people will be chatting at once, and the experience should feel responsive.
What the service must do
- Accept a user message and stream the generated reply back incrementally.
- Remember earlier turns so that a conversation can continue across many requests.
Qualities it must have
- A short wait before the first token appears (time-to-first-token) and a fast, steady token rate afterwards.
- High availability and graceful behavior when machines fail.
- Careful use of accelerator memory for long context windows.
Cover the following in your answer
- Interface: how a client starts, consumes, resumes and cancels a streamed reply.
- Components: load balancing, gateway, orchestration, routing, inference workers and where the attention cache lives.
- Growth and bursts: how the fleet reacts to traffic spikes and how GPUs are allocated and shared.
- Memory and throughput techniques: for example paged cache allocation and continuous batching, and why they matter.
- Conversation state: how a follow-up message behaves if it lands on a different machine than the previous turn.
State your assumptions (user counts, prompt and reply lengths, model size, latency goals) and back them with rough numbers.
Hints
Hint 1
Work out the per-token attention cache size for a large model (layers x KV heads x head dim x 2 x bytes). It shows memory, not raw compute, limits how many conversations fit on a node.
Hint 2
Compare static batching with batching at every decoding step, and contrast reserving one contiguous max-length buffer per request with allocating small fixed-size blocks on demand.
Hint 3
Separate durable state (the conversation database) from soft state (the cache). If the cache is only an optimization, losing it costs recomputation but never correctness, which simplifies routing and failover.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Core idea: LLM decoding is limited by GPU memory bandwidth and by how much attention cache (KV cache) fits in HBM. Treat HBM as the scarce resource and design the scheduler, allocator and router around it.
1. Assumptions and sizing
- 10M daily users, about 50K concurrent streams at peak.
- About 1K input tokens (including history) and about 300 output tokens per request.
- Targets: p99 time-to-first-token (TTFT) under 1 s; time-per-output-token (TPOT) under 50 ms, i.e. 20+ tokens/s, faster than reading speed.
- A 70B-parameter model in FP16 is about 140 GB of weights, so it needs tensor parallelism across 4-8 GPUs within one node (e.g. 8x80 GB).
- KV cost per token for 80 layers, 8 KV heads (grouped-query attention), head dim 128, FP16: 2 x 80 x 8 x 128 x 2 B, about 320 KB. A 4K-token conversation is about 1.3 GB. After weights, one node holds only a few hundred active sequences.
- If a replica sustains about 100 concurrent streams at target TPOT, 50K streams need about 500 replicas, or about 4,000 GPUs. Utilization therefore drives cost.
2. API
POST /v1/conversations/{id}/messages
Headers: Authorization, Idempotency-Key
Body: {content, model, max_tokens, temperature, parent_message_id}
Response: text/event-stream
event: token data: {"seq": 17, "text": "Hello"}
event: done data: {"message_id": "m_124", "usage": {...}, "finish_reason": "stop"}
POST /v1/conversations (create)
GET /v1/conversations/{id}/messages (history)
POST /v1/conversations/{id}/messages/{mid}/cancel
- Server-Sent Events are enough for one-way streaming, work through ordinary proxies and are simpler than WebSockets.
- Sequence numbers plus
Last-Event-IDlet a client resume after a dropped connection. parent_message_idsupports branching and doubles as an optimistic-concurrency check.- An idempotency key prevents duplicate generations on retries.
- Cancel frees GPU slots immediately, a real capacity gain.
3. Architecture
Client -> Global LB (GeoDNS/Anycast) -> API Gateway (auth, rate and token quotas)
-> Chat Orchestrator (load history, template, truncate, safety)
-> Inference Router (model pool, affinity, load-aware)
-> Inference Replicas (scheduler + paged KV cache + TP workers)
Side stores: conversation DB (partitioned by user), Redis (hot history, stream state),
metrics/tracing, object store for weights
- Gateway terminates connections and enforces requests/min and tokens/min.
- Orchestrator is stateless: it builds the prompt from stored history and handles overflow by truncating or summarizing old turns.
- Router prefers the replica likely to hold the conversation's cached prefix, but falls back to the least loaded replica (queue depth, free KV blocks).
- Replica runs an iteration-level scheduler, a block-based KV allocator and the sharded model.
4. Memory and throughput techniques
Continuous batching. Static batches wait on the slowest sequence. Scheduling per decoding step lets finished sequences leave and queued ones join immediately, keeping the GPU busy and typically improving throughput several-fold.
Paged KV cache (PagedAttention). Reserving a contiguous max-length buffer per request wastes often 60-80% of KV memory to fragmentation. Instead:
- Split the cache into fixed blocks (e.g. 16 tokens) with a per-sequence block table.
- Allocate on demand, so waste is limited to the last partial block.
- Share blocks copy-on-write for prefix caching (system prompts, earlier turns) and parallel sampling.
Preemption. When blocks run out, evict low-priority or newest sequences, either swapping KV to CPU memory or dropping it and recomputing, instead of failing requests.
Others:
- Chunked prefill so long prompts do not stall decode steps.
- Prefill/decode disaggregation, since prefill is compute-bound and decode is bandwidth-bound.
- FP8/INT8 weights and KV cache, roughly doubling capacity.
- Speculative decoding with a small draft model to reduce TPOT.
5. Scaling and GPU allocation
- Autoscale on queue wait, KV-block utilization and TTFT, not CPU.
- Cold starts are slow (140 GB of weights takes minutes): keep a warm pool, pre-stage weights on local NVMe, and scale predictively from daily patterns.
- Absorb spikes with admission control: priority tiers, bounded queues returning 429 with
Retry-After, and degradation (lowermax_tokens, smaller model for free traffic). - Placement: keep tensor parallelism inside a node over NVLink, spread replicas across zones and regions, and drain GPUs that show ECC errors or hangs.
6. Session state and consistency
Separate durable from soft state.
- The conversation database is the source of truth. Each turn gets a monotonic number, and a conditional write on
parent_message_idstops two tabs from interleaving turns. - The KV cache is only an optimization. Losing it costs a re-prefill, not correctness.
| Option | Pros | Cons |
|---|---|---|
| Sticky routing (hash on conversation id) | Prefix-cache hits, lower TTFT | Hot spots, cache lost if node dies |
| Distributed KV tier (CPU/NVMe/remote) | Survives rerouting | Moving about 1 GB per conversation is often slower than recomputing |
| Stateless recompute | Simplest, elastic | Repeated prefill cost |
Recommendation: soft affinity with load-aware overflow, rebuild the prompt from the DB on a miss, and add a tiered KV cache only if measurements show prefill dominates cost.
Mid-stream failure: the client reconnects with Last-Event-ID. Tokens already emitted are buffered (e.g. in Redis) and the gateway replays them. If the replica died, the orchestrator re-prefills the prompt plus emitted tokens on a healthy node and continues. Persist the assistant message only on done, or checkpoint partial text periodically.
7. Common mistakes
- Treating the problem as compute-bound and scaling on CPU or GPU utilization.
- Hard-pinning conversations to nodes so failures lose state.
- Forgetting cancellation, idempotency and backpressure.
- Giving no numbers for KV size, concurrency or GPU count.
- Ignoring cold-start time when describing autoscaling.
8. Trade-offs to mention
Larger batches raise throughput but also TPOT, so tune against the latency SLO. Aggressive prefix caching boosts hit rates but consumes blocks that could serve live requests. Quantization saves memory at some quality risk, so validate it with evaluations.