Lesson 29 of 40Building LLM systems
Embeddings, Vector Databases and Hybrid Search
Run retrieval at production scale: pick an embedding model, tune HNSW, use pgvector well, fuse BM25 with vectors, chunk smartly and isolate tenants.
The toy RAG from RAG and Embeddings searched nine chunks with a loop. Your company's version has 12 million chunks across 400 customer workspaces, a 300 ms latency budget, users who may only see documents they have permission for, a legal team asking how to delete one person's data, and an embedding model the team wants to upgrade. None of that is solved by "call the embeddings API and store the vectors". This lesson covers the layer underneath retrieval: how to choose and change embedding models, how approximate indexes trade recall for speed, how to do it in Postgres with pgvector, when a dedicated vector database earns its place, and how to combine keyword and vector search properly.
Choosing an embedding model
An embedding model is a long-lived decision, because every stored vector depends on it. Weigh these properties:
- Dimensions. Typical models output 256 to 3,072 numbers per text. More dimensions can hold more nuance, but storage and search cost grow linearly. 10 million chunks at 1,024 dimensions in 32-bit floats is about 41 GB of raw vectors before any index overhead; at 3,072 dimensions it is about 123 GB.
- Max input tokens. Text beyond the limit is cut off or rejected. That caps your chunk size.
- Languages and domain. A model trained mostly on English web text may cluster legal clauses, code or Japanese support tickets poorly. Some vendors offer code, legal or finance variants.
- Asymmetric embeddings. Questions and documents look different: "can I bring my dog?" versus a paragraph of pet policy. Many models take an input type, such as
input_type="query"or"document"in Voyage AI's API (the embeddings provider Anthropic's docs point to, since Anthropic does not offer an embeddings model), and embed each side slightly differently. Use it; it is a free quality gain. - Matryoshka embeddings. Some models are trained so that the first 256 or 512 numbers of a vector are already a usable, smaller embedding. You can truncate to save storage and speed, then re-normalise. Check that your model supports this before slicing vectors; truncating an ordinary embedding destroys it.
The public MTEB leaderboard ranks models across many retrieval tasks and is a fine way to build a shortlist. It is not the decision. Leaderboard data is not your data, and some models are tuned towards the benchmark. The decider is your own retrieval eval: a few hundred real queries labelled with the chunks that should come back, scored with recall@k for each candidate model.
Normalise and pick the right distance. Cosine similarity compares direction only. If you normalise every vector to length 1 when you store it, cosine similarity and dot product give the same ranking, and dot product is cheaper. Use the distance the model was trained for (the model card says), and use the same one everywhere.
Changing models means re-embedding everything
Vectors from two different models live in unrelated spaces. A query embedded with model B compared against documents embedded with model A gives nonsense scores, and nothing errors. So a model upgrade is a data migration:
Step 1
Version the index
Store the model id with every vector, or keep one index or column per model version, such as embedding_v2.
Step 2
Dual-write
New and changed documents are embedded with both the old and new model from now on, so the new index does not fall behind.
Step 3
Backfill
A batch job re-embeds the existing corpus with the new model, throttled to respect rate limits. Batch embedding APIs are usually cheaper here.
Step 4
Evaluate in shadow
Run the retrieval eval and a sample of live queries against both indexes. Compare recall@k and latency before any user sees the new one.
Step 5
Cut over, then clean up
Switch query embedding and search to the new index together, behind a flag you can flip back. Drop the old vectors once you are confident.
The trap is step 5: query and document embeddings must switch at the same moment. A flag that changes one without the other produces a silent quality collapse.
Exact versus approximate search
A flat (exact) index compares the query with every vector. Recall is perfect and the cost is O(n × d) per query. Up to a few hundred thousand vectors that is often fine, especially with a filter that shrinks n first. Beyond that you need an approximate nearest neighbour (ANN) index, which looks at a small fraction of vectors and accepts missing a few true neighbours.
Two families dominate:
- IVF (inverted file): cluster the vectors with k-means into, say, 1,000 lists. At query time, search only the
probesnearest lists. Fast to build and small, but recall drops for queries near cluster borders, and clusters drift as data changes. - HNSW (hierarchical navigable small world): a graph where each vector links to its near neighbours, plus sparse upper layers with long-range links. A search starts at the top, jumps across the space in big steps, then descends and walks the dense bottom layer greedily towards the query. It is the default in most vector stores because it gives high recall at low latency and handles inserts without retraining.
The search arrives at an entry point, handed down from the sparse upper layers that already jumped close to the right region.
HNSW has three knobs, and every interviewer who knows the topic will ask about them:
| Knob | Set when | Higher means |
|---|---|---|
m | Building | More links per node: better recall, more memory, slower build |
ef_construction | Building | Wider search while inserting: better graph, slower build |
ef_search | Querying | More candidates kept during search: better recall, higher latency |
ef_search is the one you tune live. The block below builds a small one-layer navigable graph over clustered vectors and searches it with different ef values, counting how many distance computations each search costs compared with a flat scan.
Press Run (⌘ Enter) to see what happens.Read the output as a curve: each doubling of ef buys less recall and costs more work. With ef=80 this toy finds about 97% of the true top 10 while touching roughly a third of the vectors. At 10 million vectors the fraction touched is tiny, which is the whole point. Try M = 4 and watch recall fall: fewer links make the graph harder to navigate.
Quantisation shrinks vectors to fit more in memory. Scalar (int8) stores each number in one byte instead of four, with small recall loss. Binary keeps only the sign of each number, one bit per dimension, 32 times smaller, with a large recall loss on its own. The standard fix is rescoring: search the small quantised index for, say, the top 100, then re-rank those 100 using the full-precision vectors. You get most of the memory saving and most of the recall.
Match each change to its main effect.
pgvector in depth
If your data already lives in Postgres, start with the pgvector extension. Keeping vectors next to the rows they describe means one transaction for writes, one backup, and, most importantly, joins against permissions and metadata in the same query. Version notes matter here: HNSW indexes arrived in 0.5.0, halfvec (16-bit floats, half the storage) and sparse vectors in 0.7.0, and iterative index scans in 0.8.0. Check what your managed Postgres provider ships.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
tenant_id bigint NOT NULL,
doc_id bigint NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
body text NOT NULL,
model text NOT NULL, -- which embedding model made the vector
embedding halfvec(1024) NOT NULL, -- half the size of vector(1024)
tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', body)) STORED
);
CREATE INDEX ON chunks USING hnsw (embedding halfvec_cosine_ops) WITH (m = 16, ef_construction = 64);
CREATE INDEX ON chunks USING gin (tsv);
CREATE INDEX ON chunks (tenant_id);SET hnsw.ef_search = 100; -- default is 40
SET hnsw.iterative_scan = relaxed_order; -- pgvector 0.8.0+
SELECT id, body, embedding <=> $1 AS distance
FROM chunks
WHERE tenant_id = $2
ORDER BY embedding <=> $1
LIMIT 10;<=> is cosine distance (1 minus cosine similarity), and the operator class in the index must match it: vector_cosine_ops for vector, halfvec_cosine_ops for halfvec. If the query uses a different operator, Postgres silently does a full scan instead of using the index. Run EXPLAIN and look for the index scan.
The WHERE tenant_id = $2 line hides the classic filtered-search problem. An HNSW scan walks the graph and produces up to ef_search candidates; the filter is applied after. If this tenant owns 1% of the rows, perhaps none of the 100 candidates belong to them, and the query returns fewer than 10 rows, or zero. Before 0.8.0 the workarounds were raising ef_search, partial indexes per large tenant, or partitioning. Iterative index scans fix the common case: when the filter removes too many rows, the scan keeps walking the graph until it has enough, up to a limit you can set. relaxed_order is faster but can return rows slightly out of order, so re-sort in an outer query if order matters.
This block shows the difference with SQLite and a cosine function registered from Python. The first query filters inside the search; the second does what a naive post-filter does.
Press Run (⌘ Enter) to see what happens.The Acme user asked about refunds, Acme has a refund policy, and the naive version returns nothing, because Globex's chunks crowded the candidate list. In production that looks like "the bot says we have no refund policy" for small tenants only, which is a hard bug to find unless you know this mechanism.
Managed and dedicated options
| Option | Fits when |
|---|---|
| pgvector (self-managed, RDS, Aurora, Cloud SQL, AlloyDB and others) | Data is already in Postgres, up to tens of millions of vectors, and you want joins and transactions |
| OpenSearch / Elasticsearch | You already run them for keyword search and want hybrid in one engine |
| Pinecone | Fully managed, serverless, little ops; namespaces per tenant |
| Qdrant, Weaviate, Milvus | Dedicated engines, open source or managed, strong filtering and quantisation options |
| turbopuffer | Very large, many-namespace workloads built on object storage, cheap at rest |
| Amazon S3 Vectors | Huge, rarely queried collections where low storage cost matters more than latency |
Choose on: scale (vectors now and in two years), filtering needs (how selective, how many fields), multi-tenancy model, latency target, freshness (seconds or hours from write to searchable), and ops capacity. A common senior answer: start in Postgres, measure, and move only the retrieval workload when a number (p95 latency, index build time, memory) says you must.
Hybrid search done properly
RAG and Embeddings introduced hybrid search. Here is how it is actually built.
BM25 is the standard keyword ranking in Elasticsearch, OpenSearch and most search engines. A word scores higher when it is rare across the corpus (inverse document frequency), appears in the document more often, but with diminishing returns (the k1 parameter), and when the document is short relative to average (the b parameter). It is excellent for exact tokens such as error codes, SKUs, names and function names, where embeddings blur. Postgres full-text search with ts_rank is useful but is not BM25: it does not use corpus-wide word rarity. Extensions that add BM25 to Postgres exist; check what your platform supports.
You cannot just add a BM25 score to a cosine similarity: they are on different, unrelated scales. Reciprocal Rank Fusion (RRF) ignores scores and uses only ranks. Each document gets the sum of 1 / (k + rank) over every list it appears in, with k usually 60. A document near the top of both lists wins; a document top of one list and missing from the other still scores well.
Press Run (⌘ Enter) to see what happens.For the error code, vector search put the wrong error (kb-105) first, because to an embedding model one error code looks much like another. BM25 nailed it, and fusion put kb-101 on top. For "refused", the keyword list matched kb-103 on the word "card", and fusion left kb-101 and kb-103 tied. That tie is the job of the final stage: a reranker (a cross-encoder that reads the query and each candidate together) scores the top 30 to 50 fused results on meaning and keeps the best handful. Fuse for recall, rerank for precision.
What does this print?
k = 60 score = 1 / (k + 1) # rank 1 in the keyword list only print(round(score, 4))
Chunking with numbers
Chunking decides what a "result" even is. Starting points that work well, to be tuned with your eval:
- Fixed size with overlap: 300 to 800 tokens per chunk with 10 to 20% overlap, so a sentence cut at a boundary appears whole in one chunk. Simple and a reasonable baseline.
- Structure-aware: split on headings, list items, table rows and code blocks, never in the middle of a function or table. Carry the heading path ("Billing > Refunds > EU") into each chunk.
- Parent-document retrieval: search small chunks (precise matching) but return the larger parent section to the model (enough context to answer).
- Contextual retrieval: before embedding, have a cheap model write one or two sentences placing each chunk in its document ("This is from Acme's 2026 EU refund policy, section on damaged goods") and prepend it to the chunk for both the embedding and the BM25 index. Anthropic reported large drops in failed retrievals from this, bigger again with reranking. Prompt caching keeps the cost of passing the whole document per chunk down.
- Late chunking: embed the whole document with a long-context embedding model, then pool token vectors per chunk, so each chunk's vector "knows" its surroundings. Worth knowing; model support varies.
Tenants, deletes and freshness
Multi-tenant isolation has two designs. A shared index with a tenant filter on every query is simple and cheap, but a missing filter is a data leak, so enforce it below the application (Postgres row-level security, or a search wrapper that refuses queries without a tenant). One namespace or index per tenant gives hard isolation and easy per-tenant deletion, at the cost of many small indexes. Big tenants often get their own; the long tail shares.
Deletes are a compliance feature. A GDPR erasure request reaches the source row, every chunk and vector derived from it, the BM25 index, caches of answers, and eventually backups. HNSW deletes usually mark nodes as deleted and clean up later (in Postgres, through VACUUM), so heavy delete churn can degrade the graph until it is rebuilt. Store doc_id on every chunk so a delete is one query.
Freshness is a pipeline: a change event (an outbox table or change data capture) goes to a queue; a worker chunks, embeds and upserts. Hash each chunk's text and skip re-embedding when the hash has not changed; most edits touch one section. Measure "time from write to searchable" and alert on it.
Put a production hybrid retrieval request in order.
- Tap the steps below in the right order.
- ANN index
- An approximate nearest neighbour index that searches a fraction of the vectors and trades a little recall for large speed gains.
- HNSW
- A layered graph index: long links on upper layers, dense local links at the bottom, searched greedily from the top down.
- ef_search
- The HNSW query-time setting for how many candidates to keep while searching; higher means better recall and slower queries.
- quantisation
- Storing vectors with fewer bits per number (int8 or binary) to save memory, usually followed by rescoring with full precision.
- BM25
- The standard keyword ranking function, scoring rare, repeated query words in shorter documents higher.
- Reciprocal Rank Fusion
- Merging ranked lists by summing 1 / (k + rank) for each document, ignoring the original incompatible scores.
- contextual retrieval
- Prepending a short, document-aware description to each chunk before embedding and keyword indexing it.