Skip to content

    AI Architect

    Data and Retrieval Architecture for AI Systems

    How retrieval works inside an AI system: embeddings, HNSW, IVF and product quantization, BM25, rank fusion, rerankers, chunking, access control and freshness.

    By Published 28 min read

    Share

    This lesson is part of AI Architect (Intermediate): Design the System. Enroll for free, then sign in, to read it in full.

    What you'll learn: how the retrieval half of an AI system is built and where it breaks: embeddings, HNSW, IVF with product quantization, BM25, rank fusion and rerankers, then the design choices for chunking, access control, multi-tenancy and incremental indexing, each with its cost in recall, latency, memory and risk.

    At a glance

    Figure 1. Retrieval architecture: ingestion path and query path

    Retrieval architecture with ingestion and query pathsDocument store to Event bus (change event); Event bus to Worker (consume); Worker to Vector index (chunks, embeddings); Worker to Lexical index (chunk text); Orchestrator to Retriever (question, identity); Retriever to Policy engine (scope check); Retriever to Vector index (filtered search); Retriever to Lexical index (filtered search); Retriever to Reranker (fused candidates); Eval service to Retriever (replay queries)INGESTION PATH (ASYNCHRONOUS)INDEXESQUERY PATH (SYNCHRONOUS)Document storeDocument storeEvent busEvent busWorker: chunk and embedWorkerchunk and embedVector indexVector indexLexical index: BM25Lexical indexBM25OrchestratorOrchestratorRetriever: access filterRetrieveraccess filterPolicy enginePolicy engineRerankerRerankerEval serviceEval servicechange eventconsumechunks, embeddingschunk textquestion, identityscope checkfiltered searchfiltered searchfused candidatesreplay queries

    How to read this: flowing dashes are the asynchronous ingestion path, arrows with travelling dots are calls the user waits for, and the access filter is applied inside the Retriever on both indexes, not afterwards.

    "Lexical index", "Reranker", "Embedding model" and "Chunker" are added to the course component names on this page only. The Lexical index is a search index over words that serves BM25 scoring.

    • The retrieval layer chooses the text the model sees, so a wrong, stale or forbidden passage is a retrieval defect first.
    • The RAG paper (Lewis et al., arXiv 2005.11401) paired the model with a non-parametric memory, a dense vector index of Wikipedia. This page is about that memory.
    • Embeddings find paraphrases, BM25 finds exact strings, and rank fusion combines them without comparing scores.
    • A reranker improves order but cannot recover a passage the first stage missed.
    • Where the access filter runs changes recall as well as security.
    • The index is a derived copy: it needs versions, ordered writes and a freshness objective.

    The real-world problem

    Composite scenario, not a real company. A software vendor's assistant answers customers' questions from manuals, contract templates and a ticket archive. It is excellent in the demo, then three complaints arrive in one week.

    Complaint Cause Fixed by
    Asked about "clause 14.2", it returns a similar-sounding clause No lexical search BM25 and hybrid search
    A small customer gets "I could not find anything" for questions the manuals answer The filter runs after the nearest-neighbour search Access control in retrieval
    It quotes a warranty replaced two months ago The old document is still indexed beside the new one Versions and freshness

    None of these is fixed by a better prompt.

    After this page you will be able to

    • Compute memory for a vector index from dimension, vector count, HNSW connections or product-quantization settings.
    • Calculate a BM25 score and a reciprocal rank fusion score by hand, and say what each ignores.
    • Choose between pre-filtering and post-filtering, and write the test that proves tenants cannot cross.
    • Design an ingestion pipeline with versions, retries and a freshness objective.
    • Decide when a reranker is worth its latency.

    Read Diagramming AI systems first: the figures reuse its component names.

    Core concepts

    Ingestion and freshness pipelines

    Figure 2. Ingestion of one updated document

    sequenceDiagram accTitle: Ingestion of an updated document accDescr: The Document store publishes a change event to the Event bus. A Worker reads the new version, skips the work if the content hash is unchanged, chunks and embeds it, writes the new chunks to the Vector index and the Lexical index, then marks the old version superseded and commits the event offset. If embedding fails after retries the event goes to a dead-letter queue and an alert is raised. autonumber participant D as Document store participant E as Event bus participant W as Worker participant M as Embedding model participant V as Vector index participant L as Lexical index D-)E: change event doc 42 version 4 E-)W: deliver event W->>D: read doc 42 version 4 Note over W: Decision - if the content hash equals the stored hash, stop here and skip the rest W->>M: embed chunks with model id m1 alt Embedding succeeds M-->>W: vectors W->>V: upsert chunks keyed by doc, version, chunk number W->>L: upsert chunk text and metadata W->>V: mark version 3 chunks superseded W-)E: commit offset after all writes else Embedding fails after retries W-)E: send event to the dead-letter queue and alert end

    How to read this: time runs downward, open-headed arrows are asynchronous messages, and the alt block shows the success path and the failure path of the embedding step.

    A pipeline needs a change signal (an event per create, update, delete or permission change), idempotent processing, a dead-letter queue for failures, and a measurement of the lag until a change is searchable.

    Index choice

    Situation Start with Why
    Knowledge base under 200,000 tokens (about 500 pages) Put it in the prompt Anthropic's Contextual Retrieval post says it needs no retrieval
    A per-tenant partition of 40,000 chunks Exact search with a filter Perfect recall, nothing to tune
    A 20-million-chunk shared corpus An approximate index (HNSW, IVF, PQ) Usually too large to scan exactly within an interactive latency budget

    The pgvector README says exact search is its default.

    Hybrid retrieval and reranking

    Figure 3. The query path with hybrid search, an access filter, reranking and abstention

    sequenceDiagram accTitle: Query path of a hybrid retrieval accDescr: The Orchestrator sends a question with a verified identity to the Retriever. The Retriever asks the Policy engine for the caller's scope, searches the Vector index and the Lexical index in parallel with that scope as a filter, fuses the two rankings, and reranks the candidates. If the reranker times out the fused order is used. If no passage reaches the threshold the Retriever returns an abstain result and the Orchestrator does not call the model. autonumber participant O as Orchestrator participant R as Retriever participant P as Policy engine participant V as Vector index participant L as Lexical index participant X as Reranker O->>R: question plus verified identity R->>P: which scopes may this caller read? P-->>R: tenant t1, groups g1 and g2 par Vector search R->>V: nearest chunks with scope filter, top 50 and Lexical search R->>L: BM25 chunks with scope filter, top 50 end V-->>R: ranked chunk ids L-->>R: ranked chunk ids Note over R: Fuse the two rankings with reciprocal rank fusion alt Reranker replies in time R->>X: query plus fused candidates X-->>R: relevance score per candidate else Reranker times out Note over R: Use the fused order and mark the trace end alt Top score at or above threshold R-->>O: top passages with ids, versions and scores else Below threshold R-->>O: abstain, no passages end

    How to read this: the par block runs both searches together, the first alt block is the reranker failure path, and the second is the abstain decision that stops the model being called.

    Lexical search catches exact identifiers that embeddings blur. Vector search catches paraphrases.

    Multi-tenancy

    Two things must hold: no cross-tenant results, and no tenant degrading another's. The README warns that a shared approximate index lets one tenant's vectors affect another's recall and speed. Large tenants get their own partition, small ones share one with a mandatory tenant filter.

    Evaluation hooks

    Log chunk ids, document versions, scores and model and index versions per request. Replay a golden set of questions, with the chunks that should come back, from the Eval service on every change to the chunker, model or index.

    Conflicting and stale sources

    The retriever cannot decide which of two documents is true, but metadata can: version, effective date, status and a "supersedes" link.

    Figure 4. What the Retriever does when passages disagree

    flowchart TD accTitle: Handling conflicting or stale passages accDescr: A decision tree. If the retrieved passages from different documents disagree, the Retriever first checks whether one document supersedes the other and keeps only the current one. If neither supersedes the other it returns both with their dates and sources for the answer to show. If a passage is past its review date it is flagged as possibly stale. If there is no passage with enough relevance the system abstains. Start(["Passages retrieved"]) Q0{"Any passage above the relevance threshold?"} Q1{"Do passages from different documents disagree?"} Q2{"Does one document supersede the other?"} Q3{"Is the kept passage past its review date?"} A0["Abstain: say nothing was found and offer a human route"] A1["Answer from the passages as retrieved"] A2["Keep the current version, drop the superseded one"] A3["Return both with dates and sources, let the answer state the conflict"] A4["Answer and flag the passage as possibly stale"] Start --> Q0 Q0 -->|"no"| A0 Q0 -->|"yes"| Q1 Q1 -->|"no"| Q3 Q1 -->|"yes"| Q2 Q2 -->|"yes"| Q3 Q2 -->|"no"| A3 Q3 -->|"no"| A1 Q3 -->|"yes"| A4

    How to read this: start at the top, follow yes or no at each diamond, and stop at the first rectangle.

    Match the symptom to the mechanism

    Pick the fix for each symptom.

    Which mechanism fixes this retrieval symptom? (interactive when JavaScript is on)

    Embeddings blur the identifier in "clause 14.2", so the right clause is not among the vector candidates. Which change is most direct?

    • Add a reranker
    • Add a lexical index and fuse with RRF
    • Change k in RRF to 1
    Answer

    Add a lexical index and fuse with RRF. BM25 needs the literal token. A reranker only reorders candidates the first stage returned.

    A tenant with 0.2% of the chunks gets almost nothing from a shared HNSW index filtered after the search. Which change fixes it?

    • Add BM25 beside the vector index
    • Raise the reranker threshold
    • Filter inside the index scan, or give the tenant a partition
    Answer

    Filter inside the index scan, or give the tenant a partition. Post-filtering a top-40 list leaves about 0.08 allowed results. Pre-filtering or a partition searches only allowed chunks.

    The assistant quotes a warranty replaced two months ago. Both versions are indexed. What fixes it?

    • Version and effective-date metadata with a supersedes link
    • A larger embedding model
    • A deeper candidate list
    Answer

    Version and effective-date metadata with a supersedes link. Metadata lets the retriever keep the current document and drop the superseded one.

    Case files

    Three composite scenarios and one public case apply this page.

    Under the hood: Embeddings and similarity metrics

    Intuition

    An embedding model turns text into a fixed-length vector so that texts it treats as similar land near each other. The vector is a learned summary of semantic closeness, not a copy of the text, so it is blunt about exact strings.

    Mechanism

    Figure 5. Index time and query time must use the same embedding model

    sequenceDiagram accTitle: Embedding at index time and query time accDescr: A Worker embeds each chunk with model m1 and stores the vector with the model id. At query time the Retriever embeds the question with the model id the index was built with. If the Retriever is configured with a different model id than the index records, it refuses to search and raises an alert instead of comparing vectors from different spaces. autonumber participant W as Worker participant M as Embedding model participant V as Vector index participant R as Retriever W->>M: embed chunk text with model m1 M-->>W: vector of d numbers W->>V: store vector plus model id m1 R->>V: which model id built this index? V-->>R: m1 alt Retriever configured with m1 R->>M: embed the question with m1 M-->>R: query vector R->>V: nearest vectors by the index metric else Retriever configured with m2 Note over R: Refuse - vectors from m1 and m2 are not comparable R-)W: alert and start a re-index into a new index end

    How to read this: the first half is index time, the alt block is query time with the model check, and the failure branch refuses to search.

    1. A query vector from m2 lives in a different space from m1's stored vectors, so distances between them mean nothing.
    2. The RAG paper kept its document encoder (and so the index) fixed during training because updating it "requires the document index to be periodically updated".

    For illustrative vectors a = (3, 4, 0), b = (4, 3, 0) and c = (6, 8, 0), which points the same way as a but is twice as long:

    Measure Closer is a and b c and b
    Dot product Higher 24 48
    Cosine similarity Higher 0.96 0.96
    L2 distance Lower 1.414 5.385
    Check yourself: which measure scores c and b the same as a and b, and what makes all three rank identically?

    Cosine similarity, because it ignores length. With vectors divided by their lengths, the dot product equals the cosine (0.96) and the squared L2 distance equals 2 minus twice the cosine (0.08).

    The FAISS paper (Douze et al.) lists these as the most common measures. The pgvector README advises inner product for normalised vectors.

    What this means for architects

    What changes What you do
    A model change makes every stored vector unusable Store the model id with every vector and refuse a mismatch. Migrate with a parallel index, compare recall at k, then switch
    Dimension drives cost pgvector stores 4 × dimensions + 8 bytes per vector. Size the index before choosing the model
    The metric must match the vectors Use normalised vectors with inner product when the model documents unit-length output, and match the operator class to the query metric
    Re-embedding is the price of an upgrade Size it with the LLM cost estimator and the token counter

    Under the hood: HNSW graphs

    Intuition

    Hierarchical Navigable Small World (HNSW) graphs, introduced by Malkov and Yashunin (arXiv 1603.09320), find near neighbours by walking a graph of linked vectors, arranged in layers like a skip list. A few vectors sit in the top layers with long links, and every vector sits in layer 0 with short links. A search enters at the top, jumps toward the right region, drops a layer and refines.

    Mechanism

    Figure 6. HNSW search: greedy descent through the layers

    sequenceDiagram accTitle: HNSW search walkthrough accDescr: The query enters at the entry point in the top layer and walks greedily to the closest node it can reach there. It descends through the middle layers, repeating the greedy walk from the node it found. At layer 0 it keeps a candidate list of size ef, examines the nearest unexamined candidate each step, and stops when no candidate can improve the list. The K nearest entries of the list are returned. autonumber participant Q as Query vector participant T as Top layer participant M as Middle layers participant B as Layer 0 Q->>T: enter at the entry point Note over T: Greedy walk with list size 1 - move only to a closer neighbour T-->>M: closest node found, descend from it Note over M: Same greedy walk on each layer M-->>B: closest node found, descend from it Note over B: Keep ef best candidates - expand the nearest unexamined one Note over B: Stop when the nearest unexamined candidate is farther than the worst kept B-->>Q: the K nearest of the ef kept

    How to read this: the query moves down the layers in time, and only layer 0 uses the larger candidate list ef.

    1. Layers. Each vector draws a top layer from an exponentially decaying distribution with mL = 1/ln(M), so a fraction M⁻ˡ reaches layer l. With M = 16, one vector in 16 reaches layer 1 and one in 256 reaches layer 2.
    2. Insert. A greedy walk to the vector's layer, then an efConstruction-sized search per layer. It links M neighbours chosen for diverse directions and shrinks any neighbour over Mmax links (Mmax0 on layer 0, suggested at 2M).
    3. pgvector names. m (default 16), ef_construction (default 64) and hnsw.ef_search (default 40), which limits the candidate list.

    The paper gives the graph cost per vector as (Mmax0 + mL × Mmax) × bytes per link, with 4-byte links up to about four billion vectors. With Mmax0 = 2M and Mmax = M (illustrative):

    M Graph bytes per vector Vector bytes (1,536 float32) Note
    6 about 61 6,144 Paper's range: 60 to 450 bytes
    16 about 151 6,144 1,000,000 vectors: 0.151 GB of graph, 6.144 GB of vectors
    48 about 434 6,144

    The vectors dominate. Treat the formula as a floor.

    Dial Raises Costs
    M Recall, especially in high dimensions Memory, proportional to M
    efConstruction Index quality Build time
    efSearch Recall Latency

    What this means for architects

    What changes What you do
    Recall is a dial Compare approximate with exact results on your vectors, as the README advises, and set efSearch to the lowest value that meets the target
    Memory is predictable Budget it from the formula and keep the index resident, which the README says usually performs better
    Builds and deletes cost time Expect slow inserts at high efConstruction and slow vacuum after many deletes (reindex first)
    Filters change recall See access control in retrieval

    Under the hood: IVF and product quantization

    Intuition

    An inverted file (IVF) divides the space into cells with k-means and looks only in the few cells nearest the query. Product quantization (PQ) compresses each vector into a short code by replacing each piece with the id of its nearest representative. IVF cuts how many vectors you look at, and PQ cuts the bytes each takes.

    Mechanism

    Figure 7. IVF with product quantization: coarse search, code scan, exact re-rank

    sequenceDiagram accTitle: IVF with product quantization search accDescr: The Retriever finds the nearest coarse centroids to the query and reads those inverted lists. For each list entry it estimates the distance from the stored short code using lookup tables built from the query. It keeps a shortlist of the best estimates and re-scores the shortlist with the original full vectors to produce the final top results. autonumber participant R as Retriever participant C as Coarse centroids participant L as Inverted lists with PQ codes participant F as Original vectors R->>C: find the nprobe nearest centroids to the query C-->>R: list ids Note over R: Build lookup tables of query-to-codebook distances R->>L: read the chosen lists L-->>R: entries as id plus short code Note over R: Estimate each distance with m table lookups, keep a shortlist R->>F: fetch full vectors for the shortlist only F-->>R: exact vectors Note over R: Re-score exactly and return the top results

    How to read this: the first steps narrow the search to a few lists, the middle steps use compressed codes, and the last two correct the estimate with full vectors for a small shortlist.

    1. IVF. The FAISS paper stores each vector in the list of its nearest of K centroids (nlist) and visits only the P nearest lists (nprobe). Distance computations are K + P × N/K, minimised near K = √(P × N), a rough approximation.
    2. PQ. Per Jégou, Douze and Schmid (TPAMI 2011), a vector is split into m sub-vectors, each quantized by its own codebook of k* centroids, so the code is m × log₂ k* bits.
    3. Distance without decoding. A query-to-centroid table is built once, then each vector costs m lookups and additions.
    Worked number (illustrative) Calculation Result
    IVF centroids, N = 10,000,000, P = 16 √(16 × 10,000,000) K ≈ 12,649
    Distance computations 12,649 + 16 × 10,000,000 / 12,649 about 25,298, about 395 times fewer than 10,000,000
    Raw vectors, d = 1,536 float32 10,000,000 × 6,144 B 61.44 GB
    PQ, m = 192, 8 bits each 192 B per vector 1.92 GB, 32 times smaller
    PQ, m = 96 96 B per vector 0.96 GB, 64 times smaller
    Check yourself: with m = 192 sub-vectors of 8 bits each, how many bytes is one code, and why is the resulting distance only an estimate?

    192 bytes, against 6,144 for the raw vector. The distance comes from the codes' centroids, not the original values.

    What this means for architects

    What changes What you do
    Compression costs measured recall Fix the memory budget first, pick m and nprobe to hit the recall target, and evaluate against exact search
    Distances are estimates Keep originals on cheaper storage and re-score a shortlist, as the PQ paper and the README's binary-quantization example do
    IVF and PQ were fitted to old data The FAISS paper warns they degrade when the distribution shifts a lot, so schedule retraining
    IVF is not HNSW Per the README, IVFFlat builds faster with less memory but has a lower speed-recall tradeoff

    Intuition

    BM25 scores a document by the query words it contains, weighting each by rarity, counting repeats less and less, and discounting long documents. It needs the literal token. That is its weakness (no synonyms) and its strength: "14.2" or "ERR-4012" either matches or does not.

    Mechanism

    Figure 8. The three factors in a BM25 term score

    flowchart LR accTitle: The factors in a BM25 term score accDescr: For each query term, a rarity weight from the whole collection is multiplied by a saturating term-frequency factor that is scaled by document length. The products are summed over the query terms to give the document score. Q["Query term t"] --> IDF["Rarity: log of N over df"] D["Document d"] --> TF["Count tf, saturated by k1"] D --> LN["Length against average, scaled by b"] LN --> TF IDF --> MUL["Multiply"] TF --> MUL MUL --> SUM["Sum over query terms"] SUM --> SC["Document score"]

    How to read this: rarity comes from the collection, the count factor comes from the document and is damped by length, and the sum over query terms is the score.

    The Stanford Introduction to Information Retrieval (section 11.4.3) gives equation 11.32 for document scoring:

    RSV_d = sum over query terms t of
            log(N / df_t) x (k1 + 1) x tf_td / ( k1 x ((1 - b) + b x (L_d / L_ave)) + tf_td )
    1. N is the number of documents, df_t the number containing t, tf_td the count in d, L_d the document length and L_ave the average.
    2. k₁ is positive (0 gives a binary model, a large value approaches raw counts). b between 0 and 1 sets length scaling. Without tuning the book says k₁ between 1.2 and 2 and b = 0.75 are reasonable.

    Illustrative inputs, natural log: N = 1,000, L_ave = 200, k₁ = 1.2, b = 0.75, query "indemnification cap", df = 40 (idf 3.219) and 300 (idf 1.204).

    Document Length Counts Score
    A 150 indemnification 3, cap 1 5.345 + 1.341 = 6.686
    B 400 indemnification 5, cap 0 4.987
    C 200 indemnification 1, cap 2 3.219 + 1.656 = 4.874

    A wins: it is shorter and has both terms. B repeats the rare word but is twice the average length (length factor 1.75).

    Anthropic's post reports these top-20 failure rates on its own datasets, not a prediction for yours:

    Setup Failure rate
    Embeddings alone 5.7%
    Contextual embeddings 3.7%
    Plus contextual BM25, merged by rank fusion 2.9%
    Plus reranking 1.9%

    What this means for architects

    What changes What you do
    Queries hold identifiers, defined terms or exact phrases Add a lexical index (the README suggests Postgres full-text search)
    BM25 matches only the tokens the analyser makes Check whether "14.2" stays one token
    k₁ and b are tunable Tune them on your golden set
    Lexical and cosine scores use unrelated scales Never add them. Fuse ranks instead

    Under the hood: Reciprocal rank fusion

    Intuition

    A BM25 score of 6.7 and a cosine of 0.82 mean different things. Reciprocal rank fusion (RRF) ignores scores and uses only ranks: a document earns more the nearer the top it sits in each list, and documents found by several lists add up.

    Mechanism

    Figure 9. Fusing two rankings with reciprocal rank fusion

    sequenceDiagram accTitle: Reciprocal rank fusion steps accDescr: The Retriever receives a dense ranking and a BM25 ranking from the two indexes. For each document in each list it adds one over k plus its rank to a running score, with k equal to 60. It sorts by total score, breaks ties by document id, and keeps the top depth documents for reranking. autonumber participant V as Vector index participant L as Lexical index participant R as Retriever participant X as Reranker V-->>R: dense ranking d3, d1, d7, d2 L-->>R: BM25 ranking d1, d9, d3 Note over R: For each list and each document add 1 over 60 plus rank Note over R: d1 gets 0.032522, d3 gets 0.032266, d9 gets 0.016129 Note over R: Sort by total, break ties by id, cut to depth R->>X: fused candidates d1, d3, d9, d7, d2

    How to read this: the two indexes send ranked lists, the notes are the fusion arithmetic, and the last message is the fused list passed on.

    Cormack, Clarke and Büttcher (SIGIR 2009) publish the formula RRFscore(d) = sum over rankings r of 1 / (k + r(d)), with k = 60.

    1. Ranks start at 1. A document missing from a list adds nothing for it.
    2. The paper fixed k = 60 in a pilot, found it near-optimal, and says "the choice was not critical".
    3. Elasticsearch documents the same formula, a rank_constant default of 60 and equal weight per retriever.
    Document (k = 60, illustrative) Dense rank BM25 rank RRF score
    d1 2 1 1/62 + 1/61 = 0.032522
    d3 1 3 1/61 + 1/63 = 0.032266
    d9 none 2 1/62 = 0.016129
    d7 3 none 1/63 = 0.015873
    d2 4 none 1/64 = 0.015625

    d1 wins although the dense retriever ranked d3 first, because both retrievers found d1. Try moving d9 to the top of the BM25 list, then change k and watch which document leads.

    Reciprocal rank fusion of a dense and a BM25 ranking (interactive when JavaScript is on)
    1. d1score 0.03252 (ranks 2, 1)
    2. d3score 0.03227 (ranks 1, 3)
    3. d9score 0.01613 (ranks -, 2)
    4. d7score 0.01587 (ranks 3, -)
    5. d2score 0.01563 (ranks 4, -)
    Check yourself: document a is first in one list only, and document b is fourth in both lists. Which wins at k = 60, and at k = 1?

    At k = 60, b: 2/64 = 0.03125 against 1/61 = 0.016393. At k = 1, a: 1/2 = 0.5 against 2/5 = 0.4. A small k rewards one top rank, a large k rewards agreement.

    What this means for architects

    What changes What you do
    RRF discards score magnitude A near-perfect and a poor match at the same rank earn the same, so the fused score is a poor abstention signal. Threshold a reranker or per-retriever score calibrated on labelled queries
    Every retriever counts equally You cannot weight BM25 above the vector side without changing the method
    Each list gives only what you fetch A document outside both windows (Elasticsearch's rank window size) cannot appear, so set depth deliberately
    The constant is rarely the problem Keep k at 60 unless the golden set shows a reason

    Under the hood: Rerankers

    Intuition

    A bi-encoder embeds query and passage separately, so passage vectors are precomputed and search is cheap. A cross-encoder reads the query and one passage together, so every query word can attend to every passage word. It can be more accurate (an expectation to test on your data) and is far more expensive, because nothing can be precomputed.

    Mechanism

    Figure 10. Two-stage retrieval: a cheap wide stage, then a costly narrow stage

    sequenceDiagram accTitle: Two-stage retrieval with a reranker accDescr: The Retriever fetches a wide candidate list from the first stage. It sends each query and candidate pair to the Reranker, which returns a relevance score per pair. The Retriever sorts by that score, drops candidates below the threshold and keeps the top few. If the Reranker is unavailable it keeps the first-stage order and shortens the list. autonumber participant R as Retriever participant I as First-stage indexes participant X as Reranker R->>I: hybrid search, wide candidate list I-->>R: fused candidates alt Reranker available R->>X: score each query and candidate pair X-->>R: one relevance score per pair Note over R: Sort by score, drop below threshold, keep top few else Reranker unavailable Note over R: Keep fused order, shorten the list, flag the trace end R-->>R: pass passages to the Orchestrator

    How to read this: the first stage is cheap and wide, the alt block is the costly narrow stage with its failure branch, and the last message is the hand-off.

    1. Nogueira and Cho (arXiv 1901.04085) use a cross-encoder as the second stage: BM25 returns a large set (for example a thousand), the re-ranker scores each, and the top ten or fifty go on.
    2. Their input is the query (truncated to 64 tokens) and the passage, up to 512 tokens in all. Each passage is scored independently.
    3. Cost is linear in candidates: 1,000 passages need 20 times the model runs of 50.
    Evidence Number
    MS MARCO dev MRR@10, Lucene BM25 without tuning 16.7
    Same task, BERT-large re-ranker over BM25 candidates 36.5
    Anthropic's post: rerank the top 150, pass the top 20; top-20 failure rate, before and after 2.9% to 1.9%
    Cross-encoder over all pairs of 10,000 sentences (Sentence-BERT paper) 49,995,000 inferences, about 65 hours on a V100
    Embedding those 10,000 sentences once, then cosine about 5 seconds
    Check yourself: a first stage returns 1,000 candidates and you rerank all of them instead of the top 50. How many times more model runs?

    20 times (1,000 divided by 50). Reranking cost grows linearly with the list, which is why the first stage trims it.

    What this means for architects

    What changes What you do
    A reranker only helps if the right passage is in the candidates Compare recall at 50 with recall at 5. If recall at 50 is poor, repair chunking and hybrid retrieval first
    Latency is candidates times per-pair cost Budget the list length
    A hosted reranker is another trust boundary Send access-filtered text only, and keep a timeout path
    Inputs are truncated Mind the input limit (512 tokens in the cited setup)
    A reranker score is the usual abstention signal Test on labelled queries whether a threshold generalises

    Under the hood: Chunking and its failure modes

    Intuition

    One chunk gets one vector and one citation. A chunk that mixes two topics has a vector between them, and one that cuts a sentence from its subject cannot say what it is about. Chunking is a modelling decision about the smallest retrievable unit.

    Mechanism

    Figure 11. A chunker that keeps structure and attaches context

    sequenceDiagram accTitle: Structure-aware chunking accDescr: A Worker passes a parsed document to the chunker. The chunker splits at headings first. A section longer than the size limit is split at paragraph boundaries, and a block that cannot be split, such as a table, is kept whole or split by rows with its header repeated. Each chunk gets a context header with document title, section path, version and effective date, and then goes to the embedding model and the stores. autonumber participant W as Worker participant C as Chunker participant M as Embedding model participant S as Indexes W->>C: parsed document with headings, tables and metadata Note over C: Split at headings first alt Section within the size limit Note over C: Keep the section as one chunk else Section over the limit Note over C: Split at paragraphs, repeat table headers on row splits end Note over C: Prepend title, section path, version and effective date C->>M: chunk text with its header M-->>C: vector C->>S: chunk, vector, doc id, version, offsets

    How to read this: splitting goes from coarse to fine, the alt block is the size decision, and every chunk leaves with its context header and metadata.

    1. Anthropic's post says chunks are usually no more than a few hundred tokens, and size, boundary and overlap affect retrieval. "The company's revenue grew by 3% over the previous quarter" does not say which company or period.
    2. Its remedy prepends a short generated context (usually 50 to 100 tokens) to each chunk before embedding and BM25 indexing, made affordable with prompt caching.
    Failure mode What goes wrong
    A cut through a table row, clause, list or code block The vector represents half of each
    A lost referent ("the company", "this clause") The chunk cannot say what it is about
    A chunk over the embedding model's input limit It is truncated or rejected, depending on the model
    A chunk too small to hold an answer It matches but cannot answer
    Overlapping chunks Near duplicates fill the top k
    Several versions of one document chunked identically Stale and current text compete (the root of the policy-conflict case)

    What this means for architects

    What changes What you do
    Citations, deletes and rollbacks must find a chunk Store document id, version, section path, offsets and chunker version with every chunk
    Size and overlap are modelling choices Tune them on the golden set by recall at k, not by defaults
    A chunker or embedding change is a re-index Version both and roll out like a migration
    Sources differ Chunk contracts and manuals by structure, FAQs as one chunk per question and answer

    Under the hood: Access control in retrieval

    Intuition

    Access control asks which chunks this caller may see. Pre-filtering restricts the search to allowed chunks. Post-filtering searches everything, takes the top k and then removes forbidden chunks, so forbidden text is handled along the way.

    Mechanism

    What is documented depends on the engine, so read and test your own. None of this transfers to another product.

    Engine Documented behaviour
    pgvector, approximate index "Filtering is applied after the index is scanned", so fewer rows can return: a 10% match with the default hnsw.ef_search of 40 gives about 4 rows. Fixes: iterative scans, a partial index, partitioning
    Elasticsearch A filter inside the knn clause is applied during the search "to ensure that k matching documents are returned". A filter beside it in a bool query is applied after, so the response "can contain far fewer than five hits, or none at all"
    PostgreSQL row-level security Policies restrict which rows queries return. Superusers and BYPASSRLS roles bypass it, and table owners usually do unless FORCE ROW LEVEL SECURITY is set. The documentation read does not say how policies combine with approximate vector scans: test it

    Figure 12. Pre-filter versus post-filter for a tenant with a small share of the data

    sequenceDiagram accTitle: Pre-filter and post-filter retrieval compared accDescr: The Retriever receives the caller's scope from the Policy engine. In the pre-filter branch it sends the scope with the search and the index returns only allowed chunks. In the post-filter branch the index returns the top 40 chunks from all tenants, the Retriever removes forbidden ones and may be left with almost none, and forbidden chunks were present in the Retriever before removal. autonumber participant P as Policy engine participant R as Retriever participant V as Vector index P-->>R: scope tenant t1 alt Pre-filter R->>V: search with scope t1 inside the index scan V-->>R: up to k allowed chunks else Post-filter R->>V: search without the scope, top 40 V-->>R: 40 chunks from many tenants Note over R: Drop forbidden chunks - 0.2 percent allowed means 0.08 expected Note over R: Forbidden chunks were in memory before this step end

    How to read this: the alt block compares the two designs, and the notes give the expected survivors and the exposure post-filtering creates.

    1. With 500 equal tenants a tenant matches 1/500 = 0.2% of rows, so a top-40 list holds 40 × 0.002 = 0.08 allowed rows on average, usually zero.
    2. The leak is reasoning, not a documented behaviour of any one product: forbidden chunks exist before removal, so logging, a cache, an external reranker or an error message with scores handles data the caller may not see.
    Check yourself: in the README's example a condition matches 10% of rows and ef_search is 40. About how many rows come back, and how does a 0.2% tenant compare?

    About 4 (40 × 0.10). A 0.2% tenant gets 0.08, so the smaller the share, the closer to zero.

    SET hnsw.iterative_scan = relaxed_order;
    
    SELECT id, content
    FROM chunks
    WHERE tenant_id = $1
    ORDER BY embedding <=> $2
    LIMIT 8;

    This is the README's filtered-query pattern with iterative scans (pgvector 0.8.0 and later).

    What this means for architects

    What changes What you do
    The filter must be trustworthy Derive it from the verified identity inside the Retriever or below, never from model output or a client field
    Post-filtering loses recall and exposes text Prefer pre-filtering semantics and prove them with a recall test per tenant size
    Some database roles skip the rules Run the service as a role that is not the table owner or a bypass role
    Isolation must be tested Try to cross tenants, including through the lexical index, cache and reranker, on every index change
    Revocation is urgent Send permission changes down a fast path

    Under the hood: Incremental indexing and freshness

    Intuition

    The index is a copy, and copies go stale. Freshness is the lag between a change in the Document store and the moment queries reflect it.

    Mechanism

    Figure 13. Life of an index entry for one chunk version

    stateDiagram-v2 accTitle: Lifecycle of a chunk version in the index accDescr: A change event puts a chunk version into pending. Successful embedding and writes make it indexed. Errors after retries make it failed, from where a dead-letter retry returns it to pending. When a newer version is indexed the old one becomes superseded. A deleted source or expired retention makes it deleted. Every path ends in indexed, superseded or deleted, or in the dead-letter queue with an alert. [*] --> Pending: change event received Pending --> Indexed: embedded and written to both indexes Pending --> Failed: error after retries Failed --> Pending: retried from the dead-letter queue Indexed --> Superseded: newer version indexed Indexed --> Deleted: source deleted Superseded --> Deleted: retention period ends Deleted --> [*]

    How to read this: each box is a state of one chunk version, each arrow is a transition with its trigger, and the dots are start and end.

    The ordering rule: write the new version, then mark the old one superseded, then commit the event offset. A crash between any two steps repeats work and does not lose it. Step through a normal update and a crash.

    Updating document 42 to version 4: normal run and a crash (illustrative) (interactive when JavaScript is on)

    Normal update

    1. Change event. The Worker reads doc 42 version 4.
    2. Write the new version. Chunks are upserted into both indexes, keyed by document, version and chunk number.
    3. Retire the old version. Version 3 chunks are marked superseded, so a query never sees a gap.
    4. Commit the offset. Only after all writes.

    Crash before the commit

    1. Write the new version. Version 4 chunks reach both indexes.
    2. Crash. The Worker dies before marking version 3 superseded or committing the offset.
    3. Redelivery. The event arrives again, because its offset was never committed.
    4. Repeat harmlessly. Upserts overwrite the same keys, so nothing is duplicated. Every step must be idempotent.
    5. Finish. Version 3 is marked superseded and the offset is committed.

    The RAG paper measured staleness: a December 2016 Wikipedia index against a December 2018 one, on 82 world leaders who changed in between.

    Index Leaders asked about Correct
    2016 2016 70%
    2018 2018 68%
    2018 2016 12%
    2016 2018 4%

    The authors conclude that replacing the non-parametric memory updates world knowledge without retraining. The README recommends CREATE INDEX CONCURRENTLY in production.

    What this means for architects

    What changes What you do
    Staleness must be a number Set an objective users can feel, such as "99% of changes searchable within N minutes" (N is yours). Measure the age of the oldest unprocessed change and alert on it
    Changes differ in urgency Give deletes and permission revocations a fast lane and bulk re-embeds a slow one
    Events can be lost Reconcile on a schedule, comparing versions in the Document store with those in the indexes
    A model or chunker change rebuilds the index Build beside the old one, evaluate on the golden set, switch an alias, and keep the old one until rollback is no longer wanted
    A silent failure is a stale answer Give the dead-letter queue an owner

    Decision framework

    Figure 14. Choosing the retrieval design

    flowchart TD accTitle: Choosing the retrieval design accDescr: A decision tree. If exact search meets the latency budget, use it with a filter, otherwise use an approximate index. Then, if queries contain identifiers or defined terms, add a lexical index and fuse with RRF, otherwise stay with vector search. Then, if recall at 50 is good but recall at 5 is poor, add a reranker. If recall at 50 is poor, fix chunking and hybrid retrieval first. Q1{"Exact search meets the latency budget?"} EX["Exact search with a filter"] AP["Approximate index: HNSW, or IVF with PQ if memory-bound"] Q2{"Queries contain identifiers or defined terms?"} HY["Lexical plus vector, fused with RRF"] VO["Vector search only"] Q3{"Recall at 50 good but recall at 5 poor?"} RR["Add a reranker"] FX["Recall at 50 poor: fix chunking and hybrid retrieval first"] Q1 -- yes --> EX Q1 -- no --> AP EX --> Q2 AP --> Q2 Q2 -- yes --> HY Q2 -- no --> VO HY --> Q3 VO --> Q3 Q3 -- yes --> RR Q3 -- no --> FX

    How to read this: the three questions run in order, and rows 4 to 6 of the table (access, re-indexing, conflicting sources) apply on every path.

    If Then Because Revisit when
    Exact search meets the latency budget Use it with a filter Perfect recall, nothing to tune p95 latency or memory breaks the budget
    Queries contain identifiers or defined terms Add a lexical index and fuse with RRF Embeddings blur exact strings The golden set shows no gain
    Recall at 50 good, at 5 poor Add a reranker A reranker only reorders The candidate set changes
    Callers see part of the corpus Filter from verified identity inside the search Post-filtering returns too few and exposes text The engine changes
    Model, chunker or index parameters change Build a new index beside the old, then switch Vectors from different models are not comparable Re-embedding exceeds your change window
    Sources can disagree Keep version, date and status, prefer the superseding document The retriever cannot decide truth A user reports a conflict

    Comparison of the main options

    Option Strength Weakness Fits when
    Exact scan Perfect recall, any filter Cost grows with vectors Small corpora or partitions
    HNSW Strong speed-recall More memory, slower builds Medium corpora in memory
    IVF (flat) Faster build, less memory Needs training, drifts Larger, stable corpora
    IVF with PQ Smallest memory Lossy, needs re-score Corpora that cannot fit in memory
    Lexical (BM25) Exact identifiers No synonyms Legal, code, catalogue text
    Hybrid with RRF Both, no calibration Equal weights, two indexes Mixed queries
    Add a reranker Better top order Latency, another boundary Right passage found but low

    Failure scenarios to design for

    Failure What the system does Why
    Embedding model changes, or a stale index is queried with a new model The Retriever refuses the mismatch and alerts. A new index is built in parallel Mixed vectors still return results, silently
    A filtered query returns too few results Use pre-filtering or capped iterative scans. Below the minimum, abstain Padding hands over text the filter removed
    The lexical and vector indexes diverge A version counts as indexed only when both writes succeed. A scheduled reconciliation alerts Writes and events can be lost
    The reranker times out Use the fused order, shorter, and mark the trace. High-risk uses abstain The threshold needs the reranker score
    Sources conflict or one is stale Keep the superseding version, or return both with dates The retriever cannot decide truth
    Evidence is weak Below the threshold the model is not called Weak evidence invites a made-up answer
    A permission is revoked but the chunk is still served Use a fast lane, update filter metadata first, measure permission staleness separately Revocation is urgent

    Worked example

    Size a retrieval tier for a multi-tenant assistant.

    Assumptions (all illustrative):

    • 2,000,000 documents of 10 chunks each, so N = 20,000,000, with d = 1,024 float32 values (4,096 bytes) and 500 equal tenants.
    • HNSW with M = 16, Mmax0 = 32, Mmax = 16 (151 bytes per vector), and PQ at m = 128 sub-vectors of 8 bits.
    • First stages fetch 50 candidates each. Embedding runs at 2,000 chunks per second, 300 tokens per chunk.
    Step Calculation Result
    Vectors 20,000,000 × 4,096 B 81.92 GB
    HNSW graph 20,000,000 × 151 B about 3.02 GB
    PQ codes 20,000,000 × 128 B 2.56 GB, 32 times smaller
    One tenant 20,000,000 / 500, × 4,096 B 40,000 chunks, 163.84 MB
    Post-filter, shared HNSW 40 × (1/500) 0.08 allowed results per top-40
    Exact scan of one partition 40,000 × 1,024 40.96 million multiply-adds, perfect recall
    Rerank cost At most 100 candidates, against 1,000 10 times fewer runs
    Re-embed 20,000,000 / 2,000 per second, and × 300 tokens 10,000 s (about 2.8 hours), 6.0 billion tokens

    Decisions: a partition per large tenant and a mandatory pre-filter for small ones. A model change means a parallel index and an alias switch, priced with the cost estimator.

    A hybrid retrieval function with RRF

    The function fetches two ranked lists with an identity-derived filter, fuses them and reranks with a fallback. The component objects stand for your own, the assertions reproduce the RRF worked example, and the code was run with stub components.

    from collections import defaultdict
    
    RRF_K = 60  # the constant published by Cormack et al. (SIGIR 2009)
    
    def rrf(rankings, k=RRF_K):
        """rankings: ranked lists of chunk ids, best first. Returns [(id, score)], best first."""
        scores = defaultdict(float)
        for ranking in rankings:
            for rank, chunk_id in enumerate(ranking, start=1):  # ranks start at 1
                scores[chunk_id] += 1.0 / (k + rank)
        return sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))  # ties: by id
    
    def hybrid_search(query, identity, vector_index, lexical_index,
                      reranker=None, depth=50, final_n=8):
        allowed = identity.allowed_filter()  # built from the verified identity, never from model output
        dense = vector_index.search(query, filter=allowed, k=depth)    # chunk ids, best first
        lexical = lexical_index.search(query, filter=allowed, k=depth)
        fused = [cid for cid, _ in rrf([dense, lexical])][:depth]
        if reranker is not None:
            try:
                fused = reranker.rank(query, fused)  # reorders only, cannot add candidates
            except TimeoutError:
                pass  # fall back to the fused order and record it in the trace
        return fused[:final_n]
    
    # the worked example from the lesson
    fused = rrf([["d3", "d1", "d7", "d2"], ["d1", "d9", "d3"]])
    assert [d for d, _ in fused] == ["d1", "d3", "d9", "d7", "d2"]
    assert abs(fused[0][1] - (1 / 62 + 1 / 61)) < 1e-12

    The function does not abstain: add a threshold check on the reranker score for high-risk paths.

    Common mistakes

    • Adding a vector store and calling it retrieval. Add a lexical side, versions, filters and a golden set.
    • Mixing embedding models in one index. Record the model id and refuse a mismatch.
    • Post-filtering for access control. Filter inside the search.
    • Adding scores from different retrievers. Fuse ranks, or calibrate on labelled data.
    • Treating a reranker as a fix for bad recall. Repair the first stage.
    • Never measuring recall of the approximate index. Compare against exact search, as the README says.

    Try it

    Time: 30 to 40 minutes. Use a small corpus and at least 20 questions with known right passages.

    1. Split the corpus into chunks with ids and record the right chunk per question.
    2. Build two rankings per question: exact cosine over any embedding model, and BM25.
    3. Fuse them with the rrf function and compute recall at 5 for each.

    Done when you have a three-row table of recall at 5 for vector, BM25 and fused retrieval over at least 20 questions, and a short explanation for one question where fusion changed the top result.

    Key takeaways

    • Cosine, dot product and L2 agree only on unit-length vectors, and a model change forces a re-index.
    • HNSW has three dials: M, efConstruction and efSearch.
    • IVF limits how many vectors you scan and PQ limits the bytes per vector, at an accuracy cost.
    • BM25 needs the literal token. RRF fuses ranks with 1 / (60 + rank).
    • A reranker is linear in candidates and cannot add a missing passage.
    • Pre-filter versus post-filter is engine-specific: design for pre-filtering and test it.
    • Treat the index as a derived copy with versions, ordered writes and a freshness objective.

    Self-check

    1. Two vectors point the same way but one is twice as long. Which of cosine, dot product and L2 treat them as equal, and what makes all three agree?

    Cosine ignores length. The dot product and L2 distance change with it. All three rank identically on unit-length vectors.

    2. With M = 16, Mmax0 = 32 and Mmax = 16, how much graph memory does HNSW need per vector, and what dominates the total?

    About 151 bytes. A 1,536-dimension float32 vector takes 6,144 bytes, so the vectors dominate.

    3. In the RRF example, how is d9's score reached, and why is it ahead of d7?

    d9 is only in the BM25 list, at rank 2: 1/62 = 0.016129. d7 is only in the dense list at rank 3: 1/63 = 0.015873. The better rank wins.

    4. A tenant owns 0.2% of a shared HNSW index and the query is post-filtered from the top 40. What do you expect, and what fixes it?

    On average 40 × 0.002 = 0.08 allowed results, so usually none. pgvector documents iterative scans, partial indexes and partitioning. Elasticsearch documents a filter inside the knn clause.

    5. A reranker fixes most ordering problems, but one class of questions still fails. What is the likely cause?

    The right passage is probably not among the first-stage candidates, and a reranker only reorders what it receives. Check recall at the candidate depth, then chunking, the lexical index and the filter.

    Further reading

    Last verified: 2026-10-22

    Next

    The next page covers agents, tools and the Model Context Protocol: Agents, tools and MCP.

    Enroll to keep reading

    Lesson 5 of 8 · AI Architect (Intermediate): Design the System

    How retrieval works inside an AI system: embeddings, HNSW, IVF and product quantization, BM25, rank fusion, rerankers, chunking, access control and freshness.

    In the rest of this lesson

    • Under the hood: HNSW graphs
    • Under the hood: IVF and product quantization
    • Under the hood: BM25 and hybrid search
    • Under the hood: Reciprocal rank fusion
    • Under the hood: Rerankers
    • Under the hood: Chunking and its failure modes

    Enrolling is free. It unlocks every lesson in AI Architect (Intermediate): Design the System, tracks your progress across devices and keeps your quiz scores. The newsletter is optional.

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments