Skip to the content.

System Design Primer for AI: How to Design Large-Scale LLM, RAG and Agent Systems

A practical guide to designing large-scale AI systems: LLM applications, retrieval-augmented generation (RAG), AI agents, inference serving, caching, evaluation, guardrails and cost control, with Mermaid architecture diagrams, back-of-the-envelope math and worked case studies. It is for software engineers preparing for AI system design interviews and for teams designing production LLM features.

Last reviewed: December 2026. Model names and prices change monthly, so this guide uses formulas and ranges instead; plug in current numbers from your provider or hardware.

Table of Contents

How AI systems differ from classic systems

Concern Classic web system LLM-based system
Correctness Deterministic; unit tests prove behaviour Probabilistic; needs evaluation sets and statistical comparison
Latency Milliseconds per request Seconds; output is generated token by token
Cost driver CPU, storage, bandwidth Tokens (API) or GPU-hours (self-hosted)
Scaling unit Stateless app servers GPUs with large memory; batching determines efficiency
Failure modes Errors, timeouts Plausible but wrong answers, refusals, prompt injection, format errors
Dependencies Libraries you pin Models that providers update or retire
Security Input validation, auth All of that, plus untrusted text that can steer the model

The practical consequence: an AI system design must always include evaluation, cost and latency budgets, guardrails and a plan for model changes, in addition to the usual scalability and reliability concerns.

A framework for AI system design interviews

Use this order and say each step out loud. Spend roughly the time shown in a 45-minute interview.

Step Time What to cover
1. Clarify the use case 5 min Users, tasks, inputs and outputs, languages, quality bar, what “good” means, human-in-the-loop needs
2. Constraints and scale 3-5 min Requests per second, context sizes, latency targets (TTFT and total), budget, data sensitivity, regions
3. Baseline design 5 min Simplest end-to-end flow: prompt + model, or retrieval + model. Get something working on the board
4. Data and retrieval 5-10 min Sources, ingestion, chunking, indexes, freshness, permissions
5. Model choice and serving 5 min API vs self-hosted, model size, routing, batching, caching
6. Evaluation 5 min Offline eval set, metrics, LLM judges, online metrics, regression gates
7. Safety and reliability 5 min Guardrails, prompt injection, fallbacks, rate limits, monitoring
8. Cost and scaling 3-5 min Token math, caching, model cascades, capacity planning
9. Trade-offs and next steps 2-3 min What you would build first, what you would measure, what could go wrong

Questions worth asking at step 1:

Back-of-the-envelope math for LLM systems

Tokens

API cost

cost per request  = input_tokens × input_price + output_tokens × output_price
monthly cost      = requests_per_month × cost per request × (1 + retry_rate) × agent_steps

Example: 1 million requests a month, 3,000 input tokens and 300 output tokens each, single call. If input costs P_in per million tokens and output costs P_out per million tokens, monthly cost is 3,000 × P_in + 300 × P_out (in currency units, since 1M requests × tokens / 1M). Output is usually priced several times higher than input, so verbose outputs matter. Cached input is often discounted; check your provider.

GPU memory for self-hosting

weights memory ≈ parameters × bytes_per_parameter
  16-bit: 2 bytes   8-bit: 1 byte   4-bit: ~0.5 byte

KV cache per token ≈ 2 × layers × kv_heads × head_dim × bytes_per_value
KV cache total     ≈ KV per token × tokens in flight (sum over all concurrent sequences)

Worked examples:

Model shape Weights (16-bit) KV cache per token (16-bit) KV for one 8k-token sequence
7B parameters, 32 layers, 32 KV heads, head dim 128 (no GQA) ~14 GB 2 × 32 × 32 × 128 × 2 B = 512 KB ~4 GB
8B parameters, 32 layers, 8 KV heads (GQA), head dim 128 ~16 GB 128 KB ~1 GB
70B parameters, 80 layers, 8 KV heads (GQA), head dim 128 ~140 GB 320 KB ~2.6 GB

Takeaways: grouped-query attention cuts KV memory several times; long contexts and high concurrency are limited by KV cache, not only by weights; a 70B model in 16-bit needs multiple GPUs before any KV cache.

Decode speed bound

