Ch.58: Vector Database System Design: Why Search Misses

Outline

Transcript

0:00 Ask a photo app for a bicycle beside a canal. A vector database helps it search by comparing number lists that represent the phrase and its photos. Nearby lists suggest similar scenes, beyond matching words in filenames. But our designer needs three wide, high-resolution photos for a banner. We'll design that database: how it searches quickly, applies hard constraints, and handles changing records. We'll follow one query through it. For example, search rejects its three nearby candidates even though suitable banner photos exist elsewhere in the catalog.

0:30 That leaves an empty list while suitable photos are still in the catalog. Our shortlist never reached them. First, follow the banner request on this complete map. We choose a search route, ask each machine to search its share of the photos, then merge their answers. A separate write route saves new records and makes them searchable. We'll return to this exact map. Original papers and current maintainer docs support the mechanisms; those source links are in the description. This backend is our proposed design.

1:00 We also need to check whether that fast answer left useful photos behind. What can the photo app insist on? Before choosing components, our functional requirements start with adding, replacing and deleting a photo record. Each record has a stable identifier, a version, a vector and metadata. For example, the metadata says how many pixels wide it is and whether it's landscape or portrait. Those are hard conditions on returned photos. Yes. The query supplies a compatible vector, those conditions and a result count.

1:29 We return photo identifiers and distances, with the revision searched in each data partition. So similarity chooses the order among eligible photos. It can't excuse returning a tiny portrait when the caller asked for a wide banner. And callers need a way to tell whether their latest change is searchable. Otherwise a successful upload and an empty search become a guessing game. Next, put non-functional requirements around those operations. Choose a fictional 100-million-photo catalog, 2000 queries per second and 500 record changes per second.

2:02 Set the server latency target at 100 milliseconds at the 95th percentile. That's a 10th of a second. Acknowledged writes must be durable; becoming searchable has a separate 1-second objective. For search quality, aim to recover at least 95% of the exact nearest 10, averaged across declared test queries. We call that recovery fraction recall. I don't trust a latency chart alone here. If the service answers quickly by barely looking, what tells us we're getting a useful search? Fast and empty would be an easy target.

2:35 Measure the recovered neighbors alongside latency, then track update lag separately. The planner limits work per caller, including this banner request, so other searches still get capacity. We'll calculate recall after we've built a search worth comparing with the exact answer. Before optimizing that search, define the representation. An encoder is a model that turns an input into a vector, meaning a list of numbers. Does one position mean bicycle, another canal, another sunlight? That would make those lists fairly easy to inspect.

3:06 Well, usually no. Meaning is spread across those numbers. The original text-and-image research shows how a model can place related phrases and photos near each other. Then fix the encoder configuration and choose one distance measure. Equal-length lists can still come from incompatible models, like two maps with two coordinates but different zero locations. Exactly. Nearness is evidence of similarity under that model. Whether the picture actually suits a customer's page is another evaluation, beyond our distance calculation.

3:37 With compatible vectors, the simplest query compares against every eligible record and keeps the nearest. That's exact search under our chosen distance. For example, three eligible photos need only three comparisons. But scanning a hundred million vectors for every query spends work on the entire catalog. Let's put a size on that catalog: 768 numbers per vector, 4 bytes each. The raw vectors alone occupy just over 307 decimal gigabytes. And that's before identifiers, metadata, search links or replicas.

4:09 That's already substantial. Does our design actually need all those bytes in memory? That depends on the storage layout and which data queries repeatedly touch. The estimate isn't a RAM requirement. Small eligible sets can use exact scans; larger searches need fewer comparisons. Now replace the full scan with approximate nearest-neighbor search. It tries to find close vectors while comparing only part of the data, accepting that some better ones may be missed. One approach is HNSW, a hierarchy of nearby-item graphs.

4:40 Sparse upper levels support broad moves; lower levels give us more detailed local connections. Imagine a toy city with 100 addresses. Major roads reach a neighborhood; local streets refine the route. Visiting 20 addresses saves work but can miss the closest. Yeah. Keep alternative routes open instead of betting everything on the first one. Exploring more candidates costs time and memory, but can recover neighbors a narrow search misses. That makes the search budget a quality decision. Sorting the visited photos beautifully won't help if we never visited the useful ones. Now apply our photo constraints.

5:17 How can three close results turn into zero when the catalog still has three suitable images? Let's walk through the actual miniature. Ask for landscape photos at least 2,400 pixels wide. The unfiltered nearest three are A, B and C. A and B are portraits, while C is too small. Filtering that completed list removes every result. Nothing about their similarity scores changed. Meanwhile D, E and F satisfy both conditions. They sit outside that initial three-photo list. The pgvector maintainers document this kind of underfilled filtered search.

5:52 My first thought is to fetch 30 instead. Would that actually solve it? If the extra candidates include D, E and F, yes. A rarer filter can still remove all 30. The pictures were there. Our first shortlist hid every one. Let the constraints shape our search. With that filter problem established, let the planner estimate how many records pass the metadata conditions. If only D, E and F qualify, why use an approximate graph at all? Score those three exactly. We know their identifiers from the metadata index, compare their vectors, and return the defined nearest order without searching unrelated photos. All that map building, and this query can skip it.

