Skip to content

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.

23 min read0/5 questions

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:

Upgrading the embedding model without downtime
  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

Quick check
Your team swaps the query embedding model to a newer one but keeps the stored document vectors. What happens?
Need a nudge? A hint rules out a wrong answer.

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 probes nearest 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.
A greedy walk on the bottom layer
entryabcdequery

currentwaitingdone

The search arrives at an entry point, handed down from the sparse upper layers that already jumped close to the right region.

1/4

HNSW has three knobs, and every interviewer who knows the topic will ask about them:

KnobSet whenHigher means
mBuildingMore links per node: better recall, more memory, slower build
ef_constructionBuildingWider search while inserting: better graph, slower build
ef_searchQueryingMore 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.

Python
import math, random random.seed(42)DIM, N, K = 16, 1200, 10 def normalise(v): n = math.sqrt(sum(x * x for x in v)) return [x / n for x in v] def dot(a, b): return sum(x * y for x, y in zip(a, b)) # Clustered data, like real embeddings: 30 topics, documents scattered around each.centres = [normalise([random.gauss(0, 1) for _ in range(DIM)]) for _ in range(30)]docs = [normalise([c + random.gauss(0, 0.35) for c in random.choice(centres)]) for _ in range(N)]queries = [normalise([c + random.gauss(0, 0.35) for c in random.choice(centres)]) for _ in range(40)] def exact_top_k(q, k=K): """Flat index: compare the query with every vector. Perfect recall, O(n) work.""" return sorted(range(N), key=lambda i: -dot(q, docs[i]))[:k] # Build a navigable graph: each node links to its M nearest neighbours plus 2 random# long-range links (HNSW gets its long links from upper layers instead).M = 8graph = []for i in range(N): sims = sorted(((dot(docs[i], docs[j]), j) for j in range(N) if j != i), reverse=True) graph.append([j for _, j in sims[:M]] + random.sample(range(N), 2)) def graph_search(q, ef, entry=0): """Greedy best-first search keeping the ef best candidates (HNSW's ef_search).""" computed = 0 def score(i): nonlocal computed computed += 1 return dot(q, docs[i]) visited = {entry} candidates = [(score(entry), entry)] # to explore best = list(candidates) # best ef found so far while candidates: candidates.sort() s, node = candidates.pop() # most similar unexplored node if len(best) >= ef and s < min(best)[0]: break # nothing left can improve the result for nb in graph[node]: if nb in visited: continue visited.add(nb) sn = score(nb) if len(best) < ef or sn > min(best)[0]: candidates.append((sn, nb)) best.append((sn, nb)) if len(best) > ef: best.remove(min(best)) top = [i for _, i in sorted(best, reverse=True)[:K]] return top, computed truth = [set(exact_top_k(q)) for q in queries]print(f"{N} vectors, {DIM} dims, recall@{K} averaged over {len(queries)} queries")print(f"flat (exact): recall 1.00, distance computations per query: {N}")for ef in (10, 20, 40, 80): hits, work = 0, 0 for q, t in zip(queries, truth): found, computed = graph_search(q, ef) hits += len(t & set(found)) work += computed print(f"graph ef={ef:<3} recall {hits / (K * len(queries)):.2f}, " f"distance computations per query: {work // len(queries)}")
Output
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 the pairs0/5 matched

Match each change to its main effect.

Choose an item, then its match on the other side.

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.

schema.sql
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);
search.sql
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.