During decoding, every token requires reading all (active) weights from GPU memory once per step, shared across the batch:

max single-stream tokens/s ≈ memory_bandwidth / weight_bytes

A GPU with about 3 TB/s of memory bandwidth serving 16 GB of weights tops out near 3e12 / 16e9 ≈ 190 tokens/s for one stream, before overheads. Batching many streams shares those weight reads, so aggregate throughput can be many times higher until compute or KV memory runs out. Quantizing weights to 4-bit roughly quadruples this bound for weight reads.

Latency budget

end-to-end ≈ network + queueing + retrieval + TTFT + output_tokens × time_per_output_token + tool calls
Component Typical range (order of magnitude)
Vector search (ANN, in memory) 1-50 ms
Keyword search 5-50 ms
Cross-encoder reranking of 50 docs 20-200 ms on a GPU, more on CPU
Time to first token 0.2-2 s, growing with prompt length
Output speed Tens to a few hundred tokens/s per stream
Each agent step 1-10 s

Use these as sanity checks, then measure your own stack.

Storage for vector indexes

raw vectors = num_vectors × dimensions × bytes_per_dim

100 million chunks × 1,024 dimensions × 4 bytes (float32) ≈ 410 GB before index overhead. int8 quantization brings that to about 100 GB, binary quantization to about 13 GB (usually with re-scoring on full vectors stored on disk).

Reference architecture

flowchart LR
    U[Client] --> API[API / BFF]
    API --> AUTH[Auth and rate limits]
    AUTH --> ORCH[Orchestrator<br/>workflow or agent loop]
    ORCH --> GIN[Input guardrails]
    ORCH --> RET[Retrieval service]
    RET --> KW[(Keyword index)]
    RET --> VEC[(Vector index)]
    RET --> RR[Reranker]
    ORCH --> MEM[(Memory store)]
    ORCH --> TOOLS[Tools / MCP servers]
    ORCH --> GW[AI gateway<br/>routing, caching, fallbacks]
    GW --> P1[Model provider A]
    GW --> P2[Model provider B]
    GW --> SH[Self-hosted inference]
    ORCH --> GOUT[Output guardrails]
    GOUT --> API
    ORCH -. traces .-> OBS[(Tracing and logs)]
    OBS --> EVAL[Online evals and dashboards]
    ING[Ingestion pipeline] --> KW
    ING --> VEC

Read it as three planes:

  1. Request path: auth → orchestrator → retrieval and tools → gateway → model → guardrails → response.
  2. Data plane: ingestion pipelines keep indexes and memory fresh and permission-aware.
  3. Feedback plane: traces, user feedback and evals measure quality and drive improvements.

Building blocks

Model access: API vs self-hosted

Factor Hosted API Self-hosted open-weight model
Model quality ceiling Highest available models Strong open models, usually behind the frontier on the hardest tasks
Time to start Minutes Days to weeks (GPUs, serving, ops)
Cost model Per token; scales linearly GPU-hours; cheaper per token at high, steady utilisation
Data control Depends on provider terms and region options Full control
Customisation Prompting, some fine-tuning options Any fine-tuning, quantization, custom decoding
Latency control Shared infrastructure, rate limits Dedicated capacity, tunable batching
Operational burden Low High: capacity, upgrades, monitoring, on-call

Many production systems are hybrid: hosted frontier models for hard requests, self-hosted small or fine-tuned models for high-volume simple ones.

AI gateway

A gateway sits between your services and every model endpoint.

flowchart LR
    S1[Service A] --> G[AI gateway]
    S2[Service B] --> G
    G -->|policy: route| R{Router}
    R -->|easy| SM[Small model]
    R -->|hard| LG[Large model]
    R -->|provider down| FB[Fallback provider]
    G --> C[(Response / prompt cache)]
    G --> M[(Usage and cost metrics)]

Responsibilities: one API for many providers, authentication and per-team keys, rate limits and quotas, retries with backoff, fallbacks, caching, logging and cost attribution, and policy (which teams may use which models, data residency).

