# The hard part of vector retrieval isn't HNSW; it's what you trade off for what

Date: 2025-07-07
Category: Interview Preparation
Tags: Vector Retrieval, System Design, Trade-offs
Summary: Starting from a recall fluctuation, this lays out the costs of HNSW parameters, filter placement, normalization, and hybrid retrieval one by one, making clear which costs in vector retrieval must be calculated at project initiation.

For a while, I stared at a recall curve every day. It didn't drop noticeably; it just wobbled by two or three points during a certain period. My first suspicion was that the index parameters had drifted, so I dug through the `efSearch` config, reran the stress tests, and went around in circles, only to find that the embedding model had changed versions and the chunking strategy had moved along with it.

After that, my view of this kind of vector-retrieval interview question shifted a bit. Most questions ask "do you know how to use HNSW," while what actually trips people up at work is usually the other half: do you know what you're trading away for what.

## Recall dropped—don't rush to touch the index parameters

A query goes through several transformations from entering the system to becoming an answer: first it's split into chunks, then mapped to vectors, then fed into the index for approximate search, and on the way out it may get reranked. Whichever link goes wrong, the symptom is the same: inaccurate results.

I've been burned by this. The first time recall got worse, my instinct was to tune the index, pulling `efSearch` from 64 to 200. Recall did come back a few points, and latency went up with it. The real problem was in the chunking: fixed-length splitting cut a table in half, so retrieval only ever returned the first half. The parameters just covered up the noise.

So now when someone asks me how to troubleshoot recall issues, I give the opposite order: look at chunking and the model first, then the filter conditions, and only last the index parameters. The index is the easiest to tune, and therefore the easiest to blame. This order is quite useful in interviews—it shows I know where the system's boundaries are, rather than treating ANN (approximate nearest neighbor search) as a word that explains everything.

There's another decision in the pipeline that often gets skipped: where metadata filtering goes. Put it before retrieval, and the candidate set is narrowed in advance—fast, but if the conditions are too narrow they may filter out the correct answer and recall drops straight to zero. Put it after retrieval, and the index can use its full capability, at the cost of fetching a batch first and then discarding it, burning compute and bandwidth for nothing. I lean toward putting narrow, highly selective conditions up front and vague conditions that might do collateral damage later, then looking at the results to decide whether to split it into two retrievals. There's no universal answer here, only your estimate of the data distribution.

Reranking has to be counted in the same cost ledger. Adding a cross-encoder layer usually raises accuracy, but every candidate has to go through the model, so latency grows linearly. Reranking a hundred recalled items and reranking twenty are completely different cost-benefit propositions. I've seen a solution where the metrics looked better after adding reranking but P99 doubled, and in the end all it could do was cut the candidate count—which is trading recall for latency again.

## M, efConstruction, and efSearch are three different bills

The HNSW structure isn't hard to explain: the bottom layer holds all nodes, the upper layers are sparse, and long-distance jumps are made through the layers. What's hard is explaining clearly what cost each of the three numbers M, `efConstruction`, and `efSearch` is paying for.

M is the upper limit on neighbors per node. It determines the density of the graph and directly determines memory. A larger M makes the graph more connected with fewer isolated islands, but every edge has to be stored, so the memory cost is plain to see.

`efConstruction` is the candidate list size when building the graph. It only affects writes, not queries. Raising this value gives a better-quality graph, at the cost of slower construction.

`efSearch` is the candidate list at query time and can be changed at runtime. It's the easiest parameter to tune: no index rebuild, immediate effect, at the cost of latency and QPS.

I once memorized "`efConstruction` should be set larger than `efSearch`" as a settled conclusion. Later, in a write-heavy, read-light scenario, I found that this statement has a precondition: it assumes index construction is one-off and reads dominate afterward. If the data is a continuously written stream, the latency of a single insert directly blocks the write path, and raising `efConstruction` in that case is just making trouble for yourself.

When reads dominate and writes are light, I lean toward giving M and `efConstruction` plenty, in exchange for a lower `efSearch` online. When writes dominate, it's the reverse: accept around 95% recall and get writes running first. Neither choice is more correct; it just depends on which side I'm willing to take the loss on.

When memory is really tight, I move away from HNSW. Its memory bloat is structural, and tuning can't fix it. IVF plus PQ is more practical then: coarse filtering first, then precise reranking with the original vectors, trading one extra read for accuracy back. PQ's compression ratio is tempting, but it works by splitting vectors into segments, clustering each segment, and replacing the original floats with cluster-center IDs—it's lossy by nature. The order of recalled results will be off and must be corrected by reranking. How much can be recovered depends on how many original vectors I'm willing to read for it.