6:31 What changes when exact scoring itself would miss our deadline? Consider a toy graph link from C to D. C fails the width condition, but its link reaches eligible D. A rejected output can still be an internal stepping stone. So keep bounded exploration through useful routes. Qdrant also documents extra graph links built from pre-existing metadata indexes. Those cost storage and rebuilding; neither technique guarantees exact recovery. Next, make that query work while photos change. Record each versioned update in our replicated operation log.

7:05 Acknowledge only after the required copies have saved it safely. Then search can't depend solely on a giant graph rebuilt overnight. A photo added this morning would remain absent despite its successful write. Keep recent applied records in a searchable buffer, a waiting room while workers build indexed chunks called segments. Queries combine both paths. Then a query whose view includes that update can find the photo while indexing catches up. Qdrant documents durable operations and record versions; this two-path layout and replica acknowledgement are choices we're making.

7:38 Return a revision token so callers can request their new data. What should a query do when the replica it reaches hasn't applied that revision yet? Wait for it, or route to a replica that has caught up, within the deadline. If neither works, report that freshness failure instead of quietly serving the older view. But that searchable buffer can hold a replacement for D. In a later version of our six-photo example, its landscape record is version 8 and its applied portrait is version 9. Which photos does a new banner query return?

8:11 On that replica, a new read excludes portrait D and returns E with F. It keeps that catalog view for the whole request. Even if the old graph still nominates D? That route was built around the landscape photo. The graph supplies an identifier. Resolve its version in that request's view before checking the filter and final distance. Search recent versions too. A visible deletion suppresses D instead of reviving its older copy. But the builder started before that portrait arrived. It's still making an index containing landscape D.

8:44 What stops that replacement from undoing our filter fix? The builder uses its pre-portrait copy, keeping version 9 in the recent buffer. Publish the replacement list in one switch. This list names the indexed chunks new queries use. Our running query keeps its old index and the portrait D it saw at the start. Its answer is still E, followed by F. Like lending someone a catalog. An earlier request borrowed it while D was landscape, so it can still return D. Replacing the desk copy doesn't let us tear pages from the one they're still reading. Suppose that last old request finishes.

9:21 Can we finally remove its old records? The borrower's finished, but keep the chunks and version history while another request still needs them. Replicas must also have caught up, and saved updates must no longer be able to recreate an older, deleted photo. Only then remove unneeded segments and deletion records. Now distribute that versioned search across shards, separately owned pieces of the catalog. The query router sends the search to each required partition, choosing a sufficiently current replica.

9:51 Each replica searches its chosen view, applies version and filter rules, and returns candidates plus its revision. Those revisions needn't describe one global instant. Imagine four librarians each selecting 10 photo cards. The coordinator sorts 40 cards. It cannot recover a great photo that none of those librarians included. I'd be tempted to ask each librarian for a bigger stack. Where does that start hurting? That grows network traffic and coordinator work across the partitions. Choose candidate and exploration budgets together.

10:21 Spend extra work where measurements show it recovers useful neighbors, instead of assuming a larger list is free. But sending the query to every required partition introduces another limit. For example, every shard responds before the deadline except one whose replica is stalled. Do we return the others? Only under an explicit partial-result policy. This design lets the caller choose a labeled partial answer or an error when a required shard is missing. All four librarians can send their cards and still miss a near neighbor.

10:50 If one sends no answer, we're missing its entire contribution as well. Right. Keep that distinction in the response and metrics. An empty partial answer cannot establish that the catalog contains no matching photos. And don't retry until the requested slots happen to fill. A deadline is a boundary on work, not a suggestion we discard when the answer looks disappointing. Now measure the approximate part offline, on a saved catalog copy. Choose a separate query having at least 10 eligible photos. Keep its data, distance rule and filters fixed for both exact and fast search.

11:25 For example, exact search identifies 10 nearest photos. Our fast route returns 10 too, but only eight belong to that exact set. Recall at 10 is eight out of 10. 80%. A full screen hid two missed neighbors. Those other slots weren't blank, though. What did the fast search put there? Other eligible photos outside the exact comparison set. Evaluate average recall across the chosen workload, testing narrow filters and fresh changes separately. Measure recovery alongside the latency budget. And ask people whether the photos are useful.

11:57 Exact vector neighbors can still disappoint them. Approximation loss and the representation's usefulness need separate explanations. Finally, return to our complete architecture and the original catalog, before that later portrait replacement. The query reaches the planner with its width and landscape conditions. The planner identifies D, E and F as eligible and compares that small set exactly. D, E and F, without a graph search. Their versions decide eligibility; applied changes and built indexes supply the records.

12:25 Our merge returns those three photos. Saving updates and making them searchable remain separate checkpoints. For a large eligible set, the same service uses measured approximate search. Its deadlines, recall and visibility lag stay visible rather than disappearing behind one green success response. So our missing photos were outside a list chosen without their constraints. We fixed that particular query by changing the search plan, not by pretending three rejected candidates exhausted the catalog.

12:54 I'd now ask which records were eligible, which routes were explored and whether every required shard replied. Those explain an empty screen much better than latency alone. A fast answer earns trust when we can describe what it searched and measure what it missed. Thanks for listening to Learning Podcasts.