AI system design · Token budgets, semantic cache

How to design a RAG pipeline

Retrieval-augmented generation (RAG) is classic system design in new units: tokens instead of requests, quotas instead of CPU, cost per answer instead of cost per server. This one is sized for 10 million documents, with permissions and citations.

Updated · 5 min read

The two planes meet only at the indexes. Ingestion runs async from the queue; the query path goes gateway, guardrail, retriever, reranker, model.

RAG Pipeline architecture diagram

The two planes meet only at the indexes. Ingestion runs async from the queue; the query path goes gateway, guardrail, retriever, reranker, model.

The short version

  • Ingestion is throughput capped by the embedding quota; query is latency to first token. They share storage and nothing else.
  • Skip unchanged chunks with an embedding cache keyed by content hash plus model ID.
  • Filter permissions inside retrieval, and scope the semantic cache by tenant and permission set.
  • Fuse vector and BM25 results by rank, rerank, and send the model 4 to 8 good chunks.

Clarifying questions to ask first

  • Corpus size and churn? (Assume 10 million documents, some scanned, about 1% edited daily.)
  • How fresh must answers be? (Assume an edit or delete shows within 5 minutes.)
  • Can every user read every document? (Assume not. Permissions become part of retrieval.)
  • What load and latency? (Assume 100 questions/s at peak, 30 on average, first token within about 2 seconds, with citations.)

Numbers that shape the design

Interview assumptions. Prices and latencies come from this site's model catalogue.

QuantityAssumptionResult
Chunks10M documents × ≈ 10 chunks of ≈ 400 tokens≈ 100M chunks, ≈ 40B tokens
First full embed$0.02 per million tokens (Titan Text Embeddings V2)≈ $800, once
Backfill time2M tokens a minute, the simulator's default quota≈ 14 days
Daily churn≈ 2 of 10 chunks change per edited document≈ 200,000 chunks a day; ≈ 1M with no hash cache
Cost per answer≈ 2,000 tokens in, ≈ 300 out on Nova 2 Lite≈ $0.00135
Monthly answers30 answers/s average≈ 78M answers ≈ $105,000 a month
HNSW index100M × 1.1 × (4 × 1,024 + 8 × 16) bytes≈ 465 GB per copy

Generation is where the money goes: every 10 points of semantic cache hit rate saves about $10,500 a month. For latency, the question embedding (≈ 200 ms) and Nova 2 Lite's first token (≈ 1,100 ms) leave ≈ 700 ms of the 2-second target for everything else; streaming hides the rest of the answer at 174 tokens/s.

API

POST /v1/answers   { "question": "What is the refund window for annual plans?", "stream": true }
→ 200 text/event-stream
event: meta      data: {"trace_id": "t_91", "cache": "miss"}
event: token     data: {"text": "Annual plans can be refunded "}
event: citation  data: {"n": 1, "doc_id": "d_42", "chunk_id": "d_42#v7#3"}
event: done      data: {"input_tokens": 2004, "output_tokens": 287}
→ 429 { "error": "token_budget_exhausted", "retry_after_s": 3600 }

POST   /v1/documents   { "doc_id": "d_42", "version": 7, "uri": "s3://raw/d_42/7", "acl": ["g_finance"] }  → 202
DELETE /v1/documents/d_42  → 202
POST   /v1/feedback    { "trace_id": "t_91", "rating": "down", "reason": "wrong_source" }

Every document write carries a version, so retries and out-of-order events are harmless.

Data model

documents       doc_id, tenant_id, current_version, acl_groups[], status, raw_uri
chunks          chunk_id = doc_id#version#ordinal, text, content_hash, heading_path, acl_groups[]
embedding_cache (content_hash, embedding_model_id) → vector
vector index    chunk_id → vector (HNSW) + tenant_id, acl_groups, doc_id, version
keyword index   chunk_id → text (BM25)  + the same filter fields
semantic_cache  (tenant_id, acl_set_hash) + question vector → answer, cited (doc_id, version)[]