Decision Options Guidance
Search type Keyword (BM25), vector, hybrid Hybrid with rank fusion is the safest default
Index Flat, HNSW, IVF, IVF-PQ, disk-based HNSW for speed in RAM; quantized or disk-based for very large corpora
Store Vector extension in your database, dedicated vector DB, search engine with vectors Start with what you already operate; move when scale or features demand it
Reranking None, cross-encoder, LLM reranker Rerank the top 20-100 with a cross-encoder for a large quality gain
Filtering Post-filter, pre-filter, filtered ANN Permissions and tenant filters must be enforced in the query, never by the model

Caching layers

Cache Key Saves Risk
Exact response cache Hash of model + prompt + parameters Full call cost and latency Stale answers; must exclude personalised prompts
Semantic cache Embedding of the query, similarity threshold Calls for paraphrased questions Wrong answer for similar-but-different questions
Provider prompt cache Byte-identical prompt prefix Input token cost and TTFT Only helps if stable content comes first
Self-hosted prefix (KV) cache Shared token prefix Prefill compute GPU memory pressure
Retrieval cache Normalised query Search latency Staleness after index updates
Embedding cache Content hash Re-embedding unchanged documents None significant

Design rule: put stable content (system prompt, tool definitions, shared documents) at the start of prompts so prefix caches hit.

Orchestration: workflows and agents

flowchart TB
    subgraph Workflow["Workflow (fixed path)"]
        A1[Classify request] --> A2[Retrieve] --> A3[Generate] --> A4[Validate]
    end
    subgraph Agent["Agent (model chooses path)"]
        B1[Model decides next action] -->|tool call| B2[Execute tool]
        B2 --> B3[Observe result]
        B3 --> B1
        B1 -->|done| B4[Final answer]
    end
Pattern When to use
Single call Classification, extraction, simple Q&A
Prompt chain Fixed multi-step tasks (extract → analyse → write)
Router Different request types need different pipelines or models
Parallel fan-out Independent subtasks (summarise many documents) then aggregate
Evaluator-optimizer loop Generate, critique against criteria, revise; for tasks with clear quality checks
Agent loop Steps cannot be known in advance (research, coding, troubleshooting)
Orchestrator with sub-agents Large tasks with separable parts needing isolated context

Prefer the simplest pattern that works. Agents add cost, latency and unpredictability.

Memory

Memory type Holds Implementation
Working memory The current conversation and task state The context window; summarise when long
Episodic Past interactions and outcomes Logged sessions with summaries, searchable
Semantic Durable facts about users or the world Key-value or vector store with timestamps and sources
Procedural How to do tasks Prompts, tool docs, skills loaded on demand

Design concerns: what to write (extract facts, not transcripts), conflict resolution (newer facts win, with provenance), retrieval (relevance plus recency), user control (view and delete), and privacy.

Guardrails

flowchart LR
    IN[User input] --> G1{Input checks<br/>policy, PII, injection heuristics}
    G1 -->|blocked| R1[Refuse or route to human]
    G1 -->|ok| M[Model + tools]
    M --> G2{Output checks<br/>schema, PII, toxicity, groundedness}
    G2 -->|fail| FIX[Retry, repair or fallback]
    G2 -->|ok| OUT[Response]
    M --> G3{Action checks<br/>allow-list, approval}
    G3 -->|needs approval| H[Human approval]

Layer cheap checks (regex, schema validation, allow-lists) before expensive ones (classifier models, LLM judges). Guardrails reduce risk but never replace least-privilege permissions.

Evaluation

flowchart LR
    DS[(Eval datasets<br/>golden + failures)] --> RUN[Eval runner]
    CFG[Prompt / model / retrieval config] --> RUN
    RUN --> GR[Graders<br/>code checks, LLM judge, human review]
    GR --> REP[Report and diff vs baseline]
    REP -->|pass| DEP[Deploy canary]
    REP -->|fail| FIXX[Fix]
    DEP --> ON[Online metrics + sampled judging]
    ON -->|new failures| DS

Metrics by system type:

System Offline metrics Online metrics
RAG Q&A Retrieval recall@k, faithfulness, answer correctness, citation accuracy Thumbs up/down, follow-up rate, escalation rate
Extraction Field-level precision and recall, schema validity Manual correction rate
Agent Task success rate, steps, cost, policy violations Completion rate, user interventions
Chat assistant Rubric scores, pairwise preference Retention, conversation length, feedback
Classification Precision, recall, F1 per class Override rate by human reviewers

