Skip to content

AI system design

One page that ties the topics together. Each topic teaches one box; this page shows the whole request path, a method to size it, and a worked example. Read it after two or three topics, and again after the RnR capstone. Words you don't know are in the glossary.

1. The request path

A request passes through a gateway, input guardrails and a router, then retrieval, tools or an agent loop, the LLM, output checks and approval for writes; traces, cost and offline evals run alongside every step

Almost every AI feature is this path with some boxes switched off. A one-shot classifier uses three boxes; the WhatsApp agent uses all of them.

Box What it does Where you built it Rule of thumb
Gateway One door for every model call: keys, rate and token limits, retries, fallback model, cost log rnr 09 (cost meter on the one door, ai/llm.py), 11 (ai/gateway.py: budgets, rate limits, retries, fallback; LiteLLM compared) Never let app code call a model provider directly
Input guardrails Block or clean bad input: injection, PII, off-topic, abuse prompting/05, rnr 01, 03, 04 Cheap rules first, a model only for what rules can't see
Router Pick the path: which tools, which agent, or a human llm-api/07, multi-agent/02, whatsapp-agent/06 Rules for the obvious, a small model for the rest, a human for the unsure
Retrieval Find the passages that answer the question rag 03 to 10 The model only sees what search hands it
Tools / MCP Live facts and actions: stock, price, credit, orders llm-api, mcp-server Facts that change by the minute come from tools, not documents
Agent loop Let the model pick the next step, within a budget agents, multi-agent A workflow first; an agent only when the steps depend on results
LLM Turn context into language every topic Swappable behind one chat() signature
Output checks Schema, amounts, IDs, claims, citations prompting/03, 05, llm-api/05, agents/03, whatsapp-agent/04, 08 Code checks facts; a judge checks what code can't see
Approval A person confirms anything that writes or costs money llm-api/06, agents/06, multi-agent/05 The model asks; code decides; a human signs
Traces, cost, evals See every step, price every call, score every change prompting/04, rnr phases 2, 3, 5 No prompt or model change ships without an eval run

2. The method: seven steps before code

Classic system design works for AI too. Three steps need AI-specific questions.

Step Ask AI-specific question
1. Functional requirements What must it do? Which parts need language, and which are plain code?
2. Non-functional requirements How well, how fast, how safe? Quality bar as an eval score, time to first token, ₹ per request, what data may leave the building, fail open or closed
3. Back of the envelope Requests, tokens, ₹, memory Tokens are the unit: tokens per request × requests = cost and capacity
4. Core components Which boxes from section 1? Which boxes can stay off for v1?
5. High-level design How do the boxes connect? Where does the model sit, and what can it never do (write, approve, calculate)?
6. Low-level design Data model, APIs, prompts Prompts and eval sets are versioned code
7. Trade-offs What did we give up? Quality vs latency vs cost: you pick two per box

3. Worked example: "Ask Acme Build", a buyer assistant

Functional. MSME buyers ask in English or Hinglish about policies and specs (RAG), and about their own prices, stock and order status (tools). It can draft a reorder, but a person confirms it.

Non-functional.

NFR Target How you know
Quality 90% correct on a 200-question golden set; 0 wrong prices rag/09, rnr/05 style eval, run on every change
Latency First token under 1.5 s, full answer under 6 s at p95 Traces
Cost Under ₹0.10 per question Cost meter per prompt version
Safety A buyer never sees another tier's price; no order without confirmation Filters inside tools, approval in code
Failure Model down: answer "try again" and show order status from code Fallback path tested

Back of the envelope. Every number is an assumption; write yours down the same way.

