System design concepts · Specialized Building Blocks

Designing AI-Powered Systems: LLM Serving, RAG and Vector Search

Large language models turned "add AI" into a system design problem. The model is just one box. Retrieval, serving, latency, cost, safety and evaluation are where the design actually happens.

What you'll be able to explain
  • Explain embeddings, vector search and hybrid retrieval at a system level
  • Design a RAG pipeline end to end, including ingestion, permissions and evaluation
  • Reason about LLM serving: tokens, latency, batching, GPUs and streaming
  • Cut cost and latency with caching, routing and smaller models
  • Add guardrails, observability and evaluation to an AI feature

The new building blocks

Block What it does Think of it as
LLM Generates text (or code, or tool calls) from a prompt A very capable, slow, expensive, occasionally wrong function
Embedding model Turns text, images or items into vectors of meaning A coordinate system where similar things sit close together
Vector index Finds the nearest vectors to a query, approximately A search engine for meaning
Prompt / context builder Assembles instructions, retrieved facts and history The briefing you hand to the model
Tools / function calls Let the model call your APIs (search orders, book a slot) Giving the assistant hands, carefully
Guardrails Filter inputs and outputs for safety, policy and format A bouncer and an editor
Evaluator Measures answer quality on test sets and live traffic Unit tests for fuzzy behaviour
Analogy

An LLM is a brilliant new hire with no access to your company wiki and a tendency to bluff when unsure. RAG hands them the right pages before each question. Tools let them look things up in your systems. Guardrails are the compliance review. Evaluation is the performance review that tells you whether any of it is working.

Embeddings and vector search, quickly

An embedding is a list of numbers (often 384–3,072 of them) representing meaning. "How do I reset my password?" and "forgot login credentials" land close together even though they share no words. Similarity is usually cosine similarity or dot product.

Comparing a query with every stored vector is exact but slow beyond a few million. Approximate nearest neighbour (ANN) indexes trade a little recall for big speedups:

Index Idea Strengths Costs
HNSW Layered "small world" graph; greedy walk toward the query Excellent recall and latency Memory-hungry; slower inserts
IVF Cluster vectors; search only the closest clusters Less memory; tunable Recall depends on clusters probed
PQ / quantisation Compress vectors into short codes 4–30× less memory Lower precision; re-rank needed
DiskANN-style Graph index mostly on SSD Billions of vectors on one machine More engineering

Memory maths: 100 million vectors × 768 dimensions × 4 bytes ≈ 307 GB raw, before index overhead. Quantising to 1 byte per dimension cuts it to ~77 GB. This is why vector search at scale is often a memory and sharding problem.

Hybrid retrieval

Pure vector search misses exact matches (order IDs, error codes, product SKUs); pure keyword search misses paraphrases. Production systems run both (BM25 keyword + vector), merge the results (for example with reciprocal rank fusion), then apply a re-ranker: a slower, more accurate model that re-scores the top 50–100 candidates.

RAG end to end

Retrieval-augmented generation (RAG) answers questions from your data: retrieve relevant passages, put them in the prompt, and ask the model to answer only from them, citing sources.

OBJECT STORESourcesdocs, tickets, wikiWORKERIngest workersparse, clean, chunkEXTERNALEmbedding modelDATABASEVector + keyword indexwith ACL metadataCLIENTUserSERVICEAssistant serviceWORKERRe-rankerEXTERNALLLMvectors + metadataquestionhybrid search + permission filtertop 50 → top 6instructions + context + question
RAG has two halves: an offline ingestion pipeline and an online query path.

Ingestion (offline)

  1. Connectors pull documents from sources, ideally via change events so the index stays fresh (Stream Processing and Change Data Capture (CDC) Explained).
  2. Parse and clean: extract text from PDFs and HTML, drop boilerplate, keep headings.
  3. Chunk: split into passages of a few hundred tokens with some overlap, respecting section boundaries. Chunks too small lose context; too large dilute relevance and waste prompt space.
  4. Embed each chunk; store the vector with metadata: source, URL, timestamps, tenant, and access-control lists.
  5. Re-index when the embedding model changes: every vector must come from the same model as the query embedding, so model upgrades mean a full re-embed (plan it like a migration).

Query (online)

  1. Optionally rewrite the question (resolve "it" from chat history, expand acronyms).
  2. Retrieve with hybrid search, filtered by the user's permissions inside the query.
  3. Re-rank and keep the best few chunks within the token budget.
  4. Generate with instructions such as "answer only from the sources; say you don't know otherwise; cite sources".
  5. Post-process: check citations, apply output guardrails, stream to the user.
Common trap

Filtering permissions after retrieval or, worse, trusting the model to "not mention" restricted documents. If a chunk reaches the prompt, assume it can reach the user. Enforce access control as a filter in the index query, exactly like a tenant_id filter in SQL.

Serving LLMs: tokens are the unit of everything

Models read and write tokens (roughly ¾ of an English word). Cost, latency and limits are all measured in tokens.

  • Time to first token (TTFT): how long until the answer starts appearing. Dominated by processing the prompt ("prefill").
  • Tokens per second (TPS): how fast the rest streams ("decode"). A 500-token answer at 50 TPS takes 10 seconds.
  • Context window: the maximum tokens of prompt plus output. Long prompts are slower and costlier.

That's why chat products stream responses (SSE or WebSockets, Long Polling vs WebSockets vs Server-Sent Events): the user sees progress after the TTFT instead of waiting for the full answer.

Self-hosting vs API

Hosted API Self-hosted open model
Time to launch Hours Weeks
Quality ceiling Highest-end models Good and improving; smaller models
Cost model Per token Per GPU-hour, whether busy or not
Data control Provider terms Full
Ops burden Low High: GPUs, scaling, upgrades

If you self-host, the serving tricks that matter:

  • Continuous batching: GPU throughput comes from processing many requests together; modern servers (vLLM, TGI, TensorRT-LLM) add and remove requests from the batch at every step.
  • KV cache: the model's memory of the processed prompt. It's large (often gigabytes per long conversation), and managing it (paging, reuse across requests with the same prefix) is the core of serving efficiency.
  • Quantisation: 8-bit or 4-bit weights fit bigger models on fewer GPUs with modest quality loss.
  • Autoscaling on queue depth and tokens in flight, not CPU. GPUs take minutes to start and load weights, so keep warm capacity for peaks.