Retrieval-Augmented Generation (RAG) Questions
Grounding language-model outputs in external knowledge at inference time. Covers document ingestion, chunking and embedding, sparse, dense and hybrid retrieval (BM25, score fusion, contrastive training of retrievers), vector search and approximate-nearest-neighbour index engineering (HNSW, IVF, product quantization, filtering, updates, sharding), re-ranking with cross-encoders, and context assembly with prompt templates and citations. Also covers reducing hallucination through verification and abstention, evaluating retrieval-augmented systems, and production concerns such as freshness, access control, prompt injection through retrieved documents, deletion and privacy, caching, cost, and weighing retrieval against fine-tuning. Generic LLM evaluation and release gates, the craft of prompts beyond retrieved-context templates, attention internals, parameter-efficient fine-tuning, model serving and distributed inference engineering, database indexes, and whole-product ML system design are covered elsewhere.
Design a RAG system for factual question answering over a very large corpus (hundreds of millions of documents) with a high query rate and a strict tail-latency budget. Describe the index, re-ranking, context selection, generation and how you would scale and cache it.
Sample Answer
Direct answer
Design it as a funnel with a latency budget per stage. A cheap first stage (approximate vector search plus keyword search over a sharded, compressed index) narrows hundreds of millions of documents to a few hundred candidates; a smaller, more expensive stage (a reranker) narrows those to a handful; the generator only sees a token-budgeted context. Compress and shard the index so it fits in memory, replicate shard groups to meet the query rate, cut the p99 (the latency that 99% of requests beat) with per-stage timeouts, batching and caches, and let the system degrade (skip the reranker, return fewer passages, or answer from the quoted passage) before it misses the deadline.
1. Index: size it first
At this scale the sizing decides the design. With the assumed inputs in the program below (300 million documents, 6 chunks per document, 768-dimensional embeddings), there are 1.8 billion chunks. Stored as 32-bit floats each vector is 768 x 4 = 3,072 bytes, so the raw vectors are 1.8 billion x 3,072 bytes, about 5,150 GiB. A graph index also stores neighbour links; the program assumes 128 bytes of links per vector, which lifts the total to about 5,364 GiB of RAM, or 21 machines of 256 GiB before any replica. Compressing the vectors with product quantization (PQ) shrinks the first term. PQ cuts each 768-float vector into 64 sub-vectors of 12 floats; for each sub-vector position it learns 256 representative sub-vectors (a codebook, found by k-means clustering) and stores only the 1-byte number of the nearest one. A vector becomes 64 bytes instead of 3,072 (48 times smaller). To search, compute once per query the distance from each query sub-vector to its 256 codebook entries, then the distance to any stored vector is the sum of 64 table look-ups, with no decompression. The 64 bytes of codes alone come to 1.8 billion x 64 bytes, about 107 GiB; with the same assumed 128 bytes of links per vector the total is 192 bytes per vector, about 322 GiB, which fits on 2 machines of 256 GiB. Full-precision vectors stay on SSD (solid-state disk) and are read only to rescore the top few hundred candidates (recompute their exact distances and reorder them), which recovers most of the accuracy lost to compression.
- Index type. A graph index (HNSW, hierarchical navigable small world: a layered neighbour graph searched greedily) gives high recall at low latency but its links cost memory; an inverted-file index (IVF: vectors grouped into clusters, only the nearest clusters searched) uses less memory and is cheap to build. Both are approximate (ANN, approximate nearest neighbour): they trade recall for speed. Recall@10 is the fraction of the true 10 nearest vectors (found by exact brute-force search) that the approximate search also returns, so 0.93 means 9.3 of the 10 on average. Measure it against exact search on a sample.
- Sharding. Split the chunks across shards (here 8, about 40 GiB of codes and links each) and search them in parallel; merge the per-shard top results. The data alone would fit on 2 machines, so the 8 shards are a latency and throughput choice: each shard scans an eighth of the data, and the machine count in section 5 comes from the query rate, not from the data size. Each shard uses only 16 percent of a 256 GiB machine here, so a real deployment would pack several shard replicas per machine or use smaller machines; 8 is an assumption to tune by load testing. The slowest shard sets the latency, which is why tail latency needs the tactics in section 5.
- Hybrid. Keep a keyword (BM25) index for exact identifiers, product codes and rare terms, and fuse the two result lists (for example reciprocal rank fusion, which adds 1 / (k + rank) across lists).
- Freshness. Keep a small, frequently updated index for new and changed documents beside the large static one, query both, and merge them into the large one in the background.
- Filters. Apply tenant, language and access filters inside the index query, not after retrieval, or the top-k can be filled with documents the user cannot see.
2. Re-ranking
A bi-encoder (embeds query and chunk separately, so chunk vectors can be precomputed) finds candidates; a cross-encoder (reads query and chunk together, so it cannot be precomputed) reorders them. Run the cross-encoder only on a short list, because its cost is candidates times tokens per pair: 50 candidates of about 300 tokens is 15,000 tokens per query, which at 4,000 queries per second is 60 million tokens per second; 20 candidates is 6,000 tokens per query and 24 million per second (all in the run below, under assumed lengths). Choices: fewer candidates, shorter chunks in the pair, a distilled (smaller) reranker, a cheap first-pass score to prune before the expensive one, and a timeout after which the first-stage order is used.
3. Context selection
Take the top few reranked chunks until a token budget is reached, remove near-duplicates, keep each chunk's title, version and date, and order them so the best evidence is not buried in the middle of a long prompt. Fewer, better chunks cost less and distract less than a long list; cap the generated answer length too.
4. Generation, GPU versus CPU, batching, cost control
- Hardware. Run the LLM and a cross-encoder reranker on GPUs (graphics processors, which do the large matrix multiplications these models need efficiently); keep query rewriting, keyword search, fusion and the PQ code scan on CPUs, where memory capacity and cheap scale-out matter. A tiny reranker may run on CPUs if the candidate count is low.
- Batching. GPUs are efficient when many requests are processed together. Use dynamic batching: wait up to a few milliseconds to group requests, with a hard cap, so the wait is a deliberate part of the p99 budget. Continuous batching in the LLM server lets new requests join between generation steps.
- Streaming. Stream tokens so the user's perceived latency is the time to the first token; the budget below allocates time to the first token, not the full answer.
- Cost control. The cost per query is tokens in times the input rate plus tokens out times the output rate, so cap context tokens (here a 30-token question, 5 chunks of 250 tokens and an assumed 100-token instruction make 30 + 1,250 + 100 = 1,380 tokens in, 200 out), route easy or cached questions to a smaller model, and cache the prompt prefix (instructions) if the serving stack supports it.
5. Scale and cache
- Replicas. At 4,000 QPS (queries per second) and an assumed 250 QPS per replica (a figure you would measure with a load test on the real index, hardware and recall setting), 16 replicas of each of 8 shard groups are needed: 128 index machines. Spread replicas over availability zones (separate failure domains) so one zone failing leaves the others serving, and keep spare capacity for hedging.
- Caches. An exact-match query cache keyed on the normalised query (plus the user's access scope) removes repeated work; an embedding cache avoids re-embedding the same text; a result cache for popular passages helps the reranker. In the run, with Zipf-skewed traffic (a Zipf distribution makes the query of popularity rank r about 1 / r^1.1 as frequent as the top one, so a few queries repeat very often; here 50,000 distinct queries, an assumption) a 10,000-entry LRU cache (least recently used entries are evicted first) reaches a hit rate of 0.849 and cuts backend load from 4,000 to about 603 QPS; a 100-entry cache already reaches 0.469. Real hit rates must be measured on real logs. A semantic cache (reusing an answer for a similar, not identical, question) risks serving a wrong answer for a question that differs in a key detail, so gate it with a high similarity threshold and never share it across access scopes.
- Tail latency. Give each stage a timeout; send a hedged request (a duplicate to a second replica after the typical time has passed) for slow shard calls; return partial results if one shard is late; shed load or degrade the pipeline under overload.
Worked example
The sizes, rates and latencies below are assumptions stated in the code, chosen to show the arithmetic; the IVF part is a from-scratch numpy stand-in on synthetic clustered vectors (not a production index), used only to show the recall versus work trade-off of an approximate index. Its nprobe setting is how many of the 64 clusters are searched per query, and the cache part is a simulation under an assumed Zipf query skew.
import os
os.environ["OMP_NUM_THREADS"] = "1"
import math
from collections import OrderedDict
import numpy as np
# ---- 1. sizing (every input is an ASSUMPTION stated here) ----
docs, chunks_per_doc, dim = 300_000_000, 6, 768
chunks = docs * chunks_per_doc
GiB = 2 ** 30
options = {"float32 vectors": dim * 4, "int8 vectors": dim, "PQ codes (64 bytes)": 64}
graph_bytes = 128 # assumed graph-link overhead per vector for a graph index
node_ram = 256 * GiB # assumed usable RAM per index node
print(f"chunks = {chunks:,}")
print("option B/vector vectors only plus links nodes needed")
for name, b in options.items():
total = chunks * (b + graph_bytes)
print(f"{name:22s} {b:6d} {chunks * b / GiB:9.0f} GiB {total / GiB:7.0f} GiB {math.ceil(total / node_ram):8d}")
print(f"PQ: {dim} floats / 64 sub-vectors = {dim // 64} floats each; {dim // 64} x 4 B = {dim // 64 * 4} B becomes 1 B, so {dim * 4} B -> 64 B is {dim * 4 // 64}x smaller")
pq_total = chunks * (options["PQ codes (64 bytes)"] + graph_bytes)
qps, per_replica_qps, shards = 4000, 250, 8 # 8 shards chosen so each shard is searched in parallel
print(f"\nchosen: PQ codes in RAM, full vectors on SSD for rescoring; {shards} shards -> {pq_total / shards / GiB:.0f} GiB of RAM per shard")
print(f"data alone fits on {math.ceil(pq_total / node_ram)} nodes; one shard uses {pq_total / shards / node_ram:.0%} of a node's RAM")
replicas = math.ceil(qps / per_replica_qps)
print(f"\nreplicas of each shard group for {qps} QPS at {per_replica_qps} QPS per replica: {replicas}")
print("index machines = shards x replicas =", shards, "x", replicas, "=", shards * replicas)
budget = {"query rewrite + embed": 40, "ANN search over shards + merge": 60, "keyword search + fusion": 30,
"rerank top 50": 120, "context assembly": 10, "LLM first token": 350, "network + queueing slack": 90}
print("\nassumed p99 budget, ms:", budget, "-> sum", sum(budget.values()))
# ---- 2. rerank and LLM token load (assumed lengths) ----
pair_tokens, cand, ctx_chunks, chunk_tokens, q_tokens, out_tokens, instr_tokens = 300, 50, 5, 250, 30, 200, 100
rerank_tok = cand * pair_tokens
llm_in = q_tokens + ctx_chunks * chunk_tokens + instr_tokens
print(f"\nrerank tokens/query = {cand} x {pair_tokens} = {rerank_tok}; at {qps} QPS = {rerank_tok * qps:,} tokens/s")
print(f"with 20 candidates instead: {20 * pair_tokens} tokens/query = {20 * pair_tokens * qps:,} tokens/s")
print(f"LLM input tokens/query = {q_tokens} + {ctx_chunks} x {chunk_tokens} + {instr_tokens} = {llm_in}, output {out_tokens}; at {qps} QPS = {llm_in * qps:,} in, {out_tokens * qps:,} out tokens/s")
# ---- 3. toy IVF (inverted file) against brute force; synthetic vectors stand in for embeddings ----
rng = np.random.default_rng(0)
n, d, nlist = 20000, 32, 64
centers = rng.normal(size=(nlist, d)) * 3
X = (centers[rng.integers(0, nlist, n)] + rng.normal(size=(n, d))).astype(np.float32)
Q = (centers[rng.integers(0, nlist, 200)] + rng.normal(size=(200, d))).astype(np.float32)
cent = X[rng.choice(n, nlist, replace=False)].copy()
for _ in range(8): # 8 Lloyd iterations: assign points, move centres
a = (np.sum(X ** 2, 1)[:, None] - 2 * X @ cent.T + np.sum(cent ** 2, 1)[None]).argmin(1)
for c in range(nlist):
if (a == c).any():
cent[c] = X[a == c].mean(0)
assign = (np.sum(X ** 2, 1)[:, None] - 2 * X @ cent.T + np.sum(cent ** 2, 1)[None]).argmin(1)
lists = [np.where(assign == c)[0] for c in range(nlist)]
def topk_bf(q, k=10):
return np.argsort(((X - q) ** 2).sum(1))[:k]
def topk_ivf(q, nprobe, k=10):
order = np.argsort(((cent - q) ** 2).sum(1))[:nprobe]
cand_ids = np.concatenate([lists[c] for c in order])
best = cand_ids[np.argsort(((X[cand_ids] - q) ** 2).sum(1))[:k]]
return best, len(cand_ids)
truth = [set(topk_bf(q)) for q in Q]
print("\nnprobe recall@10 fraction of vectors scanned")
for nprobe in (1, 2, 4, 8, 16):
r, sc = [], []
for q, t in zip(Q, truth):
got, m = topk_ivf(q, nprobe); r.append(len(t & set(got)) / 10); sc.append(m / n)
print(f"{nprobe:6d} {np.mean(r):9.3f} {np.mean(sc):8.3f}")
# ---- 4. query cache: Zipf-distributed repeated queries over 50,000 distinct queries, LRU cache ----
def hit_rate(cache_size, seed, n_queries=100_000, universe=50_000, a=1.1):
r = np.random.default_rng(seed)
p = np.arange(1, universe + 1, dtype=float) ** -a # query of popularity rank r drawn with weight 1 / r^a
qs = r.choice(universe, size=n_queries, p=p / p.sum())
cache, hits = OrderedDict(), 0
for x in qs.tolist():
if x in cache:
hits += 1; cache.move_to_end(x)
else:
cache[x] = 1
if len(cache) > cache_size: cache.popitem(last=False)
return hits / n_queries
print("\nLRU hit rate on queries with weight 1 / rank^1.1 over 50,000 distinct queries, mean of 3 seeds:")
for size in (100, 1000, 10000):
h = np.mean([hit_rate(size, s) for s in range(3)])
print(f" cache {size:6d} entries: {h:.3f} -> backend load {qps * (1 - h):.0f} QPS of {qps}")
Output:
chunks = 1,800,000,000
option B/vector vectors only plus links nodes needed
float32 vectors 3072 5150 GiB 5364 GiB 21
int8 vectors 768 1287 GiB 1502 GiB 6
PQ codes (64 bytes) 64 107 GiB 322 GiB 2
PQ: 768 floats / 64 sub-vectors = 12 floats each; 12 x 4 B = 48 B becomes 1 B, so 3072 B -> 64 B is 48x smaller
chosen: PQ codes in RAM, full vectors on SSD for rescoring; 8 shards -> 40 GiB of RAM per shard
data alone fits on 2 nodes; one shard uses 16% of a node's RAM
replicas of each shard group for 4000 QPS at 250 QPS per replica: 16
index machines = shards x replicas = 8 x 16 = 128
assumed p99 budget, ms: {'query rewrite + embed': 40, 'ANN search over shards + merge': 60, 'keyword search + fusion': 30, 'rerank top 50': 120, 'context assembly': 10, 'LLM first token': 350, 'network + queueing slack': 90} -> sum 700
rerank tokens/query = 50 x 300 = 15000; at 4000 QPS = 60,000,000 tokens/s
with 20 candidates instead: 6000 tokens/query = 24,000,000 tokens/s
LLM input tokens/query = 30 + 5 x 250 + 100 = 1380, output 200; at 4000 QPS = 5,520,000 in, 800,000 out tokens/s
nprobe recall@10 fraction of vectors scanned
1 0.930 0.029
2 0.992 0.070
4 1.000 0.146
8 1.000 0.241
16 1.000 0.390
LRU hit rate on queries with weight 1 / rank^1.1 over 50,000 distinct queries, mean of 3 seeds:
cache 100 entries: 0.469 -> backend load 2123 QPS of 4000
cache 1000 entries: 0.692 -> backend load 1234 QPS of 4000
cache 10000 entries: 0.849 -> backend load 603 QPS of 4000
Reading it:
- 1.8 billion chunks: 21 machines of 256 GiB if stored as float32, 6 if int8, 2 with PQ codes (each row adds the assumed 128 bytes of links per vector), which is why compression is the first lever.
- The toy IVF code in four steps. First it builds 20,000 synthetic 32-number vectors around 64 hidden centres. Then 8 Lloyd iterations (the k-means loop: assign every vector to its nearest centre, move each centre to the mean of its vectors) produce 64 cluster centres, and each vector is filed in the list of its nearest centre. At query time
topk_ivfranks the centres by distance to the query, takes the nearestnprobeof them, and measures distances only to the vectors in those lists.topk_bfmeasures the distance to all 20,000 and is the ground truth for recall@10. - The p99 budget adds to 700 ms across seven stages, so any deadline below that sum forces a cut; the LLM's first token and the reranker are the large items, so they are where timeouts and degradation apply.
- The toy IVF scans 2.9% of the vectors at nprobe 1 and gets recall@10 of 0.930, and scans 7.0% at nprobe 2 for 0.992. These numbers belong to this synthetic data only; on real embeddings, tune nprobe (the number of clusters searched) against an exact-search sample.
- The cache cuts backend load roughly in proportion to its hit rate (0.849 leaves about 15 percent of queries, 603 of 4,000 QPS), which depends entirely on how repetitive real traffic is and on how many distinct queries there are.
Trade-offs and common mistakes
- Compression saves memory and loses accuracy; rescoring with full vectors and measuring recall against exact search shows how much.
- More shards reduce per-shard work but raise the chance that one is slow, so tail latency gets worse without hedging and timeouts.
- A larger k or more candidates improves recall and costs reranker and LLM tokens linearly.
- Caching without access scoping leaks documents between users.
- Quoting a latency target without a per-stage budget gives nobody anything to design to.
Design a RAG microservice architecture that separates concerns between retrieval, re-ranking, and generation. Include API boundaries, expected inputs/outputs, batching strategies, and where to put caching and authorization checks.
Sample Answer
Direct answer
Split the request path into an orchestrator (the thin front service that owns the user request) and three backend services, each scaled and deployed on its own: retrieval (query to candidate chunks), reranking (reorder the candidates with a slower, more accurate model), and generation (build the prompt and call the language model). Each boundary carries a versioned request and response schema, a deadline, and the caller's identity (who is asking and what they may read). Authorization is enforced where the data is read (inside the retrieval query), not only at the front door. Caches sit at each stage with keys that include everything that changes the answer, and batching is applied where hardware benefits from it (reranker and embedding calls), not where it only adds waiting time.
Terms
A reranker (often a cross-encoder: a model that reads the query and one passage together and outputs a relevance score) is more accurate than vector similarity but costs one model pass per query-passage pair. Micro-batching means holding requests for a few milliseconds so several can be scored in one model call. Tenant means a customer organisation whose data must stay separate from others. Top-k (top_k) is how many results a caller asks for. Hybrid search combines keyword matching with vector similarity. An access label is a tag stored with each chunk saying who may read it (for example public or internal). Idempotent means repeating a call has the same effect as making it once, so a retry is safe. A semantic cache reuses a stored answer for a question whose meaning is close to an earlier one.
The services and their contracts
- Orchestrator / API gateway. Authenticates the caller, derives an internal identity (tenant, user, roles, group memberships), assigns a request id and a deadline (deadline propagation: a total time budget, for example 800 milliseconds, that each stage subtracts its own time from and passes on as "time remaining", so a late stage knows to skip optional work), calls the services in order, assembles the response, and applies output policies. It is the only component the client talks to.
- Retrieval service.
- Input:
{query, tenant, identity claims, top_k, filters, index_version?}. Output: a list of{chunk_id, doc_id, score, text or pointer, access_label, index_version}, plus the version of the index and embedding model that produced it (index_versionnames the index build, so the same query can be compared across builds). - It embeds the query (an embedding model call, cacheable), runs the approximate nearest-neighbour search, optionally merges keyword search (hybrid), and applies the access filter inside the index query.
- Input:
- Reranking service.
- Input: the query and the candidate list (about 20 to 100 chunks); output: the same chunk ids with new scores and the reranker version. It is stateless and GPU- or CPU-bound, so it scales independently of retrieval.
- It can be skipped: if the deadline is nearly spent or the service is down, the orchestrator continues with the retrieval order and flags the response as degraded.
- Generation service.
- Input: the query, the chosen chunks (already authorized) with their ids, the prompt template version, and generation parameters; output: the answer text with citations as chunk ids, the model identifier, and token counts.
- It holds the prompt template and the context-assembly rules (ordering, truncation to the token budget, de-duplication) and the output checks (citations refer only to supplied ids). Streaming responses use a streamed channel back through the orchestrator.
Cross-cutting rules for every boundary: a schema with explicit versions and a validator that rejects unknown or wrongly typed input; a propagated request id for tracing; the deadline carried as "time remaining"; timeouts and bounded retries only for idempotent calls (all of these calls are read-only, so retrying is safe, but retries multiply load, so cap them); and the component versions echoed in every response so the logs can reconstruct what ran.
Where authorization goes
Check at three places, for different reasons. The gateway authenticates and builds the identity (who is asking). The retrieval service enforces the data filter, because it is the component that reads the index and must never rank chunks the caller cannot see. The orchestrator re-checks document-level permission when it turns citations into links or fetches full documents, since a permission can change between indexing and answering. The reranker and generator receive only what retrieval already authorized, and service-to-service credentials (a token or certificate each service presents to the next, separate from the end user's login) ensure only the orchestrator can call them. Putting the filter after the top-k cut is a defect: restricted chunks use up result slots, so legitimate users get fewer results (the worked example shows this), and a prompt instruction is not an access control.
Batching strategy
- Retrieval is usually a per-request call; batching the query embedding across concurrent requests helps only when the embedding model runs on an accelerator, and then with a window of a few milliseconds.
- Reranking benefits most: with 40 candidates per request, 8 concurrent requests make 320 query-passage pairs. Scoring per request takes 8 model calls, one per request, because 40 pairs fit in one batch of at most 64 pairs; pooling the 320 pairs across requests takes 320 / 64 = 5 calls. The price is the waiting window, so pick it from the deadline budget (a few milliseconds, not tens), and cap the batch by memory.
- Generation: inference servers commonly batch many requests at the token level on their own, so the service should send requests promptly instead of building its own queue.
- Separate queues for interactive and bulk (evaluation, backfill) traffic, so a large job does not starve user requests.
Caching, by stage
| Stage | What to cache | Key must contain | Main risk |
|---|---|---|---|
| Embedding | query vector | normalized query text, embedding model version | stale after a model change |
| Retrieval | candidate list | tenant, permission scope, normalized query, filters, index version | cross-tenant leakage, staleness after ingestion |
| Rerank | scores | query, candidate ids, reranker version | low hit rate |
| Answer | final text | all of the above plus prompt version and model | serving an answer built from since-deleted or since-restricted content |
Permission scope belongs in every key that holds content derived from the data. Short time-to-live plus event-driven invalidation on document change or delete bounds staleness.
A traced request with real values
One request goes through the orchestrator and the three services. Everything runs on stand-ins (TF-IDF as the retriever, word overlap as the reranker, string joining as the generator, the token counts and remaining time written by hand), so the point is the shape of each payload and what crosses each boundary, not the scores. access_label is the sensitivity tag stored with each chunk at ingestion; index_version and embed_version say which index and embedding model produced the result; top_k is the number of chunks the caller wants back; deadline_ms is the time budget for the whole request.
import json
from sklearn.feature_extraction.text import TfidfVectorizer
# Stand-ins: TF-IDF retriever, word-overlap reranker, string-joining generator.
CHUNKS = [ # (chunk_id, tenant, access_label, text)
("a1", "acme", "internal", "Acme refund policy allows returns within thirty days."),
("a2", "acme", "internal", "Acme refund requests are approved by the finance team."),
("a3", "acme", "public", "Acme shipping takes five business days."),
("b1", "bolt", "internal", "Bolt refund policy allows returns within ninety days."),
]
vec = TfidfVectorizer().fit([c[3] for c in CHUNKS])
MAT = vec.transform([c[3] for c in CHUNKS])
show = lambda title, obj: print(f"{title}\n {json.dumps(obj)}")
# Orchestrator -> retrieval service
req = {"request_id": "r-1001", "deadline_ms": 800, "query": "acme refund policy", "tenant": "acme",
"identity": {"user": "u-42", "roles": ["staff"], "levels": ["public", "internal"]},
"top_k": 3, "filters": {}, "index_version": "idx-7"}
show("1. retrieval request", req)
sims = (MAT @ vec.transform([req["query"]]).T).toarray().ravel()
allowed = [i for i, c in enumerate(CHUNKS) if c[1] == req["tenant"] and c[2] in req["identity"]["levels"]]
ranked = sorted(allowed, key=lambda i: (-sims[i], i))[: req["top_k"]]
ret = {"request_id": req["request_id"], "index_version": "idx-7", "embed_version": "embedder-v1",
"chunks": [{"chunk_id": CHUNKS[i][0], "doc_id": "doc-" + CHUNKS[i][0], "score": round(float(sims[i]), 2),
"access_label": CHUNKS[i][2], "text": CHUNKS[i][3]} for i in ranked if sims[i] > 0]}
show("2. retrieval response", {**ret, "chunks": [{k: v for k, v in c.items() if k != "text"} for c in ret["chunks"]]})
# Orchestrator -> reranking service: ids and text in, new scores out.
qwords = set(req["query"].split())
rr = [{"chunk_id": c["chunk_id"], "score": round(len(qwords & set(c["text"].lower().replace(".", "").split())) / len(qwords), 2)}
for c in ret["chunks"]]
rr.sort(key=lambda x: (-x["score"], x["chunk_id"]))
show("3. rerank response", {"request_id": req["request_id"], "reranker_version": "rerank-v2", "scores": rr})
# Orchestrator -> generation service: only authorized chunks, chosen by the orchestrator.
best = next(c for c in ret["chunks"] if c["chunk_id"] == rr[0]["chunk_id"])
gen = {"request_id": req["request_id"], "model": "stub-generator", "prompt_version": "p-3",
"answer": best["text"] + " [" + best["chunk_id"] + "]", "citations": [best["chunk_id"]],
"tokens": {"in": 41, "out": 12}, "deadline_left_ms": 610}
show("4. generation response", gen)
Output:
1. retrieval request
{"request_id": "r-1001", "deadline_ms": 800, "query": "acme refund policy", "tenant": "acme", "identity": {"user": "u-42", "roles": ["staff"], "levels": ["public", "internal"]}, "top_k": 3, "filters": {}, "index_version": "idx-7"}
2. retrieval response
{"request_id": "r-1001", "index_version": "idx-7", "embed_version": "embedder-v1", "chunks": [{"chunk_id": "a1", "doc_id": "doc-a1", "score": 0.55, "access_label": "internal"}, {"chunk_id": "a2", "doc_id": "doc-a2", "score": 0.24, "access_label": "internal"}, {"chunk_id": "a3", "doc_id": "doc-a3", "score": 0.15, "access_label": "public"}]}
3. rerank response
{"request_id": "r-1001", "reranker_version": "rerank-v2", "scores": [{"chunk_id": "a1", "score": 1.0}, {"chunk_id": "a2", "score": 0.67}, {"chunk_id": "a3", "score": 0.33}]}
4. generation response
{"request_id": "r-1001", "model": "stub-generator", "prompt_version": "p-3", "answer": "Acme refund policy allows returns within thirty days. [a1]", "citations": ["a1"], "tokens": {"in": 41, "out": 12}, "deadline_left_ms": 610}
Reading it: the retrieval request carries the identity and tenant, so the access filter runs inside the index query and chunk b1, which belongs to another tenant, never appears. The retrieval response returns ids, scores and labels (the chunk text is hidden in this printout to keep it short; the real payload carries text or a pointer). The reranker returns only new scores for the same ids plus its version, and the generation response carries the answer, citations that name only supplied chunk ids, and the token counts and remaining time the orchestrator needs for the response.
Worked example
The program has two tenants with similar documents, a contract validator, an authorization-placement check, a cache-key check, and the batching arithmetic. The retriever is TF-IDF and the "generator" just returns the top chunk text; they stand in for the real components. The validator is a minimal illustration: it covers non-object input, the wrong types, an empty or oversized query, a tenant string outside a strict pattern (the regular expression [a-z0-9_-]{1,32} accepts only 1 to 32 characters, each a lower-case letter, digit, underscore or hyphen, which rules out path-like strings such as ../acme), and a boolean passed as an integer. A production validator must also handle unknown fields, Unicode normalization, size limits on whole payloads and schema versioning.
import os
os.environ["OMP_NUM_THREADS"] = "1"
import math, re
from sklearn.feature_extraction.text import TfidfVectorizer
# Stand-ins: TF-IDF retriever, word-overlap "reranker", string-joining "generator".
CHUNKS = [ # (chunk_id, tenant, text)
("a1", "acme", "Acme refund policy allows returns within thirty days."),
("a2", "acme", "Acme refund requests are approved by the finance team."),
("a3", "acme", "Acme shipping takes five business days."),
("b1", "bolt", "Bolt refund policy allows returns within ninety days."),
("b2", "bolt", "Bolt refund requests are approved automatically."),
("b3", "bolt", "Bolt warranty covers two years."),
]
vec = TfidfVectorizer().fit([c[2] for c in CHUNKS])
MAT = vec.transform([c[2] for c in CHUNKS])
def validate(req):
"""Contract check for the retrieval service. Minimal: it covers the shapes listed in the tests below."""
if not isinstance(req, dict):
return None, "request must be an object"
q, tenant, k = req.get("query"), req.get("tenant"), req.get("top_k", 3)
if not isinstance(q, str) or not 0 < len(q.strip()) <= 500:
return None, "query must be a non-empty string of at most 500 characters"
if not isinstance(tenant, str) or re.fullmatch(r"[a-z0-9_-]{1,32}", tenant) is None:
return None, "tenant must match [a-z0-9_-]{1,32}"
if isinstance(k, bool) or not isinstance(k, int) or not 1 <= k <= 5:
return None, "top_k must be an integer from 1 to 5"
return {"query": q.strip().lower(), "tenant": tenant, "top_k": k}, None
def retrieve(req, prefilter=True, candidates=4):
sims = (MAT @ vec.transform([req["query"]]).T).toarray().ravel()
order = sorted(range(len(CHUNKS)), key=lambda i: (-sims[i], i))
if prefilter: # authorization inside the index query, before the cut-off
order = [i for i in order if CHUNKS[i][1] == req["tenant"]]
return [CHUNKS[i][0] for i in order[:candidates] if sims[i] > 0]
top = order[:candidates] # post-filter: cut first, check afterwards
return [CHUNKS[i][0] for i in top if CHUNKS[i][1] == req["tenant"] and sims[i] > 0]
print("-- contract validation")
for bad in (None, 7, ["x"], {"query": "refund", "tenant": "acme", "top_k": "3"}, {"query": "", "tenant": "acme"},
{"query": "x" * 501, "tenant": "acme"}, {"query": "refund", "tenant": "../acme"}, {"query": "refund", "tenant": "acme", "top_k": True},
{"query": "refund policy", "tenant": "acme", "top_k": 2}):
ok, err = validate(bad)
print(f"{str(bad)[:58]:60s} -> {'OK ' + str(ok['top_k']) if ok else err}")
print("-- authorization placement (tenant bolt, query about refund)")
r = validate({"query": "acme refund policy", "tenant": "bolt"})[0]
print("pre-filter :", retrieve(r, True))
print("post-filter:", retrieve(r, False))
print("-- cache key")
cache_bad, cache_good = {}, {}
def answer(req, cache, key):
if key in cache:
return cache[key] + " (cache hit)"
ids = retrieve(req)
text = " | ".join(c[2] for c in CHUNKS if c[0] in ids[:1])
cache[key] = text
return text
qa = validate({"query": "acme refund policy", "tenant": "acme"})[0]
qb = validate({"query": "acme refund policy", "tenant": "bolt"})[0]
print("key=query only, acme :", answer(qa, cache_bad, qa["query"]))
print("key=query only, bolt :", answer(qb, cache_bad, qb["query"]))
print("key=(tenant,query), acme:", answer(qa, cache_good, (qa["tenant"], qa["query"], "idx-7")))
print("key=(tenant,query), bolt:", answer(qb, cache_good, (qb["tenant"], qb["query"], "idx-7")))
print("-- batching the reranker (model calls)")
requests, cands, max_batch = 8, 40, 64
per_request = requests * math.ceil(cands / max_batch)
pooled = math.ceil(requests * cands / max_batch)
print(f"pairs scored={requests * cands}; per-request batches={per_request} calls; pooled micro-batches={pooled} calls")
Output:
-- contract validation
None -> request must be an object
7 -> request must be an object
['x'] -> request must be an object
{'query': 'refund', 'tenant': 'acme', 'top_k': '3'} -> top_k must be an integer from 1 to 5
{'query': '', 'tenant': 'acme'} -> query must be a non-empty string of at most 500 characters
{'query': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -> query must be a non-empty string of at most 500 characters
{'query': 'refund', 'tenant': '../acme'} -> tenant must match [a-z0-9_-]{1,32}
{'query': 'refund', 'tenant': 'acme', 'top_k': True} -> top_k must be an integer from 1 to 5
{'query': 'refund policy', 'tenant': 'acme', 'top_k': 2} -> OK 2
-- authorization placement (tenant bolt, query about refund)
pre-filter : ['b1', 'b2']
post-filter: ['b1']
-- cache key
key=query only, acme : Acme refund policy allows returns within thirty days.
key=query only, bolt : Acme refund policy allows returns within thirty days. (cache hit)
key=(tenant,query), acme: Acme refund policy allows returns within thirty days.
key=(tenant,query), bolt: Bolt refund policy allows returns within ninety days.
-- batching the reranker (model calls)
pairs scored=320; per-request batches=8 calls; pooled micro-batches=5 calls
Reading it: the validator returns an error for None, a number, a list, a string top_k, an empty query, a 501-character query, a path-like tenant and a boolean top_k (a Python True is an int, so the check excludes it explicitly), and accepts the one well-formed request. With the filter inside the index query, tenant bolt gets two of its own chunks (b1, b2); with the filter after the cut-off of four candidates, other tenants' chunks consume slots and bolt gets only b1. In the cache demo, a key made of the query alone served Acme's refund policy to Bolt (a cross-tenant leak); including the tenant and index version in the key gave each tenant its own answer. The batching line shows 320 pairs scored in 8 calls per-request or 5 calls pooled at a limit of 64 pairs per call.
Trade-offs and when not to split
- Each network hop adds latency and a failure mode. Three extra hops can be justified only when the parts scale differently (the reranker needs accelerators, retrieval needs memory, generation needs the most capacity) or are owned by different teams. A small system should start as modules inside one service with the same interfaces, and split later along those seams.
- Payload size: sending chunk text between services costs bandwidth; pass ids plus text only where the next stage needs it.
- Version skew: if the retriever and reranker are deployed independently, record the versions on every response and test the combinations.
- Failure handling: define per-stage fallbacks (skip rerank, smaller context, "I could not find an answer" instead of a guess) and test them.
Common mistakes
- Treating authorization as a front-door concern only.
- A cache key without tenant, permission scope or index version.
- Retrying on timeouts without a budget, which turns a slow dependency into an outage.
- Micro-batching windows longer than the latency saved.
- Letting the generation service accept chunk text from the client, which bypasses retrieval authorization.
Design a RAG system served across multiple regions. How do you store and partition the vector indices, guarantee freshness of new documents, replicate, and keep tail latency low for users far from the primary?
Sample Answer
Direct answer
Run one write path and many read paths. Documents are ingested once into a durable, ordered change log in the primary region; every region consumes that log and builds its own searchable copy of the vector index, so users are served by a replica in their own region and never wait on a cross-ocean search. Freshness is the price: a replica is behind the primary by the replication lag plus the index refresh interval, so you state a freshness target (for example "99 percent of new documents searchable everywhere within a minute"), measure it, and offer a stronger read-your-writes option for the few requests that need it. Tail latency is kept low by local replicas, spare replicas to hedge against slow searches (a hedge is a duplicate request sent to a second replica when the first has not answered within a set time, using whichever answers first), and degraded-but-fast fallbacks.
Terms
A vector index stores one embedding vector per text chunk and answers "which stored vectors are nearest to this query vector" approximately; HNSW (a layered neighbour-graph index) is a common choice and keeps the vectors and the graph in memory. A shard is a slice of the index held by one node. A replica is a copy of a shard. Tail latency (p99) is the time within which 99 percent of requests finish. Compaction rewrites an index into a fresh, tidy one, merging small recent additions and dropping deleted entries for good. A monotonic version number is a counter that only ever increases, so a larger number always means a newer state. Anycast advertises one network address from several locations so that each user's traffic reaches the nearest one. A lognormal distribution is a right-skewed one for positive values (its logarithm is bell-shaped): most delays sit near the median and a few are much longer, which is why it models latencies. Read-your-writes means a user who just added a document sees it in their next query.
Design, in the order the data moves
- Partitioning. Split the index into shards by a key that matches the query pattern. If queries are scoped to a tenant (a customer organisation), shard by tenant: each query touches one shard, and data-residency rules (this tenant's data stays in this geography) become a placement rule. If queries search everything, shard by hash of the chunk id and scatter each query to all shards, then merge the top results; this costs one parallel fan-out per query (a scatter to all shards, followed by a gather) and makes the slowest shard set the latency. That is tail amplification: if each shard is slow on 1 percent of requests, a query that waits for 20 shards is slowed by at least one of them with probability 1 - 0.99^20, about 18 percent. This is why shards each get replicas.
- Write path. Ingestion (parse, chunk, embed) runs in the primary region and appends records (add, update, delete, plus access labels) to an ordered log with a monotonic version number. Regions subscribe. Each region applies the records to its own index. Shipping the log, not index files, keeps every region independent, lets each rebuild from the log, and gives you a version number to reason about freshness.
- Index structure for freshness. Graph indexes are slow to update in place and degrade after many deletes. A common pattern is a large immutable main index rebuilt or compacted periodically, plus a small in-memory "recent" index for documents added since the last build; a query searches both and merges results. Deletes are tombstones (a marker that hides the chunk) applied immediately and physically removed at compaction.
- Replication. Choose per region between a full replica and a partial one. A full replica gives local reads for everything at the cost of the storage in the worked example. A partial one (hot subset or tenants homed in that region) saves memory and sends cold queries to a remote region, so decide from the traffic distribution, not by default. Quantizing vectors (storing each number in 1 byte instead of 4, a coarser but smaller representation) cuts the memory about fourfold at some recall cost that you measure on your own data.
- Routing. Geo-aware DNS or an anycast edge sends each request to the nearest healthy region; the retrieval and generation services run in that same region, so the whole RAG path (embed the query, search, rerank, call the language model) stays local. On a regional failure, route to the next-nearest region and accept the latency hit.
- Consistency options per request. The default is eventual: search the local replica. For read-your-writes, the client sends the version number returned by its upload; the replica compares it with the version it has applied, waits up to a small bound (say 200 ms) if it is behind, and otherwise sends that one query to the primary region. A traced case: the upload returns version 1042 and the user asks a question straight away; the local replica has applied version 1040, so it holds the query. If version 1042 arrives within 200 ms it answers locally; if the replica is still at 1041 when the 200 ms are up, that one query goes to the primary, which has version 1042. The few users who need it pay the latency; everyone else does not.
- Deletes and permission changes must propagate faster than additions: a revoked document or a removed user must stop being returned everywhere within the security target. Give them priority in the log or enforce access checks against a central, quickly replicated authorization service at query time.
Worked example
All inputs are assumed values for illustration (50 million chunks, 768-dimensional vectors, HNSW with M = 16, which allows up to 2 x 16 = 32 links per node in the bottom layer, each link a 4-byte id, so the bottom-layer graph is 50 million x 32 x 4 bytes = 6.4 GB; lognormal replication delays; and a 2 percent chance a search runs six times slower, as when a disk read stalls or a garbage-collection pause hits that one machine); none is a measurement of a real system. The program prints memory arithmetic, a freshness simulation, and a tail-latency simulation with 200,000 samples each.
import os
os.environ["OMP_NUM_THREADS"] = "1"
import numpy as np
# Assumed inputs (stated, not measured): 50 million chunks, 768-dim vectors, HNSW with M=16 and 4-byte ids.
N, DIM, M_LINKS = 50_000_000, 768, 16
GB = 1e9
vec_f32 = N * DIM * 4
vec_i8 = N * DIM * 1
links0 = 2 * M_LINKS # HNSW's bottom layer allows up to 2 x M links per node
graph = N * links0 * 4 # layer-0 neighbour lists only (upper layers are a small extra)
print(f"vectors float32 : {vec_f32 / GB:7.1f} GB")
print(f"vectors int8 : {vec_i8 / GB:7.1f} GB")
print(f"graph layer 0 : {graph / GB:7.1f} GB ({N:,} x {links0} links x 4 B)")
full_f32 = (vec_f32 + graph) / GB
full_i8 = (vec_i8 + graph) / GB
print(f"one full copy : {full_f32:7.1f} GB (float32) {full_i8:7.1f} GB (int8, originals kept on disk)")
print(f"3 regions x 1 full copy x 2 replicas each: {3 * 2 * full_f32:7.1f} GB of RAM (float32)")
print(f"4 shards, 3 regions, 2 replicas per shard : {full_f32 / 4:7.1f} GB per node, {4 * 3 * 2} nodes")
# Freshness: time from "document written at the primary" to "searchable in a region".
# Assumed lag model: ship delay lognormal (median 6 s, sigma 0.7) plus a refresh wait uniform in [0, 5] s.
rng = np.random.default_rng(0)
n = 200_000
def visible_after(median_s, extra_s=0.0):
ship = rng.lognormal(np.log(median_s), 0.7, n)
refresh = rng.uniform(0, 5.0, n)
return ship + refresh + extra_s
regions = {"primary": 0.0, "region_b": 6.0, "region_c": 20.0} # median ship delay, seconds; primary has none
print("freshness (seconds until searchable):")
for name, med in regions.items():
t = rng.uniform(0, 5.0, n) if med == 0 else visible_after(med)
print(f" {name:9s} p50={np.percentile(t, 50):5.1f} p99={np.percentile(t, 99):5.1f} P(<=10s)={np.mean(t <= 10):.3f} P(<=30s)={np.mean(t <= 30):.3f}")
# Read-your-writes: a user uploads, then asks 3 s later. Share of such queries that would miss the new document.
t_b = visible_after(6.0)
print(f"region_b: queries 3 s after a write that would miss it = {np.mean(t_b > 3):.3f}")
# Tail latency. Assumed: RTT 150 ms to the far primary, 10 ms to a local replica; search time lognormal
# (median 30 ms, sigma 0.5) and 2 percent of searches are slow (x6). Hedge: send a copy to a second local replica at 60 ms.
def search_ms(size):
s = rng.lognormal(np.log(30), 0.5, size)
slow = rng.random(size) < 0.02
return np.where(slow, s * 6, s)
remote = 150 + search_ms(n)
local = 10 + search_ms(n)
first, second = search_ms(n), search_ms(n)
hedged = 10 + np.minimum(first, 60 + second)
for name, x in [("remote primary", remote), ("local replica", local), ("local + hedge@60ms", hedged)]:
print(f"{name:20s} p50={np.percentile(x, 50):6.1f} ms p99={np.percentile(x, 99):6.1f} ms")
extra = np.mean(first > 60)
print(f"hedge sends a second request for {extra:.3f} of queries")
ordinary = np.mean(rng.lognormal(np.log(30), 0.5, n) > 60)
print(f"why: an ordinary search exceeds 60 ms with probability {ordinary:.3f}; the 2% slow searches almost always do")
Output:
vectors float32 : 153.6 GB
vectors int8 : 38.4 GB
graph layer 0 : 6.4 GB (50,000,000 x 32 links x 4 B)
one full copy : 160.0 GB (float32) 44.8 GB (int8, originals kept on disk)
3 regions x 1 full copy x 2 replicas each: 960.0 GB of RAM (float32)
4 shards, 3 regions, 2 replicas per shard : 40.0 GB per node, 24 nodes
freshness (seconds until searchable):
primary p50= 2.5 p99= 5.0 P(<=10s)=1.000 P(<=30s)=1.000
region_b p50= 8.7 p99= 33.2 P(<=10s)=0.611 P(<=30s)=0.985
region_c p50= 22.6 p99=104.7 P(<=10s)=0.084 P(<=30s)=0.674
region_b: queries 3 s after a write that would miss it = 0.973
remote primary p50= 180.3 ms p99= 329.8 ms
local replica p50= 40.5 ms p99= 194.1 ms
local + hedge@60ms p50= 40.4 ms p99= 106.1 ms
hedge sends a second request for 0.100 of queries
why: an ordinary search exceeds 60 ms with probability 0.082; the 2% slow searches almost always do
Reading it:
- Storage drives the replication choice. One full copy is about 160 GB in 32-bit floats; three regions with two replicas each is 960 GB held in RAM. Splitting into 4 shards gives 40 GB per node, which fits ordinary hosts, at 24 nodes. Quantizing to 1 byte per dimension brings one copy to 44.8 GB if the full-precision vectors stay on disk for rescoring.
- Freshness differs per region. In this model the primary is searchable within about 5 seconds (the refresh wait alone), region_b has a p99 of 33.2 seconds and region_c of 104.7 seconds. Against a "within 30 seconds" target, region_b meets it for 98.5 percent of documents and region_c for 67.4 percent, so region_c either needs a faster link or a looser target. Because the target is stated per region, the dashboard can alarm on the right number.
- Read-your-writes matters in the first seconds. In region_b, 97.3 percent of queries issued 3 seconds after a write would miss the new document without the version-token mechanism.
- Local replicas cut the median and the tail; hedging cuts the tail further. The remote primary has p99 of 329.8 ms, the local replica 194.1 ms, and the hedged local pair 106.1 ms. The hedge (a duplicate request sent to a second replica if the first has not answered after 60 ms) fires on 10 percent of queries here: 60 ms is twice the 30 ms median, an ordinary search exceeds it about 8 percent of the time (the second printed line), and nearly all of the 2 percent slow searches do too. So it costs about 10 percent more search load for this latency gain. Hedging only helps when the slowness is independent per replica, as it is in this simulation (a slow disk, a garbage-collection pause, a noisy neighbour), not when all replicas are slow together (a bad query, an overloaded shard).
Freshness versus latency, stated as a trade-off
Waiting for a replica to catch up buys freshness at the price of latency; returning immediately buys latency at the price of staleness. Commit to eventual consistency as the default because almost all RAG questions concern documents that have existed for hours or days, expose the strong option on request, show the index version or "as of" time in the response so users and logs can see staleness, and set a per-request wait bound so the strong option cannot block forever. What would flip the choice: an interactive "upload then ask about it" product makes read-your-writes the default; a compliance product makes deletes the strongest-consistency path.
Failure modes and mistakes
- Replication lag grows silently after a regional incident; alert on the gap between the primary's latest version and each region's applied version, not on CPU.
- Partial failures in a fan-out: if one shard times out, return results from the others with a "partial" flag rather than failing the request, and track the rate.
- Cross-region fallbacks on every miss turn a regional outage into a global overload; cap them.
- Single-copy ingestion: an embedding-model change needs a full re-embed and a new index in every region, so version the index and switch regions one at a time.
- Assuming strong consistency from an eventually consistent store and then debugging "missing" documents.
- Hedging without limits doubles load during an incident; budget hedges as a small percentage of requests.
Design access control for a RAG system over sensitive documents so users only retrieve what they are cleared to see. How do authentication, authorization and audit logging fit into the pipeline without hurting latency?
Sample Answer
Direct answer
Enforce access control inside retrieval, before any text reaches the language model: authenticate the user once, resolve their groups and clearances into a filter, apply that filter as part of the vector search itself (vector search finds the stored vectors nearest to the query's vector; applying the filter inside that search, before results are cut to the top k, is a pre-filter), and log what was retrieved and shown. The model must never be the thing that decides what a user may see, because anything placed in its prompt can be quoted in its answer. Latency stays low because the identity lookup is cached for a short time and the filter is a metadata predicate evaluated inside the index, not a second pass over results.
The request path, in order
- Authenticate. Verify the caller's token at the edge (who is this, signed and unexpired). Do not accept a user id or a list of groups from the browser body.
- Authorize, per request. Resolve the user into the set of groups and clearance level the document ACLs (access-control lists: per-document records of who may read it) are written in. Cache this resolution for a short, bounded time (for example 60 seconds, an illustrative value) so group changes take effect quickly; the cache time is the revocation delay and should be stated.
- Build the filter and pass it to the search. Every chunk is stored with its ACL as metadata copied from the source document at ingestion. The query carries a predicate such as "chunk ACL intersects user groups AND classification <= user clearance". The search returns only chunks that pass it.
- Assemble context only from filtered results. Reranking, query rewriting, caching and any follow-up fetch use the same filter. A shared answer cache must be keyed by the access scope too, otherwise one user's answer is served to another.
- Check the output. Every citation in the answer must be one of the chunks given to the model on this request. An answer citing something else is withheld or repaired. This catches the model naming or quoting material that came from somewhere other than the permitted context, for example from a stale conversation memory.
- Audit. Write an append-only record per request: request id, user, the groups they were resolved to, the chunk ids given to the model, the chunk ids cited, and any blocked citation. Store ids, not text, so the audit log is not a second copy of the sensitive corpus. Write it asynchronously off the critical path (a queue), with a guarantee that a failed write alarms rather than silently drops.
Why pre-filtering rather than filtering the results afterwards
The program below uses random unit vectors as stand-ins for embeddings (a real system would use an embedding model) and brute-force similarity search. The corpus has 2,000 chunks, each readable by one or two of six groups; each of 300 simulated users belongs to two groups. The point is the selectivity arithmetic, which does not depend on the embedding model. Selectivity here means the share of the corpus a user's filter lets through: a user who may read 47 percent of the chunks has a selectivity of 0.47, and a user who may read 2 percent has a narrow filter.
How to read the code: V holds the 2,000 stand-in vectors and acl[i] is the set of groups allowed to read chunk i. top(qv, allowed_idx, k) scores only the listed chunks against the query vector and returns the best k. In each of the 300 trials a random user with two groups is drawn, ok lists the chunks that user may read, and truth is the best 10 among those, the exact permitted answer. plain is the best 10 over everything, with no access control. Then three strategies are compared against truth: filter plain afterwards (post_ret counts how many results survive, post_recall how many of the true top 10 are among them), fetch 50 then filter (over_ret, over_recall), and search only ok (pre_ret). The lists are averaged at the end to print one line each.
import os
os.environ["OMP_NUM_THREADS"] = "1"
import json
import numpy as np
rng = np.random.default_rng(0)
N, D, K = 2000, 32, 10
V = rng.normal(size=(N, D)); V /= np.linalg.norm(V, axis=1, keepdims=True) # stand-in embeddings (random unit vectors)
groups = ["hr", "legal", "fin", "eng", "exec", "sales"]
# each chunk is readable by 1 or 2 groups (its access-control list)
acl = [set(rng.choice(groups, size=rng.integers(1, 3), replace=False)) for _ in range(N)]
def top(qv, allowed_idx, k):
idx = np.array(allowed_idx)
sc = V[idx] @ qv
return idx[np.argsort(-sc)[:k]].tolist()
n_trials = 300
share_ok, unauth_share, post_ret, post_recall, over_ret, over_recall, pre_ret = [], [], [], [], [], [], []
for _ in range(n_trials):
user = set(rng.choice(groups, size=2, replace=False))
ok = [i for i in range(N) if acl[i] & user]
share_ok.append(len(ok) / N)
qv = rng.normal(size=D); qv /= np.linalg.norm(qv)
truth = top(qv, ok, K) # exact answer restricted to what the user may see
plain = top(qv, range(N), K) # no access control at all
unauth_share.append(np.mean([not (acl[i] & user) for i in plain]))
post = [i for i in plain if acl[i] & user] # filter AFTER retrieving k
post_ret.append(len(post)); post_recall.append(len(set(post) & set(truth)) / K)
over = [i for i in top(qv, range(N), 5 * K) if acl[i] & user][:K] # fetch 5k, then filter
over_ret.append(len(over)); over_recall.append(len(set(over) & set(truth)) / K)
pre_ret.append(len(top(qv, ok, K))) # filter INSIDE the search
print(f"mean share of chunks a user may read: {np.mean(share_ok):.2f}")
print(f"no filter: unauthorized share of top-{K}: {np.mean(unauth_share):.2f}")
print(f"post-filter k={K}: results {np.mean(post_ret):.2f}, recall vs exact allowed top-{K} {np.mean(post_recall):.2f}")
print(f"candidates needed on average to find {K} allowed chunks: {K / np.mean(share_ok):.1f}")
print(f"overfetch 5x: results {np.mean(over_ret):.2f}, recall vs exact allowed top-{K} {np.mean(over_recall):.2f}")
print(f"pre-filter: results {np.mean(pre_ret):.2f}, recall 1.00 by construction")
# Per-request enforcement, citation check and audit record (illustration with fixed values)
user_groups = {"legal", "fin"}
allowed_ids = [i for i in range(N) if acl[i] & user_groups]
shown = top(V[7], allowed_ids, 3)
forbidden = next(i for i in range(N) if i not in set(allowed_ids))
cited_by_model = shown[:2] + [forbidden] # model cites a chunk it was never given
violations = [c for c in cited_by_model if c not in set(shown)]
audit = dict(request="r-001", user="u-42", groups=sorted(user_groups), chunks_given=shown, cited=cited_by_model, blocked_citations=violations)
print(json.dumps(audit))
Output:
mean share of chunks a user may read: 0.47
no filter: unauthorized share of top-10: 0.55
post-filter k=10: results 4.48, recall vs exact allowed top-10 0.45
candidates needed on average to find 10 allowed chunks: 21.5
overfetch 5x: results 10.00, recall vs exact allowed top-10 1.00
pre-filter: results 10.00, recall 1.00 by construction
{"request": "r-001", "user": "u-42", "groups": ["fin", "legal"], "chunks_given": [7, 257, 329], "cited": [7, 257, 0], "blocked_citations": [0]}
Reading it. With no access control, 0.55 of the top ten are chunks the user may not read, and those would go straight into the prompt. Filtering after retrieving ten leaves on average 4.48 results and only 0.45 of the exact permitted top ten, because most of the ten slots were wasted on forbidden chunks. Overfetching (retrieve 50, then filter) recovers the full list here, because this average user may read about 0.47 of the corpus, so finding ten permitted chunks takes about 10 / 0.47 = 21 candidates (the printed 21.5 divides by the unrounded share), and 50 candidates is comfortably more than that. The overfetch factor is a guess about selectivity: a user who may read a small share of the corpus needs about K divided by that share candidates (here K = 10), so the fetch size has to grow as the share shrinks, and the cost and the recall both degrade as selectivity falls. A pre-filter does not depend on that guess. The last line is the per-request audit record, and it shows the output check firing: the model cited chunk 0, which was never given to it, and the record lists it under blocked_citations.
Latency
- The authorization lookup is one cached call; the filter is a predicate inside the index, whose cost depends on the engine and on how selective the predicate is. Measure p95 (the latency that 95 percent of requests beat) with your real ACL distribution, because narrow filters are the slow case for approximate indexes. An approximate index finds near neighbours without scanning every vector, typically by walking from one nearby vector to the next; with a filter, it discards each visited vector the user may not read, so when the filter lets through only a few percent of the corpus most visited vectors are discarded and the search has to visit many more of them (or return fewer than k results) to find enough permitted neighbours. How an engine handles this differs, so test it.
- If one tenant or group is tiny, give it its own partition (a physically separate slice of the index holding only that group's chunks) or index; the filter then costs nothing and isolation is stronger.
- Audit logging and the output check are the only additions after generation; keep them cheap (set membership on ids) and the log write asynchronous.
Trade-offs and failure modes
- Stale permissions. Revoking access in the source system must reach the index. Either copy ACL changes through the same incremental update path (with a short lag target and an alarm) or re-check authorization against the source of truth for the top results at query time, which costs a call per request.
- Leakage during generation. The guarantee comes from what is in the prompt: if only permitted chunks are there, the model has nothing restricted to quote. The citation check above is a backstop that catches references to chunks that were not supplied; it does not prove that every sentence is grounded in permitted text, so keep restricted material out of model weights (no fine-tuning on it) and out of any memory shared between users.
- Derived data. Summaries, caches, embeddings of conversation history and fine-tuned weights are copies of documents. Each must inherit the ACL of its inputs or not exist.
- ACL explosion. Per-user ACLs on millions of chunks are expensive; prefer groups and roles, and a classification level, as the stored attribute.
- Common mistakes: trusting groups sent by the client; filtering after retrieval and calling it done; one shared cache across users; logging full chunk text into the audit trail.
Propose a cost-optimized deployment plan for a RAG service that balances CPU-based ANN vs GPU-based re-ranking and generation for mixed query loads (80% short FAQ queries, 20% long-complex research queries). Include autoscaling and prewarming considerations.
Sample Answer
Direct answer
Put vector search on CPU nodes sized for the index's memory and availability, not for throughput, and put reranking and generation on GPUs sized from the load each query class creates. Classify queries cheaply at the front: the 80 percent short FAQ queries go through an answer cache and a light path (few candidates, little or no reranking, short generation), and the 20 percent long research queries get the full path. Because the long queries hold GPU capacity for seconds each while FAQ queries hold it for fractions of a second, give each class its own GPU pool (a "bulkhead") so a burst of research queries cannot starve FAQ users, and scale the pools on concurrency and queue depth with scheduled prewarming for known peaks. Every number below is an assumed input to show the method; replace them with measurements from your own service.
Terms
ANN (approximate nearest neighbour) search finds vectors close to the query vector without scanning all of them. A reranker reorders retrieved candidates with a slower model. Generation is the language model writing the answer. A slot is one concurrent sequence a GPU can serve (a GPU can process many requests at once). Prewarming is starting capacity before it is needed, because new GPU nodes need minutes to start and load a model. A bulkhead is a separate resource pool per traffic class so one class's overload cannot consume the other's capacity. Utilization is busy time divided by available time. p95 and p99 are the wait that 95 percent and 99 percent of requests stay under. A quantized model stores its weights with fewer bits (for example 8 instead of 16), which makes it smaller and faster at some cost in quality. Queue depth is the number of requests waiting for a slot. Failure zones are groups of machines that do not share power or network, so one failure does not take out both. Token throughput is the number of tokens a GPU generates per second across all its requests. Batching serves several requests in one pass of the model. Admission control rejects or defers requests when a queue is too long. A first-in-first-out queue serves requests in the order they arrive.
Sizing from the load, class by class
- Write the load per class. For each class: arrival rate, CPU time for search, GPU time for rerank and generation, and the cache hit rate. Time on the GPU depends on the number of rerank pairs and the number of output tokens, so measure them on real traffic.
- Convert to busy capacity: arrival rate times service time gives the average number of busy servers (Little's law: average number in service = arrival rate times time in service).
- Divide by a target utilization (here 70 percent) to leave room for variability: queues grow quickly as utilization approaches 100 percent.
- Add redundancy: at least two replicas of each tier in separate failure zones, whatever the throughput arithmetic says.
CPU versus GPU placement
- Vector search (CPU). ANN indexes such as HNSW live in memory and are lookup-bound; for these assumed numbers throughput needs only one node, so the node count is set by index size in memory, replicas and availability. Keep the index in RAM; use compressed vectors if memory dominates.
- Reranking (GPU or CPU). A cross-encoder reranker (a model reading query and passage together) costs a model pass per pair. For FAQ queries, skip it when the first-stage score is decisive or rerank only a few candidates; for research queries rerank many. A small reranker can be affordable on CPU; measure before assuming a GPU is needed.
- Generation (GPU). This is normally the dominant cost. Levers in order of impact: answer caching for repeated FAQ questions, a smaller or quantized model for the FAQ class (accept only if your evaluation set shows the quality is adequate), limits on output length and on retrieved context, and batching of concurrent requests on one GPU.
Why separate pools, and what flips it
At normal load a pool shared by both classes is a little better, because sharing smooths random fluctuations. When one class surges, the shared pool lets it take every slot. The simulation below shows both effects. The decision: use separate pools when you have a latency target for FAQ users that must hold during research bursts; use one pool with priority queues (FAQ jobs first, long jobs capped to a fraction of slots) when load is low and you want the sharing efficiency. Admission control for the long class (reject or defer with a clear message when its queue exceeds a deadline) is needed in both layouts, because no amount of isolation helps the class that is itself overloaded.
Autoscaling and prewarming
- Scale on the right signal: slot utilization, in-flight requests per replica or queue wait time, not CPU percentage, which says little about a GPU server that is saturated on memory or token throughput.
- Know the lag: starting a GPU node includes provisioning, fetching the serving software and loading model weights; assume minutes. During the lag, a reactive autoscaler cannot protect latency, so the policy has three parts: a minimum replica count that covers normal peak, scheduled prewarming before known daily or weekly peaks, and a small headroom buffer for unexpected rises, with the autoscaler handling the rest.
- Scale down slowly (cool-down periods), because a scale-down followed by a spike pays the start-up lag twice.
- Keep a warm pool of preloaded nodes if cold starts are the bottleneck, and weigh its cost against the cost of failing the SLO (service-level objective: the latency target).
- Degrade before failing: under pressure, skip reranking, shorten the context or the output, or serve a cached answer, in that order.
Worked example
Assumed inputs: 40 requests per second in total, 32 FAQ and 8 research; half of the FAQ answers come from the cache; vector search costs 0.02 CPU-seconds (FAQ) or 0.06 (research) on 16-core nodes; GPU slot time is 0.5 s (FAQ) or 6 s (research) per request; a GPU serves 16 slots; a new GPU takes 180 s to become ready; relative prices are 1 unit per hour for a CPU node and 10 for a GPU node (illustrative units, not any provider's prices). The simulation is a first-in-first-out queue with Poisson arrivals (random arrivals at a fixed average rate), 3,000 s per run and 5 seeds, and it reports the FAQ queue wait only. In plain words: each pool is a list of the times at which its slots become free; a request arriving at time t takes the slot that frees first, starts at the later of t and that time, waits for the difference, and keeps the slot busy for 0.5 s (FAQ) or 6 s (research). The inputs are chosen so that the arithmetic is easy to follow; real slots per GPU depend on model size, memory and sequence lengths, so treat 80 slots and 5 GPUs as an illustration of the method, not as a benchmark. The "burst" rows multiply the research arrival rate by 1.6 for the whole window, so the shared pool is overloaded throughout and its waits keep growing with the window length.
import os
os.environ["OMP_NUM_THREADS"] = "1"
import heapq, math
import numpy as np
# ASSUMED inputs for illustration (not measurements). Raw load: 40 requests/s, 80% short FAQ and 20% long research.
RAW_FAQ, RAW_LONG, CACHE_HIT_FAQ = 32.0, 8.0, 0.5 # half of the FAQ answers come from an answer cache
CPU_FAQ, CPU_LONG, CORES = 0.02, 0.06, 16 # CPU-seconds of vector search per request, cores per node
GPU_FAQ, GPU_LONG, SLOTS_PER_GPU = 0.5, 6.0, 16 # slot-seconds on the GPU path, concurrent sequences per GPU
TARGET_UTIL = 0.7
cpu_load = RAW_FAQ * CPU_FAQ + RAW_LONG * CPU_LONG
print(f"CPU search: {cpu_load:.2f} busy cores -> {math.ceil(cpu_load / (TARGET_UTIL * CORES))} node(s) for throughput")
lam_faq, lam_long = RAW_FAQ * (1 - CACHE_HIT_FAQ), RAW_LONG
lam = lam_faq + lam_long
load_faq, load_long = lam_faq * GPU_FAQ, lam_long * GPU_LONG
load = load_faq + load_long
slots = math.ceil(load / TARGET_UTIL)
print(f"GPU path: {lam:.0f} requests/s, busy slots FAQ={load_faq:.0f} long={load_long:.0f} total={load:.0f}; at {TARGET_UTIL:.0%} utilization {slots} slots = {math.ceil(slots / SLOTS_PER_GPU)} GPUs")
def simulate(seed, slots_by_pool, route, long_mult=1.0, horizon=3000.0):
rng = np.random.default_rng(seed)
rate_long = lam_long * long_mult
rate = lam_faq + rate_long
free = {p: [0.0] * n for p, n in slots_by_pool.items()}
t, waits = 0.0, []
while t < horizon:
t += rng.exponential(1 / rate)
faq = rng.random() < lam_faq / rate
pool = route["faq" if faq else "long"]
start = max(t, heapq.heappop(free[pool]))
heapq.heappush(free[pool], start + (GPU_FAQ if faq else GPU_LONG))
if faq:
waits.append(start - t)
return np.array(waits)
faq_slots = math.ceil(load_faq / TARGET_UTIL)
layouts = {
f"one shared pool, {slots} slots": ({"all": slots}, {"faq": "all", "long": "all"}),
f"split pools {faq_slots} + {slots - faq_slots} slots": ({"faq": faq_slots, "long": slots - faq_slots}, {"faq": "faq", "long": "long"}),
}
for mult, label in ((1.0, "normal load"), (1.6, "research burst x1.6")):
for name, (pools, route) in layouts.items():
p95, p99, over1 = [], [], []
for seed in range(5):
w = simulate(seed, pools, route, long_mult=mult)
p95.append(np.percentile(w, 95)); p99.append(np.percentile(w, 99)); over1.append(np.mean(w > 1.0))
print(f"{label:20s} {name:28s} FAQ wait, mean of 5 seeds: p95={np.mean(p95):6.2f} s p99={np.mean(p99):6.2f} s share>1s={np.mean(over1):.3f}")
# Step increase to twice the load; new GPUs need 180 s (assumed) before they take traffic.
need = math.ceil(2 * load / TARGET_UTIL)
extra_gpus = math.ceil((need - slots) / SLOTS_PER_GPU)
growth = 2 * load - slots # slot-seconds of work arriving faster than capacity per second
avg_service = load / lam
print(f"after a 2x step: {need} slots needed (+{extra_gpus} GPUs); until they are ready, backlog grows {growth:.0f} slot-s per s")
print(f"over 180 s: {growth * 180:.0f} slot-seconds of backlog = {growth * 180 / avg_service:.0f} average requests queued")
CPU_NODE, GPU_NODE = 1.0, 10.0 # relative price units per hour (assumed)
print(f"relative cost per hour: base {math.ceil(slots / SLOTS_PER_GPU) * GPU_NODE:.0f} units; holding {extra_gpus} prewarmed GPUs adds {extra_gpus * GPU_NODE:.0f}; one CPU search node is {CPU_NODE:.0f}")
Output:
CPU search: 1.12 busy cores -> 1 node(s) for throughput
GPU path: 24 requests/s, busy slots FAQ=8 long=48 total=56; at 70% utilization 80 slots = 5 GPUs
normal load one shared pool, 80 slots FAQ wait, mean of 5 seeds: p95= 0.00 s p99= 0.00 s share>1s=0.000
normal load split pools 12 + 68 slots FAQ wait, mean of 5 seeds: p95= 0.09 s p99= 0.19 s share>1s=0.000
research burst x1.6 one shared pool, 80 slots FAQ wait, mean of 5 seeds: p95=170.71 s p99=177.15 s share>1s=0.990
research burst x1.6 split pools 12 + 68 slots FAQ wait, mean of 5 seeds: p95= 0.09 s p99= 0.19 s share>1s=0.000
after a 2x step: 160 slots needed (+5 GPUs); until they are ready, backlog grows 32 slot-s per s
over 180 s: 5760 slot-seconds of backlog = 2469 average requests queued
relative cost per hour: base 50 units; holding 5 prewarmed GPUs adds 50; one CPU search node is 1
Reading it:
- CPU is cheap here: 1.12 busy cores need one node for throughput; add nodes for memory and failure zones, not load.
- The GPU path carries 24 requests per second, of which research queries are 20 percent of the raw traffic but 48 of the 56 busy slots (86 percent of the GPU time), and a single shared pool needs 80 slots, which is 5 GPUs at 70 percent utilization (the committed split plan below rounds each pool up to whole GPUs).
- Normal load: both layouts give FAQ users essentially no queueing (shared p95 0.00 s, split 0.09 s); the split costs a little because its pools cannot borrow from each other.
- Burst: with the shared pool, FAQ p95 wait is 170.71 s and 99.0 percent of FAQ requests wait more than a second; with the split pools it stays at 0.09 s. The long pool is itself overloaded in this scenario, which is why it also needs admission control and a deadline.
- Scaling lag: a step to twice the load needs 160 slots (5 more GPUs), and during the 180 s start-up the backlog grows at 32 slot-seconds per second, reaching 5,760 slot-seconds, the work of about 2,469 average requests. That is why a reactive policy alone cannot meet a latency target for a step increase. Holding 5 spare GPUs raises the hourly cost from 50 to 100 relative units while held, so prewarm on a schedule (or on leading indicators such as the time of day) instead of holding the spare capacity permanently.
The committed plan
The simulation compares 12 + 68 slots to isolate the effect of splitting. A real deployment buys whole GPUs and applies the rule of at least two replicas per tier, so the plan below recomputes the pools from the same busy-slot figures, for normal load and for a scheduled peak at twice the load.
import math
SLOTS_PER_GPU, TARGET_UTIL = 16, 0.7
load_faq, load_long = 8, 48 # busy slots from the sizing run
def plan(scale):
faq_slots = math.ceil(scale * load_faq / TARGET_UTIL)
long_slots = math.ceil(scale * load_long / TARGET_UTIL)
faq_gpus = max(2, math.ceil(faq_slots / SLOTS_PER_GPU)) # at least two replicas per tier
long_gpus = max(2, math.ceil(long_slots / SLOTS_PER_GPU))
return faq_slots, long_slots, faq_gpus, long_gpus
for name, scale in (("normal", 1), ("scheduled peak at 2x load", 2)):
fs, ls, fg, lg = plan(scale)
cpu = 2 # one node covers throughput; a second for a separate failure zone
cost = (fg + lg) * 10 + cpu * 1
print(f"{name:26s} FAQ pool {fs:3d} slots -> {fg} GPUs | research pool {ls:3d} slots -> {lg} GPUs | CPU search nodes {cpu} | relative cost {cost} per hour")
shared = math.ceil(math.ceil((load_faq + load_long) / TARGET_UTIL) / SLOTS_PER_GPU)
print(f"one shared pool at normal load: {shared} GPUs = {shared * 10} units of GPU cost; split pools: {sum(plan(1)[2:])} GPUs = {sum(plan(1)[2:]) * 10} units")
lead = 15 * 60
print(f"prewarm lead: start the extra GPUs {lead // 60} minutes ({lead} s) before the peak, against an assumed {180} s start-up")
Output:
normal FAQ pool 12 slots -> 2 GPUs | research pool 69 slots -> 5 GPUs | CPU search nodes 2 | relative cost 72 per hour
scheduled peak at 2x load FAQ pool 23 slots -> 2 GPUs | research pool 138 slots -> 9 GPUs | CPU search nodes 2 | relative cost 112 per hour
one shared pool at normal load: 5 GPUs = 50 units of GPU cost; split pools: 7 GPUs = 70 units
prewarm lead: start the extra GPUs 15 minutes (900 s) before the peak, against an assumed 180 s start-up
| Tier | Normal load | Scheduled peak at 2x load |
|---|---|---|
| CPU search nodes | 2 | 2 |
| FAQ GPU pool | 2 (12 slots of load, but two replicas) | 2 |
| Research GPU pool | 5 | 9 |
| Relative cost per hour | 72 units | 112 units |
Reading it: the bulkhead costs 2 more GPUs than one shared pool (7 against 5, or 70 against 50 units, 40 percent more at normal load), and that is the price of keeping FAQ latency flat during a research burst; the FAQ pool is two GPUs only because of the replica rule. Prewarming is a schedule: with a daily peak starting at 09:00 (assumed), raise the research pool from 5 to 9 GPUs by 08:45. Fifteen minutes is five times the assumed 180 s start-up, leaving margin for health checks and slow model loads, and the pool scales back after the peak with a cool-down.
Trade-offs and mistakes
- More caching saves the most money but risks stale or cross-user answers: key by permission scope and index version and give it a time-to-live.
- Small model for FAQ: cheaper and faster, but you must show on an evaluation set that quality holds, and keep a fallback to the large model for low-confidence cases.
- Misclassification: a research question routed to the FAQ path gets a thin answer, and the reverse wastes money. Log the route, review samples, and let the FAQ path escalate when retrieval scores are weak.
- Mistakes: sizing for average load instead of peak and variability; autoscaling on CPU; one shared queue with no admission control; counting only generation cost and ignoring the cache and the reranker; scaling down right after a spike; treating the assumed numbers here as facts about your system.
Unlock Full Question Bank
Get access to all 11 Retrieval-Augmented Generation (RAG) interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.