Graph indexes have another headache: deletion. Most implementations just set a flag; the node stays in the graph and the edges stay too. Delete enough, and searches take detours, and memory isn't freed. So in production you have to periodically compact, or just rebuild—the same idea as defragmenting a traditional database, only more expensive, since distances have to be recomputed and edges reconnected.

Cold start is in the same cost ledger. Loading a multi-GB index from disk into memory causes page faults along the way, and latency wobbles. Production environments usually need to warm up before traffic is switched in; otherwise the first wave of requests amplifies the wobble into an outage. These are the parts interviews rarely ask about but that you will definitely hit once you're live.

The rough memory estimate isn't actually hard; what's hard is getting someone to do it at project kickoff. A float32 vector is dimension times four bytes—that's the raw data; then each edge in the graph stores an ID, and the larger M is, the more substantial this part becomes. Combined, the index usually takes about twice the memory of the raw vectors, with the exact multiple depending on dimension and parameters. That number should come out when you're choosing a solution, not when you look back after the machines can't take it anymore.

## Once normalization is done, there's little to argue about in distance metrics

Cosine similarity, inner product, and Euclidean distance are asked about a lot in interviews, but what really determines the result is often not which one you pick, but whether the vectors are normalized.

After normalizing to unit length, all three give the same ranking. Cosine's denominator becomes 1, so inner product is cosine; L2 and cosine have a monotonic relationship—the smaller the distance, the greater the similarity. The only difference left is compute: inner product is just multiply-add, the most instruction-efficient.

So the common production practice is to normalize uniformly before indexing and configure inner product in the index. This choice isn't mysterious; it's trading semantic equivalence for a bit of CPU.

The real trap is when you don't normalize. If the model's output magnitude itself carries information, L2 will count "similar length" as "similar semantics," and vectors for short texts and high-frequency words tend to cluster together. Unless the business genuinely needs the magnitude (say, it represents confidence), I require that normalization has a clear owner rather than assuming the model does it.

On this question, I don't much like answers that derive all three formulas. That proves memory, not judgment.

What's more worth spending time on than distance metrics is hybrid retrieval. Dense vectors are good at semantics and weak on exact matches like model numbers, error codes, names, and abbreviations. When a user looks up a specific product number, the semantic model may recall a bunch of "related categories" that all look right—just not the one. That's not the model being bad; it's doing a different job to begin with.

So in real systems I almost always keep a keyword retrieval path, run the two in parallel, and merge them with rank fusion. Fusion can't just add the scores from both sides, because their scales are completely different—one has no upper bound, the other is between zero and one. Fusing by rank is more stable, at the cost of losing some information in the scores: whether the first place leads by a lot or barely wins isn't visible after fusion. I accept that loss in exchange for not having to tune normalization separately for each path.

## Recall rate can't be answered apart from latency

Recall is not a fixed attribute. For the same index, raising `efSearch` increases recall while latency goes up and QPS goes down; increasing `nprobe` (the number of probe clusters in IVF) involves the same trade-off. So "what is your recall" cannot be answered without also giving latency and concurrency.

I now try to state things with conditions attached: at what data scale and what P99 latency, what is Recall@K. The three numbers only mean something when they appear together.

What is harder is ground truth. Approximate search inherently allows misses, so how do you know how much it missed? The only way is to run a brute-force baseline offline and compare the approximate results against it. This step is crude, a full scan, and not cheap, but without it every later metric is self-referential.

When a single machine cannot hold the data, the problem shifts from algorithm to architecture. Sharding handles capacity and writes; replicas handle concurrency and availability. These two are often conflated. After sharding, a query must go to all shards and then be merged; the more shards, the more pronounced the tail—if any one shard is slow, the whole request is slow. So more shards is not better; there is an upper bound determined by tail latency. Replicas are pure addition, trading machines for QPS, at the cost of money and complexity around consistency.

The benchmarking method also determines what I see. Measuring only average latency is almost guaranteed to be optimistic; measuring only single concurrency says nothing about production. I usually look at three sets of numbers together: single-request latency at low concurrency, P99 at the target QPS, and where the metrics start to collapse when QPS is pushed one notch higher. The third set is the most informative—it marks the real boundary of this configuration.

I am still catching up on this. Parameter tables can be copied, but the operating point has to be found by testing yourself, and when you change the dataset or the model, the previous operating point is very likely invalid. If there is any stable lesson, it is roughly this: first decide which dimension you are willing to sacrifice this time, then change parameters—rather than tuning parameters first and seeing what the metrics turn into.