The chunk store is the truth. Both indexes and the cache can be rebuilt from it.

High-level design

Ingestion scales on queue depth and quota; query scales on concurrent streams, so a query spike never slows indexing. The question is embedded once, for both the cache lookup and retrieval.

Ingestion: chunking, quota and versions

Store parsed text per version; OCR is the slowest, flakiest step and gets its own workers. Chunk on headings, paragraphs and whole tables, capped at a few hundred tokens with 10-20% overlap. Prepend the title and heading path to each chunk, and tag it with tenant, ACL groups and version.

All embed workers share one rate limiter. AWS's Bedrock docs say embedding models are throttled by requests per minute, not tokens. On a 429, back off with jitter and requeue. Live edits get a high-priority lane; backfills get leftover quota. The RAG ingestion challenge puts this under load: 10,000 PDFs against a quota that won't be raised.

Vector and keyword writes aren't one transaction, so make each an idempotent upsert by chunk_id and reconcile counts per document. For a new version, write v8's chunks, flip current_version, delete v7's. Mark deletes first so queries filter at once.

Vector index

HNSW (Malkov and Yashunin) gives high recall at low latency but lives in memory: about 465 GB per copy here, using OpenSearch's estimate. At 256 dimensions the same formula gives about 127 GB; measure the recall you lose first. IVF uses less memory at some cost in recall or latency. At an assumed 64 GB of RAM per node, that's 16 nodes with a replica.

Gateway and semantic cache

Budget tokens, not requests. Reserve prompt plus max_tokens and refund the rest, as Bedrock does for its own quota, so keep max_tokens near the real answer length.

In the semantic cache, "refund window for annual plans" and "for monthly plans" sit close with different answers, so set the threshold from labelled near-miss pairs and start strict. Invalidate an answer when a document it cited changes. Personal questions skip the cache.

Guardrail, retrieval and reranking

A small model screens the question in parallel with retrieval. Retrieved text can carry instructions too, so chunks never trigger tools.

Vector search catches paraphrase; BM25 catches exact names, error codes and SKUs. Take about 50 from each and fuse by rank: reciprocal rank fusion scores each chunk as the sum of 1 / (k + rank), with k = 60 in Cormack, Clarke and Büttcher (SIGIR 2009), also Elasticsearch's default. A cross-encoder then reranks the 50 and keeps 4 to 8; if it times out, use the fused order.

Evaluation and cost caps

On a golden set, measure retrieval (recall@k, MRR), generation (faithfulness and relevance, by an LLM judge checked against human labels) and citations separately, and block releases on regressions. Cap cost per user, per tenant and globally, and near a cap degrade in steps: fewer chunks, a smaller model, cache-only, refuse. The RAG pipeline challenge tests this against a token quota and a monthly budget.

Common traps

  • Filtering permissions after retrieval. If a user can read 1% of the corpus, the unfiltered top 50 may hold nothing they can see.
  • Chunking on fixed token offsets. One sentence added near the top shifts every later chunk and changes every hash.
  • Letting a backfill or model migration eat the whole embedding quota while live edits wait days.
  • Reusing vectors after changing the embedding model. Rebuild from stored text and switch an alias.
  • Trusting a plausible citation without checking that the passage supports it.

Frequently asked questions

What is reciprocal rank fusion in hybrid search?

+

It merges ranked lists from retrievers such as vector search and BM25 using only ranks. That avoids comparing scores on different scales.

RAG or fine-tuning?

+

RAG for facts that change and need citations and permissions; fine-tuning for style and format. They combine.

How much memory does a vector index need?

+

OpenSearch estimates HNSW at 1.1 × (4 × dimension + 8 × m) bytes per vector. That's about 465 GB per copy for 100 million 1,024-dimension vectors.

Now fix it yourself.

Run the design under real traffic and see what breaks first. No signup.