Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 4: AI application systems

Chapter 13Retrieval and vector databases

35 min read, 1 lab, Intermediate

Searching 10 million embeddings exactly means reading about 30 GB of floats per query, yet production systems answer in milliseconds by accepting that they will occasionally miss a neighbour. You will learn how that trade works, how to measure it, and how to build retrieval for a RAG system that you tune with numbers instead of guesses.

After this chapter you can

  • Explain embeddings, similarity metrics and why exact nearest neighbour search stops scaling
  • Describe how HNSW, IVF and product quantization indexes work and what each knob trades
  • Design an ingestion pipeline with sensible chunking, freshness and re-embedding
  • Combine BM25, vector search and a reranker, and budget the latency of a full RAG request
  • Measure retrieval with recall@k and MRR, and tell ANN recall apart from retrieval quality

Embeddings turn meaning into distance

An embedding is a fixed-length vector of floats that a model produces for a piece of text, so that texts with similar meaning land close together. "How do I reset my password" and "I forgot my login" share almost no words, yet land near each other. Retrieval becomes geometry: embed the query, find the closest stored vectors.

"Closest" needs a similarity metric. You pick the one the embedding model was trained with, and you must use the same one when you build the index and when you query it.

MetricFormula in wordspgvector operatorUse when
Cosine distance1 minus the cosine of the angle between vectors<=>Most text embedding models; ignores vector length
Inner productSum of element-wise products (pgvector returns it negated)<#>Vectors are already normalized; fastest
Euclidean (L2)Straight-line distance<->Models trained with L2, many image models

If vectors are normalized to length 1, cosine, inner product and L2 all produce the same ranking, so normalizing once at write time lets you use the cheapest operator. Dimensions matter for cost: a 768-dimension float32 vector is 3 KB, and 1,536 dimensions doubles every byte of storage, memory and bandwidth.

Exact search and the case for approximation

Exact (brute-force) k-nearest-neighbour search compares the query against every stored vector and keeps the best k. It is always correct and fine up to a few hundred thousand vectors; beyond that the arithmetic catches up with you.

CorpusRaw float32 size at 768 dimsWork per exact query
100,000 chunksabout 300 MBabout 77 million multiply-adds, a few ms
10 million chunksabout 30 GBabout 7.7 billion multiply-adds, memory-bandwidth bound, often over 1 s
1 billion chunksabout 3 TBdoes not fit in RAM on one machine

Approximate nearest neighbour (ANN) indexes avoid touching most vectors. The price is that they sometimes miss a true neighbour. You measure that price as ANN recall against exact search: for each query, the fraction of the true top-k that the index returned. A recall@10 of 0.95 means the index found, on average, 9.5 of the 10 vectors an exhaustive scan would have found.

How HNSW and IVF indexes work

HNSW: navigating a layered graph

HNSW (Hierarchical Navigable Small World) builds a graph in which each vector links to its nearest neighbours. A few vectors are also promoted to sparser upper layers, like express lanes. A search enters at the top layer, greedily walks towards the query, then drops down a layer and repeats with finer steps.

Three parameters control it:

ParameterWhat it doesRaise it toCost
mLinks per node (pgvector default 16)Improve recall, especially at high dimensionMore memory, slower builds
ef_constructionCandidate list size while building (default 64)Build a better-connected graphSlower builds
ef_searchCandidate list size per query (default 40)Raise recall at query timeHigher latency

ef_search is the production knob, because it changes per query without a rebuild. HNSW gives excellent recall and latency, but the graph wants to live in RAM and builds are slow; in pgvector a graph that outgrows maintenance_work_mem makes the build slow sharply.

IVF and product quantization

IVF (inverted file) runs k-means over your vectors to create lists clusters, then stores each vector in the list of its nearest centroid. A query compares itself to the centroids, then scans only the closest probes lists. More probes means more recall and more latency. IVF builds quickly and uses little extra memory, but it must be trained on representative data, so build it after loading and rebuild when the data distribution drifts.

Product quantization (PQ) compresses the vectors themselves. It splits a 768-dimension vector into 96 sub-vectors of 8 dimensions, and replaces each sub-vector with a one-byte ID of its nearest entry in a learned codebook of 256. The vector shrinks from 3,072 bytes to 96, a 32 times reduction, at the cost of approximate distances. Systems usually rerank the top candidates with full-precision vectors to win back accuracy.

