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
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.
- 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.
- 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).
- 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):
The vectors dominate. Treat the formula as a floor.
What this means for architects
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.
- 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.
- 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.
- Distance without decoding. A query-to-centroid table is built once, then each vector costs m lookups and additions.
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
Under the hood: BM25 and hybrid search
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 )
- 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.
- 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).
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:
What this means for architects
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.
- Ranks start at 1. A document missing from a list adds nothing for it.
- The paper fixed k = 60 in a pilot, found it near-optimal, and says "the choice was not critical".
- Elasticsearch documents the same formula, a
rank_constant default of 60 and equal weight per retriever.
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.
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
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.
- 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.
- Their input is the query (truncated to 64 tokens) and the passage, up to 512 tokens in all. Each passage is scored independently.
- Cost is linear in candidates: 1,000 passages need 20 times the model runs of 50.
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
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.
- 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.
- 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.
What this means for architects
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.
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.
- 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.
- 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
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.
The RAG paper measured staleness: a December 2016 Wikipedia index against a December 2018 one, on 82 world leaders who changed in between.
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
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.
Comparison of the main options
Failure scenarios to design for
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.
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
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):
scores[chunk_id] += 1.0 / (k + rank)
return sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))
def hybrid_search(query, identity, vector_index, lexical_index,
reranker=None, depth=50, final_n=8):
allowed = identity.allowed_filter()
dense = vector_index.search(query, filter=allowed, k=depth)
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)
except TimeoutError:
pass
return fused[:final_n]
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.
- Split the corpus into chunks with ids and record the right chunk per question.
- Build two rankings per question: exact cosine over any embedding model, and BM25.
- 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
- Malkov and Yashunin, Efficient and robust approximate nearest neighbor search using HNSW graphs: layers, insert and search, parameters and the memory formula.
- Douze et al., The Faiss library: IVF, product quantization, filtering and index updates.
- Cormack, Clarke and Büttcher, Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods, SIGIR 2009.
- Manning, Raghavan and Schütze, Introduction to Information Retrieval, section 11.4.3 Okapi BM25.
- pgvector README: index types, parameters, filtering, iterative scans and multi-tenancy notes.
Last verified: 2026-10-22
Next
The next page covers agents, tools and the Model Context Protocol: Agents, tools and MCP.