Observability

Trace every request as a tree of spans: retrieval, each model call (model, version, tokens, latency, cost), each tool call, guardrail decisions. Attach the prompt template version and user feedback to the trace. OpenTelemetry-based instrumentation lets you send traces to general observability backends or LLM-specific tools.

Dashboards to build first: request volume, p50/p95 latency and TTFT, error and fallback rates, tokens and cost per feature, guardrail block rates, quality scores on sampled traffic.

Designing RAG at scale

flowchart TB
    subgraph Ingestion
        SRC[Sources: docs, wiki, tickets, PDFs] --> CDC[Change detection]
        CDC --> PARSE[Parse and clean<br/>layout-aware]
        PARSE --> CHUNK[Chunk + enrich<br/>titles, headings, ACLs]
        CHUNK --> EMB[Embed in batches]
        EMB --> VIDX[(Vector index)]
        CHUNK --> KIDX[(Keyword index)]
    end
    subgraph Query
        Q[Question] --> REWRITE[Rewrite / expand]
        REWRITE --> HY[Hybrid search with ACL filter]
        VIDX --> HY
        KIDX --> HY
        HY --> RERANK[Rerank top-N]
        RERANK --> PROMPT[Assemble prompt<br/>top-k chunks with IDs]
        PROMPT --> LLM[Generate with citations]
        LLM --> VERIFY[Citation and groundedness check]
    end

Key decisions:

Decision Questions to answer
Chunking Natural boundaries? Size and overlap tuned on retrieval metrics? Parent-child retrieval?
Enrichment Add title, section path, summary, date and permissions to each chunk?
Freshness Event-driven updates or scheduled crawls? How are deletions propagated?
Permissions ACL metadata per chunk, filtered at query time, tested for leaks?
Query understanding Rewriting, multi-query, routing to SQL or other tools for aggregate questions?
Context assembly How many chunks? Order (best at the start or end)? Deduplication?
Answer policy Must cite? Abstain when unsupported? Show sources to users?

Scaling notes:

Designing agents

sequenceDiagram
    participant U as User
    participant O as Orchestrator
    participant M as Model
    participant T as Tools (sandboxed)
    participant H as Human approver
    U->>O: Task
    loop until done or limits reached
        O->>M: Context + tools + state
        M-->>O: Tool call (name, args)
        alt sensitive action
            O->>H: Request approval
            H-->>O: Approve / reject
        end
        O->>T: Execute with scoped credentials
        T-->>O: Result (treated as untrusted data)
        O->>O: Persist state, check budgets
    end
    O-->>U: Result + summary of actions

Agent design checklist:

Inference serving deep dive

flowchart LR
    LB[Load balancer<br/>prefix-aware routing] --> Q
    LB --> R2[Replica 2]
    LB --> R3[Replica N]
    subgraph REP1[Replica 1: inference server]
        Q[Request queue] --> SCH[Scheduler<br/>continuous batching]
        SCH --> PRE[Prefill]
        SCH --> DEC[Decode]
        PRE --> KV[(Paged KV cache)]
        DEC --> KV
    end
    AS[Autoscaler<br/>queue depth, tokens/s] -.-> LB
Technique What it improves Cost or caveat
Continuous batching Throughput, GPU utilisation Slightly higher per-request latency at high load
Paged KV cache Concurrency (less fragmentation) Built into modern servers
Prefix caching TTFT and cost for shared prefixes Needs prefix-aware routing across replicas
Quantization (8-bit, 4-bit, FP8) Memory, speed Possible quality loss; evaluate
Speculative decoding Single-stream latency Extra draft compute; gains depend on acceptance rate
Tensor parallelism Fits large models, lowers latency Needs fast GPU interconnect
Pipeline parallelism Fits very large models across nodes Pipeline bubbles, higher latency
Disaggregated prefill/decode Predictable latency at scale Complexity, KV transfer cost
Multi-LoRA serving Many fine-tunes on one base model Adapter swapping overhead
Autoscaling Cost Cold starts from loading large weights; keep warm capacity

Autoscaling signals that work: queue length, pending tokens, KV cache utilisation and tokens per second, rather than CPU utilisation.

Reliability patterns