Item Working Result
Volume 5,000 active buyers × 4 questions 20,000 questions a day
Peak load 20,000 over 10 business hours, peak hour 3× average about 1.7 questions a second
Tokens per question input: rules 500 + 5 chunks × 300 + history 500; output 250 2,500 in, 250 out
Tokens a day 20,000 × 2,500 and 20,000 × 250 50M in, 5M out
Cost (hosted model) assumed rate card ₹20 per 1M in, ₹80 per 1M out ₹1,400 a day, about ₹0.07 a question
In flight at peak 1.7 a second × 6 s per answer (Little's law) about 10 answers streaming at once
Vector index 60,000 chunks × 768 dimensions × 4 bytes about 185 MB, plus index overhead
Traces 20,000 × about 10 KB 200 MB a day, so set a retention period

What the numbers tell you:

  • Input tokens are 70% of the bill, and most of them are retrieved chunks. Chunk size and k are cost levers, not just quality levers.
  • Our Mac can't serve this. qwen3:8b streams one answer at a time at roughly 20 to 30 tokens a second; we need about 10 at once. Production needs a hosted model or a GPU server with continuous batching (vLLM). Ollama is the dev box.
  • 185 MB is small. pgvector inside the Postgres you already run is enough; a dedicated vector database earns its place at millions of vectors or very high query rates.

High-level design. FastAPI streams answers. A gateway wraps every model call. Rules and a small model guard input. The router sends policy questions to retrieval (pgvector plus Postgres full-text search, fused with RRF), and account questions to tools on an MCP server over the order and pricing services. Reorders end at a cart card; the Confirm button runs code. Every step writes a span with tokens and ₹.

Latency budget. Where the 6 seconds go:

Latency waterfall: gateway and guardrails 50 ms, follow-up rewrite 400 ms, search 100 ms, rerank 300 ms, model first token at about 1.5 s, streaming finishes at about 5.5 s

Purple bars are model calls. Each one you add costs 300 ms or more, so add the rewrite and the reranker only when an eval shows they help. Streaming hides the long bar: the buyer starts reading at 1.5 s.

Low-level design. The key details:

  • chunks(id, doc_id, section, chunk_hash, tier, doc_type, embedding vector(768), tsv tsvector), with an HNSW index on embedding and GIN on tsv.
  • POST /ask streams Server-Sent Events. Tool writes take an idempotency key.
  • Prompts live in files with a version; each trace records the prompt version and model.
  • The golden set lives next to the code; CI runs the eval when a prompt, model or chunking setting changes.

4. Decisions your team will face

Decision Start with Change when
Model hosting A hosted API behind the gateway Data can't leave, or volume makes a GPU cheaper than the per-token bill
Vector store pgvector in your existing Postgres Millions of vectors, heavy filtering at high query rates, or the database team says no
Framework Hand-rolled, as in the labs Durable pauses, branching or many agents: LangGraph or similar
Router Rules plus one small model call Rules sprawl past a few dozen: a trained classifier
Caching Prompt caching for the fixed system prompt Many repeated, non-personal questions: a semantic cache, with tier in the key
Quality gate A golden set of 50 to 200 cases in CI Real traffic shows new failure types: add them from traces every week

5. What the labs don't cover

  • Serving at scale: GPU sizing, vLLM, continuous batching, KV-cache memory. The envelope above tells you when you need them.
  • Multi-tenant isolation: per-customer keys, limits and data separation across many companies.
  • Model upgrades: pinning versions and re-running every eval before a provider's new model goes live.
  • Data residency and audit: where prompts and traces are stored, and for how long.

6. How deep to go, by experience

You are Do this with this page
Early career (1 to 4 years) Read section 1 and find each box in code you've run. Skip the rest for now.
Mid to senior engineer (4 to 10 years) Sections 1 to 3. Redo the envelope for a feature you own.
Architect or lead (10 years and more) All of it. Use section 2 as the review template for every AI design doc, and For architects for context, frameworks and fine-tuning.
Engineering leader Sections 2 and 4. Ask every team for their NFR table and envelope before approving a build.

Same pattern, other industries

Industry Use case What changes
Banking Loan-policy assistant Approval is regulated; every answer needs a citation and an audit trail
Healthcare Clinical guideline Q&A Fail closed by default; a clinician signs off; PII never reaches a hosted model
Logistics Shipment-status agent Mostly tools, little RAG; latency matters more than wording
Retail (B2C) Shopping assistant 100× the volume, so caching and a small model carry most traffic

Going deeper

Topic What it solves Search terms
LLM serving Many users on one GPU vLLM PagedAttention, continuous batching
AI gateways Limits, fallback and cost across providers LiteLLM proxy, AI gateway rate limiting
Capacity planning Sizing GPUs from tokens LLM throughput tokens per second per GPU
Semantic caching Skipping repeated model calls semantic cache LLM, GPTCache
Model routing Small model first, big model when needed LLM cascade, model routing

Try it: redo the envelope for the WhatsApp agent: 2,000 stores, 6 messages a day each, measured tokens from its traces. Time qwen3:8b with ollama run qwen3:8b --verbose (it prints the eval rate in tokens a second) and work out how many Macs you'd need.

Next: the glossary, for every term on this page.