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.
Explain metadata filtering in a retrieval pipeline. How would you design query-time filters so that retrieved documents are relevant to the user and respect access controls, and what goes wrong with filtered ANN search?
Sample Answer
Direct answer
Metadata filtering restricts vector search to documents whose attributes match a condition: the user's tenant, language, document type, date range, or the groups allowed to read the document. Done well it is applied inside the retrieval step, so access control is enforced before any text reaches the model. The hard part is that an ANN index (approximate nearest neighbour: a structure that finds close vectors without comparing with all of them) is built around similarity, not around your attributes. Filtering after the search loses results; filtering during the search can walk a graph or scan cells that contain few allowed items; the right strategy depends on how selective the filter is (the fraction of documents that pass).
Designing the filters
- Two kinds of filter, treated differently. Relevance filters narrow results to what the user wants (language, product version, date). Access filters decide what the user may see at all. A relevance filter that misses costs quality; an access filter that misses is a data leak. So access filters are mandatory, derived from the authenticated identity on the server (never from text the model or the user typed), and applied inside the query.
- Store attributes with each chunk, not only with the document. Each chunk carries its document id, tenant, ACL groups (access-control list: who may read), language, version and timestamps, so the filter is evaluated on the chunk the index returns. Permission changes must propagate: either update chunk metadata or check the current ACL at result time for the final short list.
- Defence in depth for access. Filter inside retrieval for efficiency; re-check permission on the returned documents before building the prompt, because the index can be stale; and never place content the user may not see into the prompt, since the model cannot be trusted to withhold it.
- Choose the filter strategy by selectivity:
- Pre-filter, then exact scan: when few documents pass (a small tenant), score only those. Cost is proportional to the number of matches and recall is exact. The engine finds the matches without scanning everything through an attribute index, the same idea as a database index: a lookup table from each attribute value (tenant 3, language fr) to the ids of the documents that carry it.
- Filter during the ANN search: skip disallowed items while scanning or traversing. Good for moderate selectivity if the engine supports it.
- Post-filter: retrieve the top candidates, then drop the disallowed. Simple, but breaks when the filter is selective.
- Partition by the filter key: a separate index (or partition) per tenant when tenants are large and queries always carry the tenant.
What goes wrong with filtered ANN search, computed
Stand-ins: the index is a small from-scratch IVF (inverted file: k-means groups vectors into cells and a query scans only the nearest cells) built with scikit-learn 1.5.2 on synthetic clustered vectors; "post-filter" asks the ANN for 3 times k candidates and keeps those that pass; "in-scan" scans the same 4 nearest cells but scores only allowed rows. (overfetch and "in-scan" are names used in the code, not product terms.) Recall@10 is measured against the exact top 10 among the allowed rows. The last lines compute a contrastive training loss on a hand-set 3 by 3 similarity matrix, explained in the final bullet of the reading section.
Columns of the printed lines: sel is the selectivity, the fraction of documents that pass the filter (0.497 means about half). post-filter recall and in-scan recall are recall@10 for the two strategies. short lists is the fraction of queries for which post-filtering returned fewer than 10 results (0.03 means 3 percent of queries, 1.00 means every query). exact-prefilter cost is the number of documents the exact pre-filter scan scores, which is the number of allowed documents. ANN scan is the average number of documents inside the 4 cells that the approximate search looks at per query.
import os
os.environ["OMP_NUM_THREADS"] = "1"
import numpy as np
from sklearn.cluster import KMeans
rng = np.random.default_rng(0)
n, d, C, k, nprobe, overfetch = 30000, 32, 40, 10, 4, 3
centers = rng.normal(size=(C, d)) * 0.8
X = (centers[rng.integers(0, C, n)] + rng.normal(size=(n, d))).astype("float32")
Q = (centers[rng.integers(0, C, 150)] + rng.normal(size=(150, d))).astype("float32")
D2 = (Q**2).sum(1)[:, None] - 2 * Q @ X.T + (X**2).sum(1)[None, :]
km = KMeans(C, n_init=1, random_state=0).fit(X)
cell, cents = km.labels_, km.cluster_centers_
def run(mask, label):
"""mask[i] is True when document i is visible to the user (tenant, language, ACL...)."""
allowed = np.where(mask)[0]
truth = [allowed[np.argsort(D2[qi, allowed])[:k]] for qi in range(len(Q))]
# (a) pre-filter, exact: score only allowed rows
cost_pre = len(allowed)
# (b) post-filter: ANN gets overfetch*k candidates from ALL rows, then drop the disallowed ones
# (c) in-scan filter: scan the nearest cells but only score allowed rows
r_post = r_scan = short = scanned_scan = 0
for qi in range(len(Q)):
cells = np.argsort(((cents - Q[qi]) ** 2).sum(1))[:nprobe]
in_cells = np.where(np.isin(cell, cells))[0]
cand = in_cells[np.argsort(D2[qi, in_cells])[:overfetch * k]]
kept = cand[mask[cand]][:k]
r_post += len(set(kept) & set(truth[qi])); short += len(kept) < k
ok = in_cells[mask[in_cells]]
top = ok[np.argsort(D2[qi, ok])[:k]]
r_scan += len(set(top) & set(truth[qi])); scanned_scan += len(in_cells)
m = k * len(Q)
print(f"{label:34s} sel={mask.mean():6.3f} post-filter recall {r_post/m:5.3f} (short lists {short/len(Q):5.2f}) "
f"in-scan recall {r_scan/m:5.3f} exact-prefilter cost {cost_pre:6d} vs ANN scan {scanned_scan/len(Q):5.0f}")
print("A. filter independent of meaning (for example a random language tag)")
for sel in (0.5, 0.1, 0.01, 0.002):
run(rng.random(n) < sel, f"random tag, {sel:.1%} of docs")
print("B. filter correlated with meaning (for example a tenant that owns whole topics; 10 tenants each own a random set of the 40 topic cells)")
tenant_of_cell = rng.integers(0, 10, C) # 10 tenants, each owns about 4 topic cells
tenant = tenant_of_cell[cell]
run(tenant == 3, "tenant 3 only")
# queries come from any topic, but the user may only see tenant 3
# contrastive training objective (InfoNCE) on a batch of 3 query/doc pairs, hand-set similarities
sim = np.array([[0.9, 0.2, 0.1], [0.3, 0.8, 0.2], [0.1, 0.4, 0.7]]) # sim[i][j] = query i vs doc j
tau = 0.1
logits = sim / tau
row_loss = -np.log(np.exp(np.diag(logits)) / np.exp(logits).sum(1)) # one loss per query: -log(probability of its own document)
loss = row_loss.mean()
print(f"InfoNCE per-query losses: {np.round(row_loss, 4).tolist()}")
print(f"InfoNCE loss (temperature {tau}) on the 3x3 similarity matrix: {loss:.4f} | guessing among 3 documents gives {np.log(3):.4f}")
Output:
A. filter independent of meaning (for example a random language tag)
random tag, 50.0% of docs sel= 0.497 post-filter recall 0.908 (short lists 0.03) in-scan recall 0.911 exact-prefilter cost 14904 vs ANN scan 3115
random tag, 10.0% of docs sel= 0.099 post-filter recall 0.286 (short lists 1.00) in-scan recall 0.857 exact-prefilter cost 2979 vs ANN scan 3115
random tag, 1.0% of docs sel= 0.010 post-filter recall 0.031 (short lists 1.00) in-scan recall 0.581 exact-prefilter cost 308 vs ANN scan 3115
random tag, 0.2% of docs sel= 0.002 post-filter recall 0.006 (short lists 1.00) in-scan recall 0.361 exact-prefilter cost 61 vs ANN scan 3115
B. filter correlated with meaning (for example a tenant that owns whole topics; 10 tenants each own a random set of the 40 topic cells)
tenant 3 only sel= 0.027 post-filter recall 0.050 (short lists 0.97) in-scan recall 0.120 exact-prefilter cost 820 vs ANN scan 3115
InfoNCE per-query losses: [0.0012, 0.0092, 0.0509]
InfoNCE loss (temperature 0.1) on the 3x3 similarity matrix: 0.0205 | guessing among 3 documents gives 1.0986
Reading the run
- Selectivity breaks post-filtering. With a random tag passing half the documents, post-filter recall is 0.908. At 10 percent it is 0.286, at 1 percent 0.031 and at 0.2 percent 0.006, and nearly every query returns fewer than 10 results (the short-list column). The candidates were chosen without regard to the filter, so almost none survive.
- In-scan filtering holds up better but still degrades: 0.911, 0.857, 0.581, 0.361 over the same selectivities, because the 4 nearest cells contain only a handful of allowed documents. A graph index (nodes linked to their near neighbours, searched by walking from node to node) fails in the analogous way, which this IVF run does not show: if only a small fraction of nodes pass the filter, most of the links from a visited node lead to disallowed nodes, so the walk either stops early with too few results or has to pass through disallowed nodes to get anywhere, which costs extra work. The remedy is more search effort as selectivity drops (scan more cells or widen the graph search), or switching to the pre-filter exact scan.
- Cost crossover. At 0.2 percent selectivity the exact pre-filter scores 61 documents, against 3115 scanned by the ANN; at 10 percent the two are about equal (2979 against 3115). So below roughly that selectivity (in this setup) exact scan over the matches is both exact and cheaper.
- Correlated filters are the worst case. When the filter follows the topic structure (a tenant owns whole topic cells), the query's nearest cells may contain no allowed documents at all: recall was 0.050 for post-filter and 0.120 for in-scan at 2.7 percent selectivity. Routing must then be filter-aware, for example by partitioning by tenant.
- Training objective link. A retriever's embeddings are usually trained contrastively: given a batch of query and document pairs, the loss pulls each query toward its own document and pushes it away from the other documents in the batch (the in-batch documents, which serve as negatives). InfoNCE is one such loss: for each query, a softmax over its similarity to every document in the batch, with the query's own document as the target, and the loss is the negative log of the probability given to that target. The temperature τ divides the similarities before the softmax; a small τ (0.1 here) makes the softmax sharper. In the hand-set 3 by 3 matrix, row i is query i, column j is document j, and the diagonal holds the true pairs (0.9, 0.8, 0.7). Dividing by 0.1 turns row 0 into logits 9, 2, 1, so the true document gets nearly all the probability and that query's loss is tiny (the printed per-query losses are 0.0012, 0.0092 and 0.0509, the last being largest because document 1 scores 0.4 against query 2's own 0.7). Their mean is 0.0205. A loss of 0 means the right document is always ranked with certainty, and guessing uniformly among 3 documents gives ln3=1.0986, so 0.0205 is close to the best possible value on this hand-set batch. The link to filtering: the loss only teaches similarity, never permissions, so filters are applied at query time and cannot be learned away. Hard negatives (wrong documents that look similar to the query, for example other documents from the same tenant) make the training harder and sharpen the ranking within the allowed set.
Latency and recall impact, summarised
Low selectivity means a choice between more work per query (higher search effort), or switching strategy; wide filters are cheap. Monitor recall by filter selectivity bucket on a sampled exact check, and report latency by bucket, because the average hides the rare selective filters.
Common mistakes
- Using post-filtering for access control or for selective filters, then wondering why users get few or no results.
- Filtering after generation, or asking the model to hide content it already saw.
- Building the filter from user-supplied text instead of the authenticated session.
- Testing on one filter value; selectivity varies by tenant and recall varies with it.
Design a caching and precomputation layer for a RAG system so frequent queries meet a tight latency target while answers still carry citations and the corpus changes every few hours. How do you handle invalidation and the freshness-versus-cost trade-off?
Sample Answer
Direct answer
Cache in layers, and key every layer by the version of the evidence it depends on, so a cached answer is valid exactly as long as the documents it cites are unchanged. Layer 1 caches query embeddings (cheap, and valid until the embedding model changes). Layer 2 caches retrieval results keyed by normalised query (the query with trivial differences such as capitals and extra spaces removed, so equivalent strings share one key) and index version. Layer 3 caches the finished answer together with its citations, and each entry records the document ids and versions it cited; when the corpus changes, only the entries that cite a changed document are dropped. For a corpus that changes every few hours (a 6-hour cadence is the case I simulate) this keeps the hit rate high without serving a stale citation, and a small warm-up job (a background job that regenerates the most popular dropped entries before users ask for them) can refill the head of the cache. A fixed time-to-live (TTL) alone is the weak option because it either serves stale answers or throws away good entries.
Design
- Normalise the key. Lowercase, trim, collapse whitespace, optionally map known paraphrases of frequent questions to one canonical form. Include the user's access scope in the key (an answer built from restricted chunks must never be served to someone without access) and the prompt and model configuration version.
- Precompute for the head. Frequent questions follow a long-tailed popularity curve (a few questions are asked very often and a long tail of questions is asked rarely), so a small set of head queries carries most traffic. Generate those answers ahead of time after each index update, and serve the tail live.
- Citation-preserving entries. Store the answer text, the chunk ids and document versions it cites, and the display data for the citations. A hit then renders the same citations a fresh answer would. On a hit, optionally run a cheap validity check: are all cited (doc, version) pairs still current? If not, treat it as a miss.
- Invalidation. On each index publish, receive the list of changed document ids and drop entries whose dependency set intersects it (an inverted map from document id to cache keys makes this one lookup per changed document: for example, doc_17 maps to the two cache keys whose answers cite it, so when doc_17 changes, exactly those two entries are dropped and an entry citing only doc_42 stays). Full flush is the fallback when a change cannot be attributed, for example a new embedding model.
- Freshness versus cost. Cost is the number of generations; freshness is the bound on how long an answer can outlive a change. Dependency invalidation gives a bound of zero for cited documents. A change that makes a document newly relevant to a query that did not cite it before does not invalidate that query's entry, so pair it with a maximum entry age (for example one cadence period) as a backstop and say that this residual staleness exists.
- Semantic caching (serving a stored answer for a different but similar query) saves more but risks answering a subtly different question; use it only above a strict similarity threshold and only for non-sensitive head queries, and measure wrong-answer rate on a labelled sample.
Worked example, simulated
The simulation is a model of the traffic with stated assumptions, not a measurement of any real system: 300 distinct frequent queries with popularity proportional to 1/rank (a Zipf-like curve: the second most popular query gets half the traffic of the first, the third a third, and so on), 1,000 requests per hour for 24 hours, each answer citing 3 of 1,000 documents, and an update that changes 50 documents at the stated hours. A p95 latency target (the 95th percentile) means 95 percent of requests must finish within the target time, so at most 5 percent may be slow. Hit latency is assumed to be 20 ms and a miss 2,000 ms, so the "mean_ms" column is arithmetic on those assumed values. Each row averages 10 seeds. "ttl" keeps entries for 6 hours with no invalidation; "flush" clears everything at each update; "dep" drops only entries that cite a changed document. The simulation counts a stale answer only when a cited document has changed (the residual case above is not modelled).
import os
os.environ["OMP_NUM_THREADS"] = "1"
import numpy as np
# Simulation set-up (all values are assumptions of the demo, not measurements):
# 300 distinct frequent queries with Zipf popularity, 1000 requests per hour for 24 hours,
# each answer cites 3 of 1000 documents, corpus updated at hours 6, 12, 18 (50 documents change each time).
Q, D, PER_HOUR, HOURS, CHANGED = 300, 1000, 1000, 24, 50
HIT_MS, MISS_MS = 20, 2000
def run(policy, seed, UPDATES):
rng = np.random.default_rng(seed)
cites = rng.integers(0, D, size=(Q, 3))
pop = 1 / np.arange(1, Q + 1); pop /= pop.sum()
ver = np.zeros(D, dtype=int)
cache = {} # query -> (stored_at_hour, versions of cited docs at that time)
hits = stale = total = gens = 0
for h in range(HOURS):
if h in UPDATES:
changed = rng.choice(D, size=CHANGED, replace=False)
ver[changed] += 1
if policy == "flush":
cache.clear()
if policy.startswith("dep"):
for q in list(cache):
if any(cache[q][1][j] != ver[cites[q][j]] for j in range(3)):
del cache[q]
for q in rng.choice(Q, size=PER_HOUR, p=pop):
total += 1
e = cache.get(q)
if e is not None and policy == "ttl" and h - e[0] >= 6:
e = None
if e is None:
cache[q] = (h, tuple(ver[cites[q]])); gens += 1
else:
hits += 1
stale += any(e[1][j] != ver[cites[q][j]] for j in range(3))
return hits / total, stale / total, gens
for label, ups in [("updates at hours 6, 12, 18", {6, 12, 18}), ("updates every hour", set(range(1, 24)))]:
print(label)
print("policy hit_rate stale_served generations mean_ms (mean over 10 seeds)")
for pol in ["ttl", "flush", "dep"]:
runs = np.array([run(pol, s, ups) for s in range(10)])
r = runs.mean(axis=0)
mean_ms = r[0] * HIT_MS + (1 - r[0]) * MISS_MS
print(f"{pol:<7} {r[0]:.3f} {r[1]:.4f} {r[2]:7.0f} {mean_ms:6.0f}")
print(f" hit rate per seed: min {runs[:, 0].min():.3f}, max {runs[:, 0].max():.3f}, "
f"seeds under 0.95: {int((runs[:, 0] < 0.95).sum())} of 10")
if label.startswith("updates every") and pol != "flush":
print(f" generations per seed: min {runs[:, 2].min():.0f}, max {runs[:, 2].max():.0f}")
print("p95 equals the hit latency only if misses are under 5% of requests: need hit_rate >= 0.95")
p_inval = 1 - (1 - CHANGED / D) ** 3
print(f"chance a 3-citation entry is dropped by one update of {CHANGED} of {D} documents: {p_inval:.3f}, "
f"so its expected life is {1 / p_inval:.1f} update periods")
Output:
updates at hours 6, 12, 18
policy hit_rate stale_served generations mean_ms (mean over 10 seeds)
ttl 0.952 0.0042 1160 116
hit rate per seed: min 0.951, max 0.952, seeds under 0.95: 0 of 10
flush 0.950 0.0000 1190 118
hit rate per seed: min 0.950, max 0.951, seeds under 0.95: 0 of 10
dep 0.982 0.0000 427 55
hit rate per seed: min 0.981, max 0.983, seeds under 0.95: 0 of 10
updates every hour
policy hit_rate stale_served generations mean_ms (mean over 10 seeds)
ttl 0.952 0.2982 1161 116
hit rate per seed: min 0.951, max 0.952, seeds under 0.95: 0 of 10
generations per seed: min 1149, max 1165
flush 0.793 0.0000 4970 430
hit rate per seed: min 0.791, max 0.795, seeds under 0.95: 10 of 10
dep 0.952 0.0000 1161 116
hit rate per seed: min 0.951, max 0.953, seeds under 0.95: 0 of 10
generations per seed: min 1140, max 1182
p95 equals the hit latency only if misses are under 5% of requests: need hit_rate >= 0.95
chance a 3-citation entry is dropped by one update of 50 of 1000 documents: 0.143, so its expected life is 7.0 update periods
Reading it. With updates every 6 hours, "dep" has the highest hit rate (0.982), zero stale answers and about 427 generations per day, against about 1,190 for "flush" and 1,160 for "ttl" (which also serves 0.0042 of requests with a stale citation). With updates every hour, the picture changes: "flush" falls to a hit rate of 0.793 and 4,970 generations, "ttl" serves 0.2982 of requests with a changed document behind them, and "dep" holds 0.952 hit rate with none stale. Note the p95 line: a latency target stated at p95 is met by the hit path only when the miss share is below 5 percent, so the hit rate is the number to protect. Only the 6-hour "dep" row clears 0.95 with margin (0.981 to 0.983 per seed). Every other row that passes sits on the line: "ttl" and "flush" at the 6-hour cadence and "ttl" and "dep" at the hourly cadence print 0.950 to 0.953, a margin of at most about 0.003 over the target. The hit rate also depends on the assumed number of distinct queries and the assumed update size, so those assumed inputs, not the policy, decide which side of 0.95 these rows land on: treat them as at the limit, not as clearing it. "flush" at hourly updates fails in every seed (0.791 to 0.795). The practical reading is that hourly updates leave a 5 percent miss budget with almost no slack even when invalidation is exact, which is why the warm-up job and single-flight below matter.
In the hourly case "ttl" and "dep" print the same hit rate and nearly the same generations (1,161), and that is a coincidence of the settings, not a bug and not a shared mechanism. With 50 of 1,000 documents changing per update, an entry that cites 3 documents is dropped by a given update with probability 1 - (1 - 50/1000)^3 = 0.143, so its expected life is about 7.0 hourly updates, close to the 6-hour TTL. The per-seed generation counts differ (the program prints a minimum and maximum for the two non-flush policies), and the real difference is in the stale column: "ttl" serves 0.2982 stale and "dep" serves none. The zero for "dep" holds by construction, because its invalidation rule and the stale test compare the same stored and current versions; for "dep" the simulation measures hit rate and generations, while the stale column is informative for "ttl", where it moves with the update cadence (0.0042 at 6-hour updates, 0.2982 at hourly).
How the simulation works, in the order the code runs:
cites[q]lists the 3 documents that queryqcites, andverholds the current version number of each document.- The cache maps a query to a pair: the hour it was stored and the versions of its 3 cited documents at that moment. This is the "cited (doc, version) pairs" record from the design.
- On an update hour, 50 random documents get their version bumped. Policy "flush" clears the whole cache. Policy "dep" (the code tests
policy.startswith("dep"), which just matches that name) deletes every entry whose stored versions no longer equal the current versions of its cited documents. - Each request looks the query up. A miss, or under "ttl" an entry 6 or more hours old, triggers a generation and stores a fresh entry. A hit counts as stale when any stored version differs from the current one.
Trade-offs and failure modes
- Thundering herd. After an invalidation, many requests for the same head query miss at once; collapse them into one generation (single-flight: the first request starts the generation, and requests for the same key that arrive meanwhile wait for its result instead of starting their own) so cost does not spike.
- Memory. Entries hold text and citation data; bound the cache and evict by recency and cost-to-regenerate.
- Wrong keys. Forgetting the access scope, prompt version or model version in the key serves answers built under different rules.
- Cache poisoning. An injected or wrong answer, once cached, is served repeatedly; do not cache answers flagged by output checks, and let an operator purge by document id.
- Common mistakes: one TTL for everything; caching answers without their citation versions; invalidating by flushing the whole cache on each hourly publish.
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.
You must choose a vector database for a production semantic search service holding about a million 768-dimension embeddings, with a tight tail-latency target, near-real-time inserts and deletes, and multi-region replication. What criteria drive your choice and how do you validate it?
Sample Answer
Direct answer
For about a million 768-dimension vectors, the whole index fits in RAM on one machine, so the decision is driven less by raw capacity and more by four operational properties: tail latency under filters, how fast an insert or delete becomes visible, how replication across regions behaves, and what happens during failure and rebuild. I would pick an engine with an in-memory graph index (HNSW style: a navigable graph where a query hops toward nearer neighbours), one full replica per region, and I would only accept it after a validation run on my own vectors and my own filters. A benchmark on someone else's data does not count as evidence.
Criteria, in the order I would apply them
- Capacity arithmetic (does it fit, does it need sharding?). A vector is 768 numbers. As 4-byte floats that is 3072 bytes, so one million vectors is about 3.07 GB. The graph adds roughly 128 bytes per vector under the stated assumption of 16 links per node (doubled at the bottom layer) with 4-byte ids. One replica is about 3.2 GB, which a single node holds. So I would not pay the complexity of sharding; I would pay for replicas (availability and read throughput) instead.
- Recall at the latency target. ANN (approximate nearest neighbour) search trades a little recall for a lot of speed. Recall@k is the share of the true top-k (found by exact brute force) that the index returns. The engine must hold the recall I set (for example 0.95 at k=10) at the query rate I need, with the filters my product uses. Every approximate engine has a search-effort parameter that trades work for recall:
efSearch(the width of the candidate list) in HNSW-style graph engines,nprobe(how many k-means cells are scanned) in IVF-style engines. That parameter is what the validation sweep below varies. - Tail latency, not average. p99 (the latency that 99 percent of queries beat) is set by the slowest few queries: cold pages, garbage collection, a background merge or compaction, a big filter. I would ask how the engine behaves while it is compacting (a background job that merges the small files that fresh writes create into larger ones and physically drops deleted rows) or while writes arrive.
- Freshness: insert, update, delete. Ask how long after a write the vector is searchable, and whether a delete removes the vector from results immediately (a tombstone, meaning a mark that hides the row until a later cleanup) and when the space is reclaimed.
- Filtered search. If queries carry metadata filters (tenant, language, date), the engine must filter inside the search, not by throwing results away afterwards.
- Multi-region replication. Is replication built in, asynchronous or synchronous, what is the lag, and what is read-your-writes behaviour in the writer's region (after a client inserts a vector, does that same client's next search see it)? With synchronous replication the write is acknowledged only after the other region has also stored it, so every insert waits for a wide-area round trip (a message crossing between regions and back, far slower than a hop inside one data centre); with asynchronous replication the write is acknowledged locally and copied afterwards, which makes a second region briefly stale. I would choose asynchronous replication with a lag alarm unless the product needs a delete to be effective everywhere instantly (then deletes need a separate fast path).
- Operations and exit cost. Backup and restore time, rebuild time from the source of truth, upgrade behaviour, monitoring, and how hard it is to move away (keep embeddings and ids in your own store so the index is always rebuildable).
Memory budget, computed, plus a validation harness in the same program. The index in part 2 is a small from-scratch IVF (inverted file: k-means groups the vectors into cells, and a query scans only the few nearest cells) used as a stand-in for the candidate engine; the harness, not the stand-in, is what carries over to the real engine. IVF and HNSW are different structures with different recall-versus-work curves, so the IVF numbers below do not transfer to a graph engine. What transfers is the method: exact ground truth, a sweep of the search-effort parameter (nprobe here, efSearch there), and a delete test. IVF is used because it is short to write from scratch.
import os
os.environ["OMP_NUM_THREADS"] = "1"
import numpy as np
from sklearn.cluster import KMeans
# Part 1: memory budget for 1,000,000 vectors of 768 dimensions
N, D = 1_000_000, 768
GB = 1e9
raw32 = N * D * 4
raw8 = N * D * 1
pq = N * 96 # product quantization (PQ): each vector compressed to a short code; 96 bytes is an assumed code length
graph = N * 16 * 2 * 4 # graph index, 16 links per node, doubled at the base layer, 4-byte ids
print(f"float32 vectors : {raw32/GB:.2f} GB")
print(f"int8 vectors : {raw8/GB:.2f} GB")
print(f"PQ 96B codes : {pq/GB:.3f} GB")
print(f"graph links : {graph/GB:.3f} GB")
print(f"float32 + graph : {(raw32+graph)/GB:.2f} GB per replica")
print(f"3 regions x 2 replicas : {6*(raw32+graph)/GB:.1f} GB total RAM")
# Part 2: validation harness on a small synthetic set. A from-scratch IVF index
# (inverted file: k-means cells, scan only the nearest cells) is a stand-in for
# the candidate engine; the harness, not the engine, is what carries over.
rng = np.random.default_rng(0)
n, d, ncell = 20000, 32, 64
centers = rng.normal(size=(ncell, d)) * 0.8
X = (centers[rng.integers(0, ncell, n)] + rng.normal(size=(n, d))).astype("float32")
Q = (centers[rng.integers(0, ncell, 200)] + rng.normal(size=(200, d))).astype("float32")
def exact_topk(X, Q, k, alive=None):
d2 = (Q**2).sum(1)[:, None] - 2 * Q @ X.T + (X**2).sum(1)[None, :]
if alive is not None:
d2[:, ~alive] = np.inf
return np.argsort(d2, axis=1)[:, :k]
class IVF:
def __init__(self, X, ncell):
self.km = KMeans(ncell, n_init=1, random_state=0).fit(X)
self.X = X
self.cell = self.km.labels_
self.alive = np.ones(len(X), bool)
def search(self, Q, k, nprobe):
cd = ((Q[:, None, :] - self.km.cluster_centers_[None]) ** 2).sum(2)
out, ops = [], 0
for qi, q in enumerate(Q):
cells = np.argsort(cd[qi])[:nprobe]
scanned = np.where(np.isin(self.cell, cells))[0]
ops += len(scanned) # a tombstoned row is still read, then discarded
ids = scanned[self.alive[scanned]]
dd = ((self.X[ids] - q) ** 2).sum(1)
out.append(ids[np.argsort(dd)[:k]])
return out, ops / len(Q)
def recall(found, truth, k):
return np.mean([len(set(f) & set(t)) / k for f, t in zip(found, truth)])
k = 10
idx = IVF(X, ncell)
truth = exact_topk(X, Q, k)
print("\nnprobe recall@10 avg distance computations per query (brute force = 20000)")
for nprobe in (1, 2, 4, 8, 16):
f, ops = idx.search(Q, k, nprobe)
print(f"{nprobe:6d} {recall(f, truth, k):9.3f} {ops:8.0f}")
# churn test: delete 20% of rows, then check recall against the exact answer over the live rows
dead = rng.choice(n, n // 5, replace=False)
idx.alive[dead] = False
truth2 = exact_topk(X, Q, k, idx.alive)
f, ops = idx.search(Q, k, 4)
print(f"\nafter deleting 20% (tombstones): recall@10 at nprobe=4 = {recall(f, truth2, k):.3f}, "
f"distance computations per query = {ops:.0f}")
Output:
float32 vectors : 3.07 GB
int8 vectors : 0.77 GB
PQ 96B codes : 0.096 GB
graph links : 0.128 GB
float32 + graph : 3.20 GB per replica
3 regions x 2 replicas : 19.2 GB total RAM
nprobe recall@10 avg distance computations per query (brute force = 20000)
1 0.732 329
2 0.825 644
4 0.893 1274
8 0.944 2536
16 0.984 5052
after deleting 20% (tombstones): recall@10 at nprobe=4 = 0.888, distance computations per query = 1274
Reading the run
- Part 1 is arithmetic on the stated sizes: float32 vectors are 3.07 GB, the assumed graph links 0.128 GB, so one replica is 3.20 GB and three regions with two replicas each need 19.2 GB of RAM in total. Compression (int8 or product quantization, which stores a short code per vector) cuts memory further but costs recall, which is why it is a lever to test, not a default.
- Part 2 shows the shape of the measurement you must run on the real engine: recall against exact search rises as more cells are scanned (0.732 at 1 cell, 0.984 at 16 cells in this synthetic set) while the work per query, counted as distance computations instead of seconds, rises with it (329 to 5052, against 20000 for brute force). The latency target picks a point on this curve; you then re-measure p99 on the real hardware. How to read a sweep: a recall@10 target such as 0.95 is a product decision (what fraction of the best results the user can afford to lose). Here 0.944 at 8 cells just misses 0.95 and 0.984 at 16 cells clears it for about twice the work (2536 versus 5052 computations), so 16 is the setting to carry to the latency test. On the real engine the same reading applies with p99 latency on the x-axis: take the cheapest setting that clears the recall target and check that its p99 is inside the budget.
- The churn line shows that after 20 percent of rows were deleted, the scan work did not shrink (1274 computations before and after), because tombstoned rows are still read and then discarded, and recall against the true answer over live rows stayed near the earlier value. That is the point of testing deletes: a real engine can behave worse, for example a graph whose deleted nodes break routes.
How I validate (what I would actually run)
- Use real data. Take a few hundred thousand real vectors and several thousand real queries, with the real filters, and compute exact top-k as ground truth.
- Recall versus latency sweep. For each candidate, vary its search-effort parameter, plot recall@10 against p50 and p99 latency at the production query rate on the production instance type, and pick the setting that meets recall at the p99 target with headroom.
- Load while writing. Run the same sweep while a steady stream of inserts, updates and deletes is applied at 2 to 3 times the expected rate. Record p99 and recall during background merges.
- Freshness test. Write a marker vector, poll until it appears in results, record the lag distribution; do the same for a delete.
- Region and failure drills. Measure replication lag, kill a node, kill a region, and measure error rate, recovery time and recall after recovery.
- Rebuild drill. Rebuild the index from the source of truth and time it; this is your disaster-recovery plan.
- Cost at target load. Replicas times instance cost, with N+1 headroom (enough replicas that the load is still met after losing any one of them).
Trade-offs and what would flip the choice
- If the team already runs a relational database, the queries are low volume and the latency target is loose, a vector extension of that database removes a system to operate. The tight tail-latency target and region replication are exactly what usually pushes toward a purpose-built engine, so test the extension first and move only if it misses the target.
- If the corpus grows 100 times, the arithmetic changes (hundreds of GB per replica), and sharding plus compression become the main concern.
- If every query carries highly selective filters, filter handling outranks raw speed in the ranking.
Common mistakes
- Choosing from a vendor's published benchmark that used different vectors, filters and recall.
- Reporting average latency, or latency measured with no concurrent writes.
- Treating the vector database as the source of truth, so there is no rebuild path.
- Quoting recall without saying at what k, what ground truth and what filters.
You need to support regulatory compliance (e.g., GDPR) that requires deletion of a user's documents from the RAG index within seconds. Propose an end-to-end design for immediate deletion that covers vector indices, backups, caches, and derived artifacts like fine-tuned models or log-derived features.
Sample Answer
Direct answer
Make deletion a first-class, ordered pipeline with a durable record: write the deletion request to an append-only ledger first, hide the user's chunks from retrieval immediately with a tombstone (a marker checked at query time), purge every cache entry and derived store that references those chunks using a reverse index, and let physical removal (index compaction, backup expiry) follow on a defined schedule, with the ledger replayed after any restore so deleted data cannot reappear. Fast logical deletion in seconds, physical deletion within a bounded, documented window, and a verification step that proves the data is no longer retrievable.
One framing point to settle with legal counsel before building: the GDPR right to erasure (Article 17) requires erasure "without undue delay", and Article 12(3) sets one month (extendable in some cases) to respond to a request. "Within seconds" is therefore an internal service-level target that is stricter than the text of the regulation, which matters for cost; confirm with counsel what applies to your case, including how backups are treated.
Terms used below
A RAG (retrieval-augmented generation) system answers a question by first fetching relevant text and giving it to a language model. The pieces that matter for deletion:
- Chunk: a passage of a document stored as one retrievable unit.
- Embedding: a list of numbers that represents a chunk's meaning; similar chunks get nearby lists.
- Vector index: a data structure that, given a query's embedding, returns the nearest stored embeddings quickly. The lookup of those closest entries is the nearest-neighbour step.
- Compaction: a background job that rewrites the index files and drops entries that were only marked as deleted, so the data is physically gone only after it runs.
- Semantic cache: a cache of past answers keyed by the meaning of the question, so a similar later question can reuse a stored answer that contains retrieved text.
- Fine-tuned model: a model whose weights were further trained on your own data, so some of that data's information lives in the weights.
- Append-only ledger: a log you only add to, never edit, here holding one line per deletion request.
Where the user's data lives (the inventory comes first)
| Location | Why it keeps data | Deletion approach |
|---|---|---|
| Source store (documents, database) | System of record | Delete or anonymise; this is the authoritative step |
| Vector index and keyword index | Embeddings and text of chunks | Tombstone now; physical removal at compaction. Index types differ on in-place deletion, so check the version you use |
| Result and semantic caches | Answers and retrieved chunks | Purge exact entries by a reverse index (a map from each chunk id to the cache keys whose answers used it, so you can find them without scanning the cache); a short time-to-live (an expiry time after which an entry is dropped automatically) is the backstop |
| Backups and snapshots | Point-in-time copies | Do not edit backups; keep the deletion ledger separately and replay it on restore; let backups age out on a fixed retention |
| Logs and traces | Queries and retrieved text | Do not log raw content, or log with a per-user key or short retention; delete by user id |
| Derived features and training sets | Aggregates, labels | Rebuild or delete by user id on the next run; keep lineage (a table recording which source documents and users went into each dataset or model) so you know which sets include the user |
| Fine-tuned models and embeddings trained on the data | Information baked into weights | Cannot be edited out on demand; see below |
| Third parties (hosted embedding, vector or LLM APIs) | Copies you do not control | Contracts and deletion APIs; prefer providers that do not retain inputs |
Ordered flow
- Authenticate the request and resolve the user to the set of chunk ids and document ids (the lineage table from ingestion, which maps each user to the documents and chunks created from their data).
- Append the request to the ledger (durable, outside the index and outside the snapshots).
- Tombstone the chunk ids in the retrieval layer; every query filters tombstoned ids.
- Purge caches through the reverse index.
- Enqueue the asynchronous jobs: compaction, derived features, logs, third-party calls; each reports completion to the ledger.
- Verify: run probe queries that should have retrieved the user's content and assert none of it appears; record the check.
- After the physical deletion deadline, confirm that every enqueued job completed, and alert on those that did not.
Worked example
The program is a minimal in-memory model: an index with tombstones, a cache with a reverse index, a snapshot, and a ledger. It shows (a) the answer served from cache before the deletion, (b) the cache entry gone and the user's chunk invisible after it, and (c) a restore from the old snapshot with and without replaying the ledger. The last table sizes the over-fetch needed when tombstones are filtered after the nearest-neighbour step.
import json
import math
class Store:
"""Minimal model of a RAG stack: an index with tombstones, a semantic cache, a snapshot, and a ledger."""
def __init__(self):
self.index = {} # chunk_id -> (user_id, text)
self.tombstones = set() # chunk ids hidden at query time until a compaction removes them
self.cache = {} # query -> (answer, [chunk_ids that produced it])
self.by_chunk = {} # chunk_id -> set of cache keys (reverse index so purge is exact)
self.ledger = [] # append-only deletion requests, kept outside the snapshots
self.snapshot = None
def add(self, cid, user, text):
self.index[cid] = (user, text)
def search(self, word, k=3):
hits = [c for c, (u, t) in sorted(self.index.items()) if word in t and c not in self.tombstones]
return hits[:k]
def answer(self, query, word):
if query in self.cache:
return self.cache[query][0]
ids = self.search(word)
ans = " / ".join(self.index[c][1] for c in ids) or "no result"
self.cache[query] = (ans, ids)
for c in ids:
self.by_chunk.setdefault(c, set()).add(query)
return ans
def delete_user(self, user):
self.ledger.append(user) # 1. durable record first
doomed = {c for c, (u, _) in self.index.items() if u == user}
self.tombstones |= doomed # 2. hidden from search at once
for c in doomed: # 3. exact cache purge
for key in self.by_chunk.pop(c, set()):
self.cache.pop(key, None)
return sorted(doomed)
def compact(self): # later, off the hot path
for c in list(self.tombstones):
self.index.pop(c, None)
self.tombstones.clear()
def take_snapshot(self):
self.snapshot = json.dumps({c: v for c, v in self.index.items()})
def restore(self, replay_ledger=True):
self.index = {c: tuple(v) for c, v in json.loads(self.snapshot).items()}
self.tombstones.clear(); self.cache.clear(); self.by_chunk.clear()
if replay_ledger:
for user in self.ledger:
self.tombstones |= {c for c, (u, _) in self.index.items() if u == user}
s = Store()
s.add("c1", "alice", "alice invoice dispute")
s.add("c2", "bob", "bob invoice question")
s.take_snapshot() # a backup that still holds alice
print("before delete :", s.answer("invoices?", "invoice"))
print("deleted chunks:", s.delete_user("alice"))
print("cache entry gone:", "invoices?" not in s.cache)
print("after delete :", s.answer("invoices?", "invoice"))
s.compact()
s.restore(replay_ledger=False)
print("restore without ledger replay:", s.search("invoice"))
s.restore(replay_ledger=True)
print("restore with ledger replay :", s.search("invoice"))
# Over-fetch needed when tombstoned entries are filtered after the nearest-neighbour step,
# assuming the deleted entries are spread evenly among the neighbours.
print()
print("deleted_fraction fetch_to_keep_10_live")
for f in (0.0, 0.1, 0.5):
print(f"{f:16.1f} {math.ceil(10 / (1 - f))}")
Output:
before delete : alice invoice dispute / bob invoice question
deleted chunks: ['c1']
cache entry gone: True
after delete : bob invoice question
restore without ledger replay: ['c1', 'c2']
restore with ledger replay : ['c2']
deleted_fraction fetch_to_keep_10_live
0.0 10
0.1 12
0.5 20
How delete_user("alice") runs, in order: (1) it appends "alice" to the ledger, so the request is durable before anything else changes; (2) it finds every chunk id owned by Alice (doomed) and adds them to the tombstone set, which is what makes search skip them from that moment; (3) for each doomed chunk it pops that chunk's entry in by_chunk, which lists the cache keys whose answers contained it, and removes those cache entries, so no stored answer can still show her text. Compaction is a separate later call (compact) that removes the tombstoned entries from index for good.
Reading it: before the deletion the cached answer includes Alice's chunk; delete_user hides the chunk, removes the cache entry and returns the chunk id, and the next query returns only Bob's content. After compaction, a restore from the old snapshot brings Alice's chunk back (['c1', 'c2']) when the ledger is not replayed, and hides it again when it is (['c2']). That is the specific failure this design prevents. This is a minimal illustration of the ordering, not a production system: it has one process, no concurrency, no failure handling, and it does not cover the other stores in the table.
The final table matters for tombstones: if deleted entries remain in the graph or lists and are filtered after retrieval, a query that needs 10 live results must fetch more, 12 at 10 percent deleted and 20 at 50 percent, assuming the deleted entries are spread evenly among the neighbours. The arithmetic: if a fraction f of stored entries is deleted, only 1 - f of what you fetch is live, so you must fetch 10 divided by (1 - f) and round up: 10 / 0.9 = 11.1, which rounds up to 12; 10 / 0.5 = 20. That is why compaction is scheduled by the deleted fraction and not left indefinitely.
Fine-tuned models and derived artifacts
A model fine-tuned on personal data (see the terms above) cannot reliably forget one record on request. The practical design is prevention: do not fine-tune on identifiable user content unless the legal basis and a retrain cadence are agreed; keep training data lineage by user id; exclude deleted users from the next training run and retire the old model on a schedule; and prefer retrieval over fine-tuning for user-specific knowledge, which is itself an argument for RAG in this setting. Say plainly to the stakeholders which artifacts are deleted at once and which are replaced on a cycle.
Trade-offs and failure modes
- Tombstone-only deletion keeps the data physically present until compaction; encryption and access control on the index limit exposure in that window.
- Caches that are keyed by the question and not by the chunks cannot be purged precisely; use the reverse index, or a short time-to-live.
- A deleted chunk can persist in a replica, a read-through cache (a cache that fetches from the source on a miss and keeps the result) or an in-flight request; define the consistency guarantee (for example, no result after the tombstone is acknowledged) and test it.
- Per-user encryption keys (delete the key to make the data unreadable, "crypto-shredding") are an option for backups and logs; the trade-off is that you must store, protect and reliably destroy one key per user, and every read pays a decryption step, so security staff should review it.
- Verification cannot prove absence everywhere; keep an inventory and a signed-off list of stores.
That is every published Retrieval-Augmented Generation (RAG) question for Backend Developer so far. Browse the other topics in this category, or practice this one interactively.