IndexMemoryBuildQuery latencyTypical home
Flat (exact)Vectors onlyNoneGrows linearlySmall corpora, ground truth
HNSWVectors plus graph linksSlowVery lowMost production RAG up to tens of millions
IVF-FlatVectors plus centroidsFastLow, tuned by probesLarge batch-loaded corpora
IVF-PQCompressed codesModerateLow, lossyHundreds of millions to billions
DiskANN-style graphsGraph on SSD, compressed vectors in RAMModerateLowCorpora larger than RAM

Filtering breaks naive ANN

Real queries carry filters: this tenant, this language, newer than last month. If the index returns the 40 nearest vectors and a filter keeps 10 percent of them, you get four results instead of ten. pgvector 0.8 added iterative index scans (SET hnsw.iterative_scan = relaxed_order) that keep walking the index until enough rows pass; dedicated vector databases use filter-aware traversal. For very selective filters such as one tenant, a partial index or per-tenant partition is often faster still.

Choosing where vectors live

The first question is whether you need a separate system at all, because vectors are increasingly a column type in databases you already run.

Vectors in your existing database

  • pgvector in PostgreSQL, or vector types in Elasticsearch, OpenSearch, MongoDB and Redis
  • Transactions, joins, backups and access control you already operate
  • Filters are ordinary SQL WHERE clauses
  • Comfortable into the tens of millions of vectors on one node

A dedicated vector database

  • Qdrant, Milvus, Weaviate, Pinecone, Chroma, LanceDB, turbopuffer
  • Purpose-built filtering, quantization and horizontal sharding
  • Some keep data on object storage for much cheaper scale
  • One more stateful system to secure, back up and keep in sync

A reasonable default in late 2026 is pgvector, unless you already know you need billions of vectors or very high query rates. Extensions such as pgvectorscale (a DiskANN-style index) and ParadeDB's pg_search (BM25 in Postgres) push that boundary further, and object-storage services such as turbopuffer and Amazon S3 Vectors trade latency for far lower cost per vector.

Ingestion: chunking, embedding and freshness

Retrieval quality is mostly decided at write time. An ingestion pipeline turns raw sources into indexed chunks and keeps them current.

Chunking splits documents into retrievable units. Too large and a chunk mixes topics and wastes prompt tokens; too small and it loses the context needed to answer.

  • Start with 200 to 500 tokens per chunk and 10 to 20 percent overlap, then tune against your eval set.
  • Split on structure first (headings, paragraphs, functions in code), and fall back to token windows only inside long sections.
  • Store the document title and section path with every chunk, and consider prepending them to the text you embed. Anthropic's "contextual retrieval" write-up reports large reductions in failed retrievals from prepending a short, generated summary of each chunk's surrounding document.

Freshness is an operations problem. Store a content hash per chunk so you only re-embed what changed, and process deletes as carefully as inserts, because a deleted document that still answers questions is a data leak. Record the embedding model and version on every row: changing models means re-embedding everything into a new column, then switching reads, like any backfill migration.

Hybrid search, reranking and the request path

Keyword search still matters

Embeddings are weak at exact tokens: error codes, SKUs, rare names, version numbers. BM25, the classic keyword ranking function, rewards rare query terms, with diminishing returns for repeats and a penalty for long documents. Hybrid search runs both retrievers and merges the lists.

The standard merge is Reciprocal Rank Fusion (RRF): each document scores the sum, over every list it appears in, of 1 divided by (60 plus its rank). RRF ignores raw scores, which matters because BM25 scores and cosine distances live on incompatible scales.

Rerankers buy precision

A bi-encoder (your embedding model) embeds query and document separately, which is what makes indexing possible. A cross-encoder reranker reads the query and one candidate together and outputs a relevance score. It is far more accurate and far too slow to run over the whole corpus, so you run it on the top 50 or so fused candidates and keep the best 5 to 10.

