Systemsfor Aravinda
0 / 78 core
Week 8 · Modern systems

Vector search

1.5 hours · core path

Read first: Indexes: B-trees and LSM trees, Retrieval-augmented generation

In one sitting

An embedding is a point, and exact nearest-neighbor search touches every point, which does not survive a large corpus on a user path. HNSW searches a coarse small-world layer and then a finer one, trading recall against latency and memory. Tenant and time filters belong in the query, because a filter applied after the walk can return a wrong-tenant neighbor or quietly starve a small tenant.

You embedded the chunks. Now a question is a point, and you need the chunks that sit near it, for this tenant, fast enough that the agent can use them on the request the user is waiting for. “Check every chunk” is correct and, past a certain corpus, impossible on that path. The index you build instead will sometimes miss a nearer point. You need to say that out loud, and you need the miss to stay inside the tenant.

Core concepts

An embedding maps a chunk, or a query, to a list of numbers. That list is a point. Distance to other points is a stand-in for “the embedding model considers these similar.” It is only as good as the model and the chunk. Retrieval-augmented generation is why you have the points at all: the thing you return is a passage id, and the passage bytes still live in the source of truth. The vector store does not become the document.

Exact nearest neighbors compute the distance from the query to every point, then take the closest. The answer is right, relative to the embedding. The work is proportional to the number of points. One query over N points does about N distance computations. A user-facing path that does this at large N is a path that gets slower every time you add a document. Exact search dies at scale because the corpus grows and the latency budget does not.

HNSW is the layered graph people reach for instead. Malkov and Yashunin described a hierarchical navigable small world: each point is a node with links to a handful of nearby points, arranged in layers. The top layer is a small sample with long-range links. Each lower layer has more nodes and shorter links. The bottom layer has everyone.

Search enters at the coarse layer and greedy-walks: from the current node, step to the neighbor closest to the query, until no neighbor is closer. Then drop to the finer layer and continue, and so on down to the base. You visit a small neighborhood instead of N. You can miss a true neighbor that the walk never stepped toward. That miss is the recall gap.

Recall here means: of the true nearest neighbors, how many did the search return. You measure it by running exact search on a sample of queries and comparing ids. You do not recite a percentage from memory, and this page will not invent one. Latency is how long the walk takes, which grows as you allow it to visit more nodes. Memory is the vectors plus the edges. If each node stores M edges, edge storage is proportional to N × M. Double the links and you double that term. More links give the walk a better chance of a useful step, and each step looks at more neighbors, so latency moves too.

You can push recall up by searching longer or storing more edges. You pay latency, memory, or both. You can cut latency and memory by searching less, and recall falls. There is no setting that maximizes all three. A blocking tool inside an agent cares about the latency the user waits on. An offline job that builds an eval set can spend the walk and demand the neighbors be closer to exact. Say which one you are building before you pick a knob.

A B-tree does not save you inside the vector space. Bayer and McCreight’s structure is the right tool for a point read or a range on a key: tenant id, timestamp, document id. It does not answer “which points are near this one” in a high-dimensional embedding. You still want it, or something like it, for the predicate. Equality on a tenant and a range on time are ordinary key lookups. Nearest-neighbor is the other structure. The hit you return should carry the document id so you can fetch the real text from the source, not from the vector.

Filters belong in the query. A tenant id or a time window is part of what “nearest” means. Nearest in the whole corpus is the wrong question if the caller may only see one tenant.

Pre-filter restricts the candidate set to legal points, then searches. The neighbor you return is the nearest legal neighbor. On a small tenant the restricted set may be small enough that exact search over just those points is the right plan. The graph walk, if you still use one, has to stay inside the predicate. Points that fail the filter are not candidates.

Post-filter walks the global graph first and drops illegal hits afterward. This looks easy to bolt on. It fails in two ways that feel like mystery relevance bugs. If the tenant is a thin slice of the corpus, the nearest global points may all belong to someone else. You throw them away and keep whatever is left, which can be empty or a distant leftover, because the walk already stopped. And if the filter is late, buggy, or fails open, the hit you already selected is a wrong-tenant neighbor. The embedding was honest. The texts really were near. Authorization never ran. That is a data leak with a similarity score attached.