Problem Pattern
Provider outage or 5xx Fallback to another provider or self-hosted model via the gateway
Rate limits (429) Exponential backoff with jitter, request queues, quota-aware scheduling
Slow responses Timeouts per step, streaming, hedged requests for short calls
Invalid structured output Constrained decoding, schema validation, repair retry with the error message
Long-running jobs Durable workflows with checkpoints; idempotent steps
Model update changes behaviour Pin model versions, eval before upgrade, canary rollouts
Retrieval service down Degrade to answering without retrieval only when safe, or show a clear message
Runaway agent Step, token and cost budgets; kill switch

Cost engineering

Levers, roughly in order of impact for most products:

  1. Right-size the model. Route easy requests to smaller models; reserve large ones for hard requests (a cascade or router).
  2. Shrink prompts. Fewer, better retrieved chunks; compact tool definitions; summarised history.
  3. Cap and shape outputs. Ask for concise answers; set max tokens; use structured outputs instead of prose where possible.
  4. Cache. Prompt caching for stable prefixes, response caches for repeated questions.
  5. Batch offline work. Use batch endpoints or off-peak self-hosted capacity for non-interactive jobs.
  6. Fine-tune or distil a small model for high-volume narrow tasks once you have data and evals.
  7. Self-host when volume is high and steady enough to keep GPUs busy.

Cascade example:

flowchart LR
    Q[Request] --> S[Small model]
    S --> C{Confident and<br/>passes validation?}
    C -->|yes| OUT[Return]
    C -->|no| L[Large model]
    L --> OUT

Track cost per successful task, not cost per call; cheaper models that fail more can cost more overall.

Security and privacy

Threat Mitigation
Direct prompt injection Clear instruction hierarchy, input checks, never rely on the system prompt for security
Indirect prompt injection (in documents, web pages, emails) Treat tool and retrieval output as untrusted; least-privilege tools; approvals; restrict outbound requests
Data exfiltration via links or images Allow-list domains, strip query parameters with user data, do not auto-load model-generated URLs
Cross-tenant leakage ACL filters in retrieval, tenant-scoped caches and memory, isolation tests
Sensitive data sent to providers Redaction, data processing agreements, regional endpoints, self-hosting for the most sensitive data
Unsafe output rendered or executed Treat output as untrusted: escape HTML, validate SQL and code, sandbox execution
Supply chain (models, weights, packages) Use safe weight formats, pin and verify artifacts, scan dependencies
Abuse and cost attacks Auth, rate limits, per-user budgets, anomaly alerts

The OWASP Top 10 for LLM Applications is a useful checklist for threat modelling.

Case studies

1. Customer support assistant

Requirements: answer customer questions from help-center articles and account data; 2,000 requests per minute at peak; first token under 1.5 s; escalate to humans; never reveal another customer’s data.

flowchart LR
    C[Customer] --> API
    API --> CL[Intent classifier<br/>small model]
    CL -->|FAQ| RAG[RAG over help center]
    CL -->|account question| TOOLS[Account tools<br/>scoped to this customer]
    CL -->|angry / legal / unsure| HUMAN[Human agent queue]
    RAG --> GEN[Answer with citations]
    TOOLS --> GEN
    GEN --> GUARD[Output checks]
    GUARD --> C

Design notes:

2. Enterprise search over 50 million documents

Requirements: employees search and ask questions across wikis, drives and tickets; strict per-document permissions; updates visible within 15 minutes.

Key choices:

3. Coding agent

Requirements: an agent that takes an issue, edits a large repository and opens a pull request that passes CI.

flowchart TB
    ISSUE[Issue] --> PLAN[Plan steps]
    PLAN --> SEARCH[Search code<br/>lexical + symbols + embeddings]
    SEARCH --> EDIT[Edit files in sandbox]
    EDIT --> TEST[Run tests, linters, type checks]
    TEST -->|fail| EDIT
    TEST -->|pass| REVIEW[Self-review diff]
    REVIEW --> PR[Open pull request for human review]

Design notes:

4. Document extraction pipeline

Requirements: extract 30 fields from 1 million invoices a month into a database, with 99% field accuracy after review.

5. Internal LLM platform

Requirements: 40 internal teams need model access with cost visibility, compliance controls and shared evaluation.