A full request, with a latency budget

  1. Embed the query

    One call to the embedding model, local or hosted.

  2. Retrieve candidates in parallel

    ANN search and BM25 run concurrently, each returning around 50 candidates, with tenant and permission filters applied inside the query.

  3. Fuse and rerank

    RRF merges the lists, then the cross-encoder scores the fused set and keeps the top 5.

  4. Generate with citations

    The model receives the question plus the chunks, labelled with IDs it must cite, and streams the answer.

StageTypical latency (approximate)Notes
Query embedding5 to 30 ms local, 50 to 150 ms hosted APICache embeddings of popular queries
ANN plus BM25, in parallel2 to 20 msHigher with heavy filters or cold caches
Rerank 50 candidates20 to 50 ms on GPU, 100 to 400 ms on CPUOften the largest retrieval cost
Time to first token200 ms to over 1 sGrows with prompt length; prompt caching helps
GenerationSecondsStreamed, so users tolerate it

Retrieval should usually take well under a fifth of total latency. If it does not, the reranker or an unindexed filter is the usual culprit.

Measuring retrieval quality

Retrieval quality asks whether results are the documents a human would call relevant. You need labelled queries with their relevant document IDs, often called qrels.

MetricDefinitionRead it as
Recall@kRelevant documents found in the top k, divided by all relevant documentsDid the answer make it into the context at all
MRR@kAverage of 1 divided by the rank of the first relevant result, 0 if none in the top kHow high the first good result sits
nDCG@kRank-weighted gain, normalized to the ideal orderingQuality of the whole ordering, with graded labels

For RAG, recall@k at your context size (say k = 5) matters most, because the generator cannot use a document it never saw. MRR tells you whether a reranker is earning its latency.

metrics.py
def recall_at_k(retrieved, relevant, k):
    return len(set(retrieved[:k]) & relevant) / len(relevant)
 
def mrr_at_k(retrieved, relevant, k):
    for rank, doc_id in enumerate(retrieved[:k], start=1):
        if doc_id in relevant:
            return 1 / rank
    return 0.0

The chapter "Evaluation infrastructure" turns these functions into a regression gate that runs on every pull request.

Key terms

Embedding
A fixed-length vector a model produces so that similar meanings are close in space.
ANN recall
The fraction of the exact top-k neighbours that an approximate index returns.
HNSW
A layered proximity graph searched greedily from sparse upper layers down to a full bottom layer.
IVF
An index that clusters vectors with k-means and scans only the clusters nearest the query.
Product quantization
Compression that replaces sub-vectors with one-byte codebook IDs, trading accuracy for memory.
BM25
A keyword ranking function that rewards rare query terms with diminishing returns for repetition.
Reciprocal Rank Fusion
A rank-only method for merging result lists by summing 1 over 60 plus rank.
Cross-encoder
A model that scores a query and one document together; accurate but too slow for whole-corpus search.
MRR
Mean reciprocal rank: the average of 1 over the position of the first relevant result.
Lab

Build and tune a RAG service on Postgres and pgvector

Intermediate, 120 min

Goal: build a small RAG service over the SciFact corpus, measure ANN recall while tuning HNSW and IVFFlat, then show with numbers what hybrid search and a reranker add.

You need: Docker, Python 3.11 or newer, and Ollama. Everything runs on a laptop CPU; 8 GB of RAM is enough. The next chapters in this part reuse this project, so put it in its own Git repository.

  1. Start Postgres with pgvector and pull the models. The embedding model makes 768-dimension vectors; the small chat model writes answers.
mkdir rag-lab && cd rag-lab && mkdir data
docker run -d --name pgv -e POSTGRES_PASSWORD=rag -e POSTGRES_DB=rag \
  -p 5432:5432 pgvector/pgvector:0.8.7-pg18
ollama pull nomic-embed-text && ollama pull qwen3:1.7b
python3 -m venv .venv && source .venv/bin/activate
pip install "psycopg[binary]" pgvector numpy pandas pyarrow ollama \
  sentence-transformers fastapi uvicorn
  1. Download SciFact: about 5,200 scientific abstracts, plus test queries with human relevance labels.
B=https://huggingface.co/datasets/BeIR
curl -L -o data/corpus.parquet  $B/scifact/resolve/main/corpus/corpus-00000-of-00001.parquet
curl -L -o data/queries.parquet $B/scifact/resolve/main/queries/queries-00000-of-00001.parquet
curl -L -o data/test.tsv        $B/scifact-qrels/resolve/main/test.tsv
  1. Create the schema. The generated tsv column gives you keyword search for free.