Python
import json, math, sqlite3 db = sqlite3.connect(":memory:") def cosine_distance(a_json, b_json): # pgvector's <=> operator: 1 - cosine similarity (0 = same direction) a, b = json.loads(a_json), json.loads(b_json) dot = sum(x * y for x, y in zip(a, b)) norm = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)) return 1 - dot / norm db.create_function("cosine_distance", 2, cosine_distance)db.executescript("""CREATE TABLE chunks (id TEXT PRIMARY KEY, tenant_id TEXT, text TEXT, embedding TEXT);""")rows = [ ("a1", "acme", "Acme refund policy: 30 days", [0.8, 0.3, 0.0]), ("a2", "acme", "Acme shipping times", [0.1, 0.9, 0.1]), ("g1", "globex", "Globex refund policy: 14 days", [0.95, 0.05, 0.0]), ("g2", "globex", "Globex refunds need a receipt", [0.9, 0.2, 0.0]), ("g3", "globex", "Globex refunds for damaged goods", [0.85, 0.1, 0.1]), ("g4", "globex", "Globex refund exceptions", [0.88, 0.0, 0.2]),]db.executemany("INSERT INTO chunks VALUES (?, ?, ?, ?)", [(i, t, txt, json.dumps(v)) for i, t, txt, v in rows])query = json.dumps([1.0, 0.1, 0.0]) # "how do refunds work?" print("1) Filter inside the query (what pgvector does with WHERE + iterative scans):")for row in db.execute(""" SELECT id, text, round(cosine_distance(embedding, ?), 3) AS dist FROM chunks WHERE tenant_id = ? ORDER BY dist LIMIT 2""", (query, "acme")): print(" ", row) print("\n2) Naive post-filter: take the global top 3, then drop other tenants:")top3 = db.execute(""" SELECT id, tenant_id, round(cosine_distance(embedding, ?), 3) AS dist FROM chunks ORDER BY dist LIMIT 3""", (query,)).fetchall()print(" global top 3:", top3)print(" after filter:", [r for r in top3 if r[1] == "acme"])
Output
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

OptionFits 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 / ElasticsearchYou already run them for keyword search and want hybrid in one engine
PineconeFully managed, serverless, little ops; namespaces per tenant
Qdrant, Weaviate, MilvusDedicated engines, open source or managed, strong filtering and quantisation options
turbopufferVery large, many-namespace workloads built on object storage, cheap at rest
Amazon S3 VectorsHuge, 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.

Python
import math, refrom collections import Counter DOCS = { "kb-101": "Error E1043 means the payment card was declined by the issuing bank.", "kb-102": "If a customer's card is refused, ask them to contact their bank or try another card.", "kb-103": "Refunds go back to the original card within five working days.", "kb-104": "To export invoices, open Billing and choose Export as CSV.", "kb-105": "Error E2001 appears when the CSV export times out on very large accounts.",} def tokens(text): return re.findall(r"[a-z0-9]+", text.lower()) # ---- BM25: the default ranking in Elasticsearch, OpenSearch and most search engines ----k1, b = 1.2, 0.75doc_tokens = {d: tokens(t) for d, t in DOCS.items()}avg_len = sum(len(t) for t in doc_tokens.values()) / len(DOCS)df = Counter(w for toks in doc_tokens.values() for w in set(toks)) def idf(word): n = df.get(word, 0) return math.log(1 + (len(DOCS) - n + 0.5) / (n + 0.5)) # rare words count more def bm25(query): scores = {} for d, toks in doc_tokens.items(): tf = Counter(toks) s = 0.0 for w in tokens(query): if tf[w]: # term frequency saturates (k1) and long documents are penalised (b) s += idf(w) * tf[w] * (k1 + 1) / (tf[w] + k1 * (1 - b + b * len(toks) / avg_len)) if s > 0: scores[d] = s return sorted(scores, key=scores.get, reverse=True) # ---- Pretend vector search: hand-made ranked lists standing in for an embeddings model ----# A real model ranks by meaning: "card refused" is close to "declined", but it blurs codes.VECTOR_RESULTS = { "what does E1043 mean": ["kb-105", "kb-102", "kb-101", "kb-103"], "my card keeps getting refused": ["kb-102", "kb-101", "kb-103", "kb-105"],} def rrf(rankings, k=60): """Reciprocal Rank Fusion: sum 1 / (k + rank) over every list a document appears in.""" fused = Counter() for ranking in rankings: for rank, doc in enumerate(ranking, start=1): fused[doc] += 1 / (k + rank) return [(doc, round(score, 4)) for doc, score in fused.most_common()] for query, vector_ranking in VECTOR_RESULTS.items(): keyword_ranking = bm25(query) print(f"Q: {query}") print(" bm25: ", keyword_ranking) print(" vector:", vector_ranking) print(" rrf: ", rrf([keyword_ranking, vector_ranking])[:3]) print()
Output
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.

Predict the outputPython

What does this print?

k = 60
score = 1 / (k + 1)          # rank 1 in the keyword list only
print(round(score, 4))
Need a nudge? Hints walk you through it.

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.

Quick check
Small tenants report that search often returns nothing, while large tenants are fine. The query uses an HNSW index with WHERE tenant_id = ?. What is the most likely cause?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Put a production hybrid retrieval request in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
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.