flowchart LR
  query[Query point] --> predicate[Tenant predicate]
  predicate --> coarse[Coarse layer]
  coarse --> fine[Finer layer]
  fine --> base[Base layer]
  base --> hits[Neighbor ids]

The predicate sits in front of the walk on purpose. A box drawn after the hits is post-filter, and post-filter is how a small tenant gets other people’s neighbors.

A worked example

You search chunks for an agent that serves many tenants from one index. Most of the corpus belongs to a handful of large tenants. One small tenant asks questions too.

Assumptions:

  • 20,000,000 vectors in the global index.
  • Tenant A owns 5,000 of them. Tenant B owns the other 19,995,000. Both counts are assumptions you would take from a real catalog before you design the filter.
  • 1,000,000 searches a day, spread across tenants. You are not claiming a company’s traffic. You are picking a round interview number and showing the arithmetic.
  • Distance cost is whatever your embedding dimension makes it. You will count distance operations, not invent a microseconds-per-distance benchmark.
1 day = 86,400 s
shortcut ≈ 100,000 s
1,000,000 searches / 86,400 ≈ 11.6/s ≈ 12 searches/s

assumption: 20,000,000 vectors
exact work at the average ≈ 12 × 20,000,000 = 240,000,000 distances/s

assumption: peak is 3× 
peak exact work ≈ 36 × 20,000,000 = 720,000,000 distances/s

tenant A only: 5,000 vectors
exact inside A ≈ 12 × 5,000 = 60,000 distances/s

Two hundred forty million distances a second, before the peak, is the reason exact nearest neighbors do not survive this corpus on the user path. Sixty thousand distances a second inside tenant A is a different regime. A’s queries can be exact over A’s points and still have budget left. B’s queries cannot scan 19,995,000 points per search. One global exact plan treats A and B as the same problem. They are not.

HNSW is how you avoid the 240 million. The walk visits a neighborhood whose size you choose, on a graph whose edges you paid for in memory. Recall is whatever that choice achieves on a sample you compare to exact search. If you cannot show the sample, you do not have a recall number, and you should not borrow one.

Now the wrong tenant. A’s question, “how do we rotate the signing key,” lands near a chunk of B’s that uses the same words and contains B’s key material. Similarity is real.

Post-filter, done carelessly: the walk returns 10 global neighbors. Nine are B. One is A. If the caller asked for 5 from A, you have 1, and the other 4 are whatever else survived, possibly weak matches. If a bug returns the top hit before the filter, or the filter fails open when the tenant claim is missing, A receives B’s key material. The symptom in a relevance review is “the model leaked.” The bug is the order of operations.

Pre-filter: A’s search never sees B’s nodes. With 5,000 points, you can scan them exactly at 60,000 distances a second and skip the global graph entirely. B still needs the layered walk, with the predicate applied so the walk does not spend its budget stepping through other tenants and then discarding them.

A time filter has the same shape. “Nearest among docs updated this week” is not “nearest overall, then hope one of them is recent.” If you post-filter a week onto a corpus of years, you can throw away the entire candidate list and return nothing, or return an old document because you filled k before you noticed the dates. Pre-filter by time, or continue the walk until you have enough legal hits. Stopping at k global hits and then filtering is how you silently shorten the result.

Memory for the graph edges, so the tradeoff is visible without a fake recall:

assumption: you store M edges per node
edge storage ∝ N × M
N = 20,000,000
doubling M doubles edge memory
it also gives each greedy step more neighbors to inspect
latency per hop moves up as M moves up
recall moves only if those extra edges change where the walk can go
you learn which, by comparing to exact search on a sample

If the top layer is too sparse, the coarse walk never arrives near the right region, and the fine layers polish the wrong neighborhood. The query is fast. The neighbors are wrong. A latency dashboard stays green. Only the comparison to exact ids shows the miss. That is why recall is a measurement you run, not a setting you remember.

Tradeoffs

Choice What you gain What you spend
Exact scan The true nearest ids, for this embedding Work proportional to N, which misses the latency budget at large N
HNSW with more edges The walk has more ways to step toward the query Memory proportional to N times edges, and more work per hop
A longer walk Higher recall, if you measure it Latency on the path the agent is blocking on
A shorter walk A faster tool call Recall falls, and a latency graph will not tell you
Pre-filter by tenant Nearest legal neighbor, and small tenants can be exact The index has to search a subset, not decorate a global top-k
Post-filter after a global walk Simple to add beside an existing graph Small tenants get starved or, worse, someone else’s neighbor
A separate index per tenant Isolation is structural Many indexes to build, and a large tenant still needs an approximate graph