schema.sql
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE IF NOT EXISTS docs (
  id        text PRIMARY KEY,
  title     text NOT NULL,
  body      text NOT NULL,
  embedding vector(768),
  tsv       tsvector GENERATED ALWAYS AS
            (to_tsvector('english', title || ' ' || body)) STORED
);
CREATE INDEX IF NOT EXISTS docs_tsv ON docs USING gin (tsv);
docker exec -i pgv psql -U postgres -d rag < schema.sql
  1. Write the shared module. Keyword search here uses Postgres full-text ranking with OR semantics, which is BM25-like rather than true BM25; that is enough to see the hybrid effect.
common.py
import os
import numpy as np
import ollama
import psycopg
from pgvector.psycopg import register_vector
 
DSN = os.getenv("DSN", "postgresql://postgres:rag@localhost:5432/rag")
EMBED_MODEL = "nomic-embed-text"
CHAT_MODEL = os.getenv("CHAT_MODEL", "qwen3:1.7b")
 
def connect():
    conn = psycopg.connect(DSN, autocommit=True)
    register_vector(conn)
    conn.execute("SET hnsw.ef_search = 100")  # must be at least the candidate pool
    return conn
 
def embed(texts, kind):
    prefix = "search_query: " if kind == "query" else "search_document: "
    resp = ollama.embed(model=EMBED_MODEL, input=[prefix + t for t in texts])
    return [np.array(e, dtype=np.float32) for e in resp["embeddings"]]
 
def vector_search(conn, qvec, k=10):
    sql = "SELECT id FROM docs ORDER BY embedding <=> %s LIMIT %s"
    return [r[0] for r in conn.execute(sql, (qvec, k)).fetchall()]
 
def keyword_search(conn, question, k=10):
    sql = """
      SELECT id FROM docs,
        replace(plainto_tsquery('english', %s)::text, '&', '|')::tsquery AS q
      WHERE tsv @@ q ORDER BY ts_rank_cd(tsv, q) DESC LIMIT %s"""
    return [r[0] for r in conn.execute(sql, (question, k)).fetchall()]
 
def rrf(rankings, k=60, top=10):
    scores = {}
    for ranking in rankings:
        for rank, doc_id in enumerate(ranking, start=1):
            scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)[:top]
 
_reranker = None
 
def rerank(conn, question, ids, top=10):
    global _reranker
    if _reranker is None:
        from sentence_transformers import CrossEncoder
        _reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
    rows = dict(conn.execute(
        "SELECT id, title || '. ' || body FROM docs WHERE id = ANY(%s)", (ids,)).fetchall())
    scores = _reranker.predict([(question, rows[i]) for i in ids])
    ranked = sorted(zip(ids, scores), key=lambda x: x[1], reverse=True)
    return [i for i, _ in ranked[:top]]
 
def hybrid_search(conn, question, k=10, pool=50, use_rerank=True):
    qvec = embed([question], "query")[0]
    fused = rrf([vector_search(conn, qvec, pool), keyword_search(conn, question, pool)], top=pool)
    return rerank(conn, question, fused, k) if use_rerank else fused[:k]
  1. Ingest. Each SciFact abstract is short enough to be one chunk, so this step skips chunking; for your own documents, chunk here.
ingest.py
import pandas as pd
from common import connect, embed
 
corpus = pd.read_parquet("data/corpus.parquet").rename(columns={"_id": "id"})
conn = connect()
rows = list(corpus.itertuples(index=False))
for i in range(0, len(rows), 64):
    batch = rows[i:i + 64]
    vecs = embed([f"{r.title}. {r.text}" for r in batch], "document")
    with conn.cursor() as cur:
        cur.executemany(
            "INSERT INTO docs (id, title, body, embedding) VALUES (%s, %s, %s, %s) "
            "ON CONFLICT (id) DO NOTHING",
            [(r.id, r.title, r.text, v) for r, v in zip(batch, vecs)])
    print(f"{i + len(batch)}/{len(rows)}", end="\r")