flowchart TB
    T1[Team apps] --> GW[AI gateway<br/>auth, quotas, routing, logging]
    GW --> EXT[External providers]
    GW --> SERVE[Self-hosted serving cluster<br/>multi-LoRA, autoscaling]
    GW --> OBS[(Usage, cost, traces)]
    REG[Model and prompt registry] --> GW
    EVALS[Shared eval service] --> REG
    POL[Policy: allowed models, data classes, regions] --> GW

6. Real-time voice assistant

Requirements: spoken conversation with responses starting within about one second.

flowchart LR
    MIC[Audio in] --> VAD[Voice activity detection]
    VAD --> STT[Streaming speech-to-text]
    STT --> LLM[LLM streaming tokens]
    LLM --> TTS[Streaming text-to-speech]
    TTS --> SPK[Audio out]
    VAD -. barge in .-> TTS

Tool landscape

Examples of widely used open-source projects by layer. This is not an endorsement or a complete list; check each project’s licence and maintenance before adopting it.

Layer Open-source examples
Inference servers vLLM, SGLang, Text Generation Inference, TensorRT-LLM, llama.cpp, Ollama
Vector search pgvector, Qdrant, Milvus, Weaviate, Chroma, LanceDB, FAISS, Vespa, OpenSearch
Orchestration and agents LangGraph, LlamaIndex, DSPy, Pydantic AI, OpenAI Agents SDK, CrewAI, AutoGen
Gateways LiteLLM, Portkey Gateway, Envoy AI Gateway
Observability Langfuse, Arize Phoenix, OpenLLMetry, Opik, OpenLIT
Evaluation promptfoo, Ragas, DeepEval, Inspect, lm-evaluation-harness
Guardrails and security testing NeMo Guardrails, Guardrails AI, LLM Guard, Presidio, garak, PyRIT
Structured output Instructor, Outlines
Document parsing Docling, Unstructured, MarkItDown
Memory Mem0, Letta
Durable workflows Temporal
Graph-based RAG GraphRAG

Trade-off cheat sheet

Choice Option A Option B Decide by
Knowledge RAG Fine-tuning Does knowledge change or need citations (RAG) or is it behaviour/style (fine-tune)?
Control flow Workflow Agent Are the steps known in advance?
Model Large general Small specialised Quality on your evals vs cost and latency at your volume
Hosting API Self-hosted Volume, data control, team skills
Context Long context Retrieval Cost per request, latency, how much is relevant
Search Vector only Hybrid Do queries contain IDs, names or exact terms?
Freshness Batch re-index Streaming updates How stale can answers be?
Output Free text Structured Will code consume it?
Safety Model refusals External guardrails + permissions Impact of a failure
Evaluation LLM judge Human review Cost vs need for nuance; calibrate judges on human labels

Common interview mistakes

FAQ

How is AI system design different from classic system design interviews? The classic topics (APIs, databases, caching, queues, scaling) still matter, but interviewers also expect you to discuss model choice, retrieval, evaluation, guardrails, token economics and GPU constraints.

Do I need to know GPU internals? You should understand memory as the main constraint (weights plus KV cache), batching, and quantization at the level of the formulas above. Deep kernel knowledge is only needed for inference-engineering roles.

Which vector database should I pick in an interview? Name the requirements first (scale, filtering, hybrid search, operations), then pick. “PostgreSQL with a vector extension until we exceed X, then a dedicated vector store” is a reasonable, defensible answer for many cases.

How do I talk about evaluation convincingly? Describe the dataset (where it comes from, how big, how it grows), the metrics per stage, how LLM judges are calibrated, the CI gate, and the online metrics you would watch after launch.

Should every AI system be an agent? No. Most production value comes from well-designed workflows: retrieval, a model call, validation. Use agents where flexibility clearly pays for the extra cost and risk.

How do I prepare in one week? Read this guide once, then design three systems out loud with a timer (a RAG assistant, an agent, and a serving platform), and do the back-of-the-envelope math for each.

Where to go next

Contributing

PRs are welcome. Keep entries accurate: back up numbers with a formula or source, keep diagrams in Mermaid so they render on GitHub, avoid vendor marketing claims, and prefer durable guidance over model names and prices that go stale.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.