Home / AI Architecture & System Design / AI System Design
Anatomy of a production LLM system
The map every design answer builds on: the online request path, the per-request capabilities, where state lives, the offline loops, and how one request flows through all of it with real timings and payloads.
16 min read
Most LLM system design questions (a support bot, a RAG assistant, a coding agent, a moderation service) are the same skeleton with different emphasis. If you can picture the skeleton, every answer in this section becomes a variation on it. This guide gives you that picture.
Scroll sideways to see the whole diagram.
The layers
| Layer | Its job | Typical technology | Scale notes | When it fails |
|---|---|---|---|---|
| Client | Send the request, render streamed tokens, citations and actions | Web/mobile app, SDK | Keep one long-lived HTTP response per answer (SSE) | Reconnect and resume from the last event ID |
| API gateway | Authenticate, apply per-user/tenant quotas, assign request IDs, hold the stream open | Managed API gateway or Envoy/NGINX plus a small service | Stateless; scale on concurrent connections, not requests/s, because streams last seconds | Shed load with 429 + Retry-After instead of queueing forever |
| Orchestrator | Run the steps for this request in order: guardrails, context building, model call, tools, output checks, logging | A stateless service (Python/TypeScript/Go/C#); sometimes a workflow engine for long jobs | Mostly waiting on I/O, so one instance handles hundreds of concurrent requests with async code | Time-box every step; degrade (e.g. skip reranking) rather than fail |
| Guardrails | Input checks (abuse, PII, prompt injection) and output checks (policy, groundedness, format) | Small classifiers, regexes, an LLM judge for hard cases | Must be fast: tens of ms for input checks so they don't eat the latency budget | Fail closed for high-risk checks, fail open for low-risk ones; decide per check |
| Retrieval | Turn the question into the right few passages | Query rewrite, BM25 + vector search, reranker, permission filters | Index size drives choice: millions of chunks fit one machine; billions need sharding | Return "not found" honestly; never let the model answer from nothing |
| Tools | Read and change the outside world (orders, calendars, code, search) | Internal APIs, MCP servers | Each tool call is another network hop; parallelize independent calls | Scope to the user, idempotency keys for writes, human confirmation for risky ones |
| Model gateway | One place to call models: routing, retries, provider failover, rate-limit pooling, cost accounting | A thin internal service or an off-the-shelf LLM gateway | Pools provider quotas (tokens per minute) across the company | Fail over to a second provider or a smaller model; circuit-break a failing one |
| Models | Generate tokens | Hosted APIs or self-hosted (vLLM/TensorRT-LLM/SGLang on GPUs) | Self-hosting: capacity set by GPU memory for the KV cache and the per-token latency target | Queue briefly, then fail fast; warm spares because cold starts take minutes |
| State | Conversations, user/tenant config, caches, indexes | Postgres for conversations and config, Redis for short-lived state and caches, a vector index (pgvector, OpenSearch, a vector DB), object storage for documents | Conversations grow without bound: summarize old turns and set retention | Treat caches as optional: a cache outage should slow things down, not break them |
| Offline loops | Keep knowledge fresh (ingestion), record everything (logs/traces), measure quality (evaluation) | Queues (Kafka/SQS), batch jobs, a tracing system, eval harness in CI | Ingestion is bursty (bulk imports); queue it. Logs are large: sample full prompts, keep metadata for all | A failed ingestion job goes to a dead-letter queue and alerts; it never blocks requests |
Life of one request
Take a customer asking a support assistant, "Can I get a refund on my annual plan?", in an ongoing conversation. Here is what actually happens, with typical timings.
| t (ms) | Step | What's sent / returned |
|---|---|---|
| 0 | Client sends POST /conversations/c_81/messages with {"text": "...", "locale": "en"} |
Gateway checks the session cookie, finds tenant acme, takes ~4,500 tokens from the tenant's budget, opens an SSE stream |
| 5 | Orchestrator loads the last 6 messages and a running summary from Postgres | ~1,000 tokens of history |
| 5–60 | In parallel: input guardrails (PII, injection, abuse) and an intent router (small model) | Router returns {"intent": "billing_policy", "sensitive": false, "difficulty": "medium"} |
| 5–250 | In parallel: a small model rewrites the question using the history | "refund policy for annual subscription plans" |
| 250–330 | Hybrid search over the help-center index, filtered by locale=en, product=pro, status=published |
50 candidate chunks |
| 330–450 | Reranker scores the 50 and keeps the top 4 | Top score 0.91, above the 0.5 "I don't know" threshold |
| 450 | Orchestrator assembles the prompt | System prompt and tool definitions (1,500 tokens, identical every time so the provider caches them) + summary + history + 4 chunks in <doc id=...> blocks + the question ≈ 4,200 tokens |
| 450–950 | Model gateway routes to the large model (billing intent) and streams | First token at ~950 ms; the client starts rendering |
| 950–4,000 | Tokens stream to the client; citations arrive as a final sources event |
~200 output tokens |
| 4,000–4,300 | Output checks: policy and groundedness on the finished answer for this high-risk intent | Pass; if it failed, the client would replace the text with links to the articles |
| 4,300 | Log one trace: every span's latency, tokens, cost, model and prompt version | Cost of this turn ≈ 1.5 cents with the cached prefix; written asynchronously so it never delays the user |
Three things to notice:
- Independent steps run in parallel. Guardrails, routing and query rewriting don't depend on each other, so the user pays for the slowest of them, not the sum.
- The model call dominates both latency and cost, so most design effort goes into calling it less (caching, routing), with less (shorter prompts) and earlier (streaming).
- Every step has a defined failure behaviour. A slow reranker is skipped; a failed groundedness check downgrades the answer to links; a provider outage fails over.
Where the money and the milliseconds go
A quick template you can fill in for any question:
requests/day × (input tokens × input price + output tokens × output price) = model cost/day
first-token latency ≈ max(parallel pre-steps) + retrieval + model TTFT
end-to-end latency ≈ first-token latency + output tokens × time per token + post-checks
For the request above: ~250 ms of pre-steps, ~200 ms retrieval, ~500 ms TTFT ≈ 1 s to first token; 200 tokens × 15 ms ≈ 3 s more to finish streaming.
Synchronous versus asynchronous
- Synchronous (user waiting): anything that changes the answer: guardrails, retrieval, the model call, output checks for high-risk answers.
- Asynchronous (user not waiting): logging, analytics, feedback, re-indexing, evaluation, summarizing old turns, follow-up emails. Put these behind a queue so a slow logging pipeline can never slow down answers.
- Long-running work (an agent that takes 10 minutes, a batch of 10,000 documents): accept the job, return a job ID, run it in workers, and push progress or a final notification.
How to use this map in an interview
- Draw the online path first (client → gateway → orchestrator → model).
- Add only the capabilities the question needs: retrieval for knowledge, tools for actions, guardrails always.
- Say where state lives and which loops keep it fresh and measured.
- Walk one request through it with rough numbers, as above.
- Spend the deep dive on the one or two boxes where this particular product is hard.
Every design answer in this section now includes a "How it works: a worked example" section that does step 4 for that system, with real payloads.
Discussion
Help us improve our content — give feedback. Spotted an error, have a better explanation, or got asked a follow-up in a real interview? Share it here.