print("\ndone")
python ingest.py   # 5183/5183, then done; a few minutes on a laptop CPU
  1. Measure ANN recall. With no vector index, Postgres scans every row, so the first run is your exact ground truth. Then the script builds indexes with different settings and compares.
recall.py
import time
import numpy as np
import pandas as pd
from common import connect, embed
 
conn, K = connect(), 10
qrels = pd.read_csv("data/test.tsv", sep="\t", dtype=str)
queries = pd.read_parquet("data/queries.parquet")
texts = queries[queries["_id"].isin(set(qrels["query-id"]))]["text"].tolist()
qvecs = embed(texts, "query")
SQL = "SELECT id FROM docs ORDER BY embedding <=> %s LIMIT %s"
 
def run():
    results, lat = [], []
    for v in qvecs:
        t = time.perf_counter()
        results.append([r[0] for r in conn.execute(SQL, (v, K)).fetchall()])
        lat.append((time.perf_counter() - t) * 1000)
    return results, np.percentile(lat, 50), np.percentile(lat, 99)
 
for name in ("docs_hnsw", "docs_ivf"):
    conn.execute(f"DROP INDEX IF EXISTS {name}")
truth, p50, p99 = run()
print(f"exact                       p50={p50:.2f}ms p99={p99:.2f}ms")
 
def recall(res):
    return np.mean([len(set(r) & set(t)) / K for r, t in zip(res, truth)])
 
conn.execute("SET enable_seqscan = off")  # small table: force the planner onto the index
for m, efc in [(4, 16), (16, 64)]:
    conn.execute("DROP INDEX IF EXISTS docs_hnsw")
    t = time.perf_counter()
    conn.execute(f"CREATE INDEX docs_hnsw ON docs USING hnsw (embedding vector_cosine_ops) "
                 f"WITH (m = {m}, ef_construction = {efc})")
    build = time.perf_counter() - t
    for ef in (10, 20, 40, 100):
        conn.execute(f"SET hnsw.ef_search = {ef}")
        res, p50, p99 = run()
        print(f"hnsw m={m:<2} efc={efc:<3} ef={ef:<3}  recall={recall(res):.3f} "
              f"p50={p50:.2f}ms p99={p99:.2f}ms build={build:.1f}s")
conn.execute("DROP INDEX docs_hnsw")
conn.execute("CREATE INDEX docs_ivf ON docs USING ivfflat (embedding vector_cosine_ops) "
             "WITH (lists = 72)")
for probes in (1, 4, 8, 16):
    conn.execute(f"SET ivfflat.probes = {probes}")
    res, p50, p99 = run()
    print(f"ivfflat lists=72 probes={probes:<2}  recall={recall(res):.3f} p50={p50:.2f}ms")
conn.execute("DROP INDEX docs_ivf")
conn.execute("CREATE INDEX docs_hnsw ON docs USING hnsw (embedding vector_cosine_ops)")
python recall.py

Recall should climb towards 1.000 as ef_search and probes rise, with the weak m=4 graph and probes=1 clearly below the rest. At 5,000 vectors exact search is already fast; the point is the shape of the curve, which holds at any scale.

  1. Measure retrieval quality against the human labels, for four retrieval strategies.
quality.py
import numpy as np
import pandas as pd
from common import connect, embed, vector_search, keyword_search, hybrid_search
 
conn = connect()
qrels = pd.read_csv("data/test.tsv", sep="\t", dtype=str)
relevant = qrels.groupby("query-id")["corpus-id"].apply(set).to_dict()
queries = pd.read_parquet("data/queries.parquet").set_index("_id")["text"]
tests = [(qid, queries[qid]) for qid in relevant]
 
strategies = {
    "vector": lambda q: vector_search(conn, embed([q], "query")[0], 10),
    "keyword": lambda q: keyword_search(conn, q, 10),
    "hybrid": lambda q: hybrid_search(conn, q, use_rerank=False),
    "hybrid+rerank": lambda q: hybrid_search(conn, q, use_rerank=True),
}
for name, search in strategies.items():
    recalls, rrs = [], []
    for qid, text in tests:
        got, gold = search(text), relevant[qid]
        recalls.append(len(set(got[:5]) & gold) / len(gold))
        rrs.append(next((1 / r for r, d in enumerate(got, 1) if d in gold), 0.0))
    print(f"{name:<14} recall@5={np.mean(recalls):.3f}  MRR@10={np.mean(rrs):.3f}")