Use the distance the embedding model was built for. Swapping in a different one without re-embedding makes “near” a property you no longer defined. That is a recall collapse you can cause with a one-line change, and no graph parameter will explain it.

Pitfalls

  • Quoting a recall percentage you did not measure against exact search. The graph does not have a default recall. Your corpus and your walk do.
  • Post-filtering tenant or time after taking a global top-k. Small tenants look like they have a bad embedding. They have a bad plan, or they have just been shown another tenant’s chunk.
  • Treating a wrong-tenant neighbor as a ranking bug. If the text should not have been visible, the filter failed open. Fix authorization, then talk about similarity.
  • Using a B-tree as the nearest-neighbor structure. It will find the tenant’s rows. It will not find the nearby points. You want it in front of the vector walk, not instead of one.
  • Forgetting that the vector is not the passage. The hit must carry an id into the source of truth. A rebuilt index is fine. A rebuilt document is not.
  • Updating the source text and leaving the old point. You retrieve a neighbor whose text no longer exists. That stale hit is a retrieval bug on the RAG path.
  • Adding edges or walk depth because latency looks fine, without a fresh comparison to exact ids. You can spend memory and not move recall, or move recall and blow the tool’s deadline.
  • One shared graph and a filter in a different service that can time out and continue. Timeout-open is how B’s signing key reaches A’s prompt.

In the interview

Start with the arithmetic. Exact search is one distance per point per query, so at 12 queries a second over millions of vectors the product leaves the user path. An embedding is a point. HNSW is a layered small-world graph: coarse walk, then finer, then base. You trade recall, latency, and memory, and you only claim the recall you measured.

Skip parameter folklore from the paper. If you remember that more links and a longer search move the tradeoff, that is enough. Skip any percentage.

The question that usually follows is the filter. Say pre-filter versus post-filter in one breath, then the wrong-tenant neighbor: the nearest point in the world can be illegal, and a late filter either leaks it or throws away the list and returns something weak. Offer exact search for a tenant small enough that the product queries × points still fits, and the graph for the tenant that is the corpus.

Check yourself

You run 12 searches a second over 20 million vectors. Why is exact nearest neighbor the wrong plan on the user path?

Each search computes a distance per vector. Twelve times 20 million is 240 million distances a second at the average, before you apply a peak factor. That work grows when the corpus grows, and the user’s latency budget does not. Exact search remains the right way to grade a sample, and the right way to serve a tenant whose own count is small.

In HNSW, what does the coarse layer do that the base layer does not?

The coarse layer is a small sample with long-range links. The greedy walk uses it to get near the right region without visiting everyone. The finer layers, and then the base layer that holds every point, finish the search with shorter links. If the coarse layer never gets close, the lower layers carefully rank the wrong neighborhood, quickly.

Tenant A owns 5,000 of 20 million vectors. You take a global top 10 and drop the other tenants. Why can A still receive B's chunk?

Post-filter runs after the walk has already chosen neighbors. If the filter is missing, late, or fails open, the top hit can be B’s point, which was genuinely near and is not A’s data. Even when the filter works, nine of the ten hits may be discarded and A is left with a weak survivor. Pre-filter so B’s nodes are not candidates, or scan A’s 5,000 points exactly.

You double the number of edges per node. Which terms move, and which number are you not allowed to invent?

Memory for the edges is proportional to nodes times edges, so it doubles. Each hop inspects more neighbors, so latency can move up. Recall moves only if the new edges change the walk, which you learn by comparing to exact ids on a sample. You do not get to state a recall percentage as if it came with the library.

A latency chart for vector search is green and the agent is quoting the wrong runbook. What measurement is missing?

Recall against exact nearest neighbors on a labeled sample, inside the same tenant filter the user should have hit. A short walk and a sparse coarse layer are both fast and wrong. Query time will not show that. The id comparison will.

Based on: HNSW, Malkov and Yashunin; B-trees, Bayer and McCreight.