python quality.py

Expect scores roughly in the 0.6 to 0.8 range, with hybrid matching or beating either retriever alone and the reranker typically adding a few points of MRR. Queries where keyword search wins usually contain rare technical terms.

  1. Wrap it as a service that reports where the time goes.
rag.py
import time
import ollama
from common import CHAT_MODEL, embed, vector_search, keyword_search, rrf, rerank
 
PROMPT = ("Answer the question using only the sources below. Cite sources as [id]. "
          "If the sources do not contain the answer, say you do not know.")
 
def answer(conn, question, k=5):
    t, marks = time.perf_counter(), {}
    def mark(name):
        nonlocal t
        now = time.perf_counter()
        marks[name] = round((now - t) * 1000, 1)
        t = now
    qvec = embed([question], "query")[0]; mark("embed_ms")
    fused = rrf([vector_search(conn, qvec, 50), keyword_search(conn, question, 50)], top=50)
    mark("retrieve_ms")
    ids = rerank(conn, question, fused, k); mark("rerank_ms")
    rows = conn.execute("SELECT id, title, body FROM docs WHERE id = ANY(%s)", (ids,)).fetchall()
    sources = "\n\n".join(f"[{i}] {title}. {body}" for i, title, body in rows)
    reply = ollama.chat(model=CHAT_MODEL, think=False, messages=[
        {"role": "system", "content": PROMPT},
        {"role": "user", "content": f"Sources:\n{sources}\n\nQuestion: {question}"}])
    mark("generate_ms")
    return {"answer": reply["message"]["content"], "doc_ids": ids,
            "contexts": {i: body for i, _, body in rows}, "timings": marks}
app.py
from fastapi import FastAPI
from pydantic import BaseModel
from common import connect
from rag import answer
 
app, conn = FastAPI(), connect()
 
class Ask(BaseModel):
    question: str
 
@app.post("/ask")
def ask(req: Ask):
    return answer(conn, req.question)
uvicorn app:app --port 8000 &
curl -s localhost:8000/ask -H 'content-type: application/json' \
  -d '{"question": "Does vitamin D supplementation reduce fracture risk?"}' | python -m json.tool

The response contains an answer with bracketed citations, the cited document IDs and a timings object. On a CPU laptop, generation dominates, and reranking is the largest retrieval stage.

Check your work: you have a table showing recall against exact search for at least six index configurations, a quality table where hybrid plus rerank has the best MRR@10 (or a written explanation of why it does not on your run), and a /ask endpoint that returns cited answers with a per-stage latency breakdown.

Stretch: set hnsw.iterative_scan = relaxed_order, add a year column with a filter that keeps only 5 percent of rows, and compare result counts and recall with and without iterative scans.

Check yourself

Your HNSW index reports recall@10 of 0.99 against exact search, but users say answers miss obvious documents. What should you investigate first?

A multi-tenant app filters every vector query by tenant_id. Small tenants frequently get only two or three results instead of ten. What is the most likely cause?

Why does Reciprocal Rank Fusion use only ranks rather than adding BM25 scores to cosine similarities?

You switch to a better embedding model and re-embed new documents only, leaving old rows untouched. What happens?

A RAG endpoint takes 2.4 s before the first token. Embedding takes 20 ms, retrieval 15 ms, reranking 1.8 s on CPU and time to first token from the model 500 ms. Which change helps most?

Recap

  • Embeddings turn retrieval into nearest-neighbour geometry, and the metric and model must match at write and query time.
  • Exact search is the ground truth but scales linearly; ANN indexes trade a measurable amount of recall for orders of magnitude less work.
  • HNSW gives low latency at a memory cost and tunes per query with ef_search; IVF and PQ trade accuracy for build speed and compression.
  • Most retrieval quality is decided at ingestion: chunking, metadata, freshness, deletes and versioned embeddings.
  • Hybrid BM25 plus vectors, fused with RRF and reranked by a cross-encoder, is the standard production retrieval stack.
  • Measure two different things: ANN recall against exact search, and recall@k and MRR against human relevance labels.

Go deeper