Vector Databases
A vector database stores embeddings, lists of numbers produced by a model, and answers one question very fast: "which stored vectors are closest to this one?" Turn a question into an embedding, and the closest document chunks are probably about the same thing. Turn a user into an embedding, and the closest items are probably things they'll like. That single operation, nearest neighbor search, sits under RAG, semantic search, recommendations, deduplication and image search.
A few properties define the category:
- Approximate, not exact: Finding the true nearest neighbors among a billion vectors means comparing against all of them. Vector databases use indexes that skip almost all of that work and return nearly the right answer, usually 90-99% of the true top results, in milliseconds.
- Vectors plus metadata: Each vector carries an ID and a payload (
tenant_id,doc_id,language,created_at). Real queries are "nearest neighbors where tenant = 42 and language = 'en'," and doing that filter well is harder than it sounds. - A database around an index: The index (HNSW, IVF) is an algorithm you can get from a library like Faiss. The database adds what the library doesn't: durable writes, updates and deletes, sharding, replication, filtering, access control and an API.
- Memory-hungry: The fastest indexes want everything in RAM. A lot of a vector database's design, from quantization to disk-based indexes, exists to make that cheaper.
Vector databases come up in almost every ML system design interview that touches retrieval. Your interviewer usually won't ask you to build one, but they will ask how you'd store 500 million chunks, why recall dropped after you added a tenant filter, or whether you really need Pinecone when you already run Postgres. So we'll cover how the indexes work, the knobs that trade recall for latency, how filtering and updates work under the hood, and how to pick one.
Embeddings and Similarity
An embedding model maps an input (a sentence, an image, a product, a user) to a fixed-length vector, typically 256 to 3,072 dimensions. The model is trained so that similar inputs land near each other. The vector database doesn't know or care what the numbers mean. It just measures distance.
There are three common distance measures:
| Metric | Formula (for vectors a, b) | When to use |
|---|---|---|
| Cosine similarity | a·b / (‖a‖‖b‖) | Text embeddings; only direction matters |
| Dot product (inner product) | a·b | Normalized vectors (same as cosine), or models trained for it, like many two-tower recommenders |
| Euclidean (L2) | ‖a − b‖ | Some image and older embedding models |
Use the metric the embedding model was trained with. If vectors are normalized to length 1, cosine, dot product and L2 all give the same ranking, which is why most systems normalize and use dot product: it's the cheapest to compute.
Now the size arithmetic, which drives almost every decision later:
- One 768-dimension float32 vector is 768 × 4 bytes = 3 KB.
- 100 million of them is 307 GB. A billion is about 3 TB.
- A 1,536-dimension vector doubles all of that.
That's before any index structure. Keep these numbers handy, because the first thing a good answer does is say whether the vectors fit in RAM.
Why Exact Search Doesn't Scale
The simplest vector search is a flat (brute-force) scan: compute the distance from the query to every vector, keep the top k. It's exact, it needs no index, and for small collections it's the right answer.
It stops working because the cost grows linearly with the data. A scan is bound by memory bandwidth, since every vector has to be read:
- 1M vectors (3 GB): a multi-threaded CPU scan reading on the order of 50-100 GB/s takes tens of milliseconds. Fine.
- 100M vectors (307 GB): several seconds per query on one machine. Not fine.
- On a GPU with around 2-3 TB/s of bandwidth a scan is much faster, but 307 GB doesn't fit on one GPU, and you'd need to do it hundreds of times a second.
A common mistake in interviews is reaching for a vector database for 50,000 vectors. Below a few million vectors, a flat scan with NumPy or Faiss's
IndexFlatIP, or a pgvector table without an index, is exact, simple and fast enough. Say so, and only introduce approximate indexes when the numbers demand it.
Approximate nearest neighbor (ANN) indexes get around this by looking at only a tiny fraction of the vectors. There are two main families: graph indexes (HNSW, DiskANN), which walk a graph of neighbors, and partition indexes (IVF), which only scan the clusters near the query. Quantization (PQ, scalar, binary) is a separate tool that shrinks vectors and combines with either.
HNSW: Graph Search
Hierarchical Navigable Small World (HNSW) is the default index in most vector databases (Qdrant, Weaviate, Milvus, pgvector, Elasticsearch, OpenSearch, Redis all offer it). It gives high recall at low latency, and it's what you should name first.
The idea: connect every vector to a few of its nearest neighbors, forming a graph. To search, start somewhere and repeatedly hop to whichever neighbor is closest to the query, until no neighbor is closer. That greedy walk works well locally but would take many hops to cross a large graph. So HNSW adds layers, like a skip list:
- Layer 0 has every vector, each linked to up to
2 × Mneighbors. - Each higher layer has an exponentially smaller random sample of vectors, with long-range links.
- A search enters at the top layer, greedily descends toward the query's region, drops a layer, and repeats. At layer 0 it runs a wider local search.
But what is actually happening under the hood? At layer 0, the search keeps a priority queue of the ef best candidates found so far. It repeatedly takes the closest unexplored candidate, computes the distance to each of its neighbors, and adds any that beat the worst of the ef best. It stops when the closest unexplored candidate is farther than the worst result. A larger ef explores more of the graph: higher recall, more distance computations, more latency.
HNSW has three knobs you should know:
| Parameter | What it controls | Typical range | Trade-off |
|---|---|---|---|
| M | Links per node | 8-64 (16 is common) | More links: better recall, more memory, slower build |
| efConstruction | Candidate list size while building | 100-500 | Higher: better graph quality, slower inserts |
efSearch (ef) |
Candidate list size while searching | 40-500, must be ≥ k | Higher: better recall, higher latency. Tunable per query |
Its strengths are speed and recall: a well-tuned HNSW index on tens of millions of vectors typically answers in a few milliseconds at 95%+ recall. Its weaknesses all come from being a big in-memory graph:
- Memory: the full vectors plus the links. At M = 16, layer 0 stores 32 neighbor IDs per vector, about 128 bytes with 4-byte IDs, plus a little for upper layers. For 100M 768-dimension vectors that's ~307 GB of vectors plus ~13 GB of graph. The links are cheap; the vectors are the problem.
- Build cost: every insert runs a search to find its neighbors. Building a 100M index takes hours on one machine.
- Deletes: removing a node leaves holes in the graph. Most implementations mark deleted nodes as tombstones (skipped in results, still walked through) and repair or rebuild in the background. Heavy churn degrades recall until that happens.
IVF: Search Only the Nearby Clusters
The inverted file index (IVF) takes the opposite approach. At build time, run k-means on a sample of vectors to find nlist centroids, then assign every vector to its nearest centroid. Each centroid owns a list of vectors, just as a search engine's inverted index maps a term to a posting list.
At query time:
- Compare the query to all
nlistcentroids (cheap: thousands, not millions). - Pick the
nprobeclosest centroids. - Scan only the vectors in those lists.
With 100M vectors and nlist = 65,536, each list holds about 1,500 vectors. Probing 32 lists scans about 49,000 vectors, 0.05% of the collection. Raise nprobe and recall goes up because you're less likely to miss a true neighbor sitting just across a cluster boundary, but you scan more.
IVF builds faster and uses less memory than HNSW (no graph, just a list assignment), and its lists map naturally onto disk, GPU batches and shards. At the same recall it's usually a bit slower than HNSW for single queries. A common rule of thumb is nlist on the order of √N to 16√N, then tune nprobe against measured recall. IVF also needs a training step: if your data drifts far from the sample the centroids were learned on (a new language, a new product category), lists become unbalanced and you retrain.
Quantization: Making Vectors Smaller
Both families still have to store and compare full vectors somewhere. Quantization compresses them, trading a little accuracy for a lot of memory and speed.
Scalar quantization (SQ) stores each float32 dimension as an int8, using per-dimension min and max to map the range onto 256 levels. That's 4x smaller with a small recall loss. Float16 (halfvec in pgvector) is 2x with almost no loss.
Binary quantization keeps one bit per dimension (positive or negative), so 32x smaller, and distance becomes a Hamming distance computed with XOR and popcount. Recall drops a lot on its own, but it works surprisingly well on high-dimensional embeddings when followed by rescoring.
Product quantization (PQ) is the most powerful and worth being able to explain:
- Split each 768-dimension vector into
m = 96sub-vectors of 8 dimensions. - For each of the 96 sub-spaces, run k-means to learn 256 centroids (a codebook).
- Store each sub-vector as the 1-byte ID of its nearest centroid.
Each vector is now 96 bytes instead of 3,072, a 32x reduction. 100M vectors drop from 307 GB to under 10 GB.
But what is actually happening under the hood? To compare a query with PQ codes, you don't decompress anything. For each of the 96 sub-spaces, precompute the distance from the query's sub-vector to all 256 centroids: a 96 × 256 lookup table. The distance to any stored vector is then 96 table lookups and adds. This is called asymmetric distance computation, because the query stays exact and only the stored vectors are approximated.
The standard combination is IVF-PQ: IVF picks which vectors to look at, and PQ makes looking at them cheap. Because PQ distances are approximate, the final step is rescoring (or reranking): take the top few hundred candidates by PQ distance, fetch their full-precision vectors (from RAM, SSD or object storage) and recompute exact distances. Rescoring recovers most of the recall that compression lost.
In an interview, the move that shows you understand this is "compress for the search, keep full vectors for the rerank." It lets you say how a billion vectors fit in a few hundred GB of RAM without giving up much recall.
DiskANN (and its Vamana graph) applies the same idea to graphs. Keep PQ-compressed vectors in RAM to guide the search, and the graph plus full vectors on SSD. Each hop costs an SSD read, but the graph is built to need few hops. It serves billion-scale indexes from one machine with a fraction of the RAM HNSW would need, at latencies of a few milliseconds instead of sub-millisecond. Several databases offer DiskANN-style or disk-backed indexes; check what your chosen engine actually supports.
Comparing the Index Types
| Index | Memory | Query speed | Recall | Build | Best for |
|---|---|---|---|---|---|
| Flat | Full vectors | Slow at scale | 100% | None | < a few million vectors, ground truth |
| HNSW | Full vectors + graph | Fastest | Highest | Slow | Default for up to ~100M per node with RAM to spare |
| IVF-Flat | Full vectors | Fast | High | Fast | Large collections, GPU search, frequent rebuilds |
| IVF-PQ | ~3-10% of full | Fast | Medium, high with rescoring | Medium | Hundreds of millions to billions |
| DiskANN | PQ codes in RAM, rest on SSD | Fast (SSD-bound) | High | Slow | Billion-scale on few machines |
| HNSW + SQ/BQ | 1/4 to 1/32 of full | Fastest | High with rescoring | Slow | When RAM is the constraint but you want graph search |
The Recall-Latency Trade-Off
Every ANN index has a dial between "fast" and "right." To reason about it you need a way to measure "right."
Recall@k is the fraction of the true top-k neighbors that the index returns. To compute it, run a sample of real queries (a few thousand) through a flat exact search to get ground truth, run them through the index, and compare. If the true top 10 has 10 items and the index returns 9 of them, recall@10 is 0.9.
Then sweep the knob (efSearch for HNSW, nprobe for IVF) and plot recall against p99 latency. The curve always looks the same: recall climbs quickly at first and then flattens, while latency keeps growing. Going from 90% to 95% recall is cheap. Going from 98% to 99.5% can double or triple the latency. You pick the point that meets the latency budget.
A few practical points make this concrete:
- Measure on your data and your filters. Benchmarks like ann-benchmarks use clean public datasets. Your recall depends on your embedding model, your dimension, and especially your filters.
- ANN recall isn't end-to-end quality. If the embedding model ranks the right chunk 40th, perfect ANN recall still misses it. In RAG, the embedding model and a reranker usually matter more than going from 95% to 99% ANN recall. Retrieve more candidates (say 100) and rerank them with a cross-encoder; see RAG Fundamentals.
- Latency also depends on k, dimension and concurrency. A 3,072-dimension vector costs 4x as much per distance as a 768-dimension one. Some embedding models support truncating dimensions (Matryoshka-style training), which is a cheap way to trade a little quality for a lot of speed and memory.
When your interviewer asks "how would you tune the index?", the answer is a process, not a number: build a ground-truth set with exact search, sweep
efSearchornprobe, and pick the cheapest setting that meets your recall target at your p99 latency budget. Then keep monitoring recall as data grows, because it drifts.
Filtering: The Hard Part
Real queries almost always come with a filter: this tenant's documents, products in stock under $50, posts from the last week. Combining a filter with ANN search is where naive designs break.
Post-filtering: run the ANN search for the top k, then drop results that fail the filter. Simple, but if the filter matches 1% of vectors, the top 10 by similarity will usually contain zero matches. You can over-fetch (ask for 1,000 to return 10), but for selective filters no over-fetch is enough, and you silently return too few results.
Pre-filtering: find all vectors that match the filter first, then search only among them. Correct, but if the filter matches 5 million vectors you're back to brute force over 5 million. And in a graph index, skipping filtered-out nodes breaks the graph's connectivity, so the greedy walk can get stuck.
Filter-aware search is what good vector databases do. They evaluate the filter during the traversal, using a bitmap of allowed IDs from a metadata index. Graph search walks through disallowed nodes for navigation but only returns allowed ones. When the filter is very selective (matches a few thousand vectors), the planner switches to a brute-force scan of just those, which is both exact and fast. Qdrant, Weaviate, Milvus and others each implement some version of this, and pgvector added iterative index scans (in its 0.8 releases) so a filtered HNSW query keeps scanning until it finds enough matches instead of returning too few.
Partitioning sidesteps the problem for your most common filter. If every query filters by tenant_id, give each tenant its own namespace, collection, or partition. Then a tenant's search only ever touches that tenant's index, isolation is enforced by structure instead of by a filter, and deleting a tenant is dropping a partition. This is the standard answer for multi-tenant RAG; Design a RAG System works through it for a thousand tenants.
| Filter selectivity | What works |
|---|---|
| Matches most vectors (> 10-20%) | Post-filtering or filter-aware graph search |
| Matches a moderate fraction | Filter-aware search with a metadata index |
| Matches very few vectors (thousands) | Pre-filter and brute-force those |
| Always the same field (tenant, region) | Partition by it |
Schema Design
A vector database collection looks a lot like a table, and designing it deserves the same care. For a RAG corpus:
{
"id": "doc_8812#chunk_14#v3",
"vector": [0.012, -0.044, ...],
"embed_model": "embed-v3",
"tenant_id": "acme",
"doc_id": "doc_8812",
"chunk_index": 14,
"doc_version": 7,
"acl_groups": ["legal", "exec"],
"language": "en",
"updated_at": 1764374400,
"text": "Either party may terminate this Agreement..."
}
The decisions behind it:
- Make the ID deterministic (
doc_id#chunk#model). Re-ingesting a document then upserts the same IDs instead of creating duplicates, and you can delete every chunk of a document by itsdoc_id. - Index the fields you filter on. Most engines need you to declare a payload index on
tenant_id,acl_groupsorupdated_atfor filters to be fast. Unindexed filters fall back to scanning. - Store only what you need in the payload. Storing the chunk text next to the vector saves a lookup, but it multiplies storage. For large text, store a pointer and fetch from a document store or S3.
- Track the embedding model version (
embed_model, and thev3in the ID). Vectors from two different models aren't comparable. You can't mix them in one index. - Multiple vectors per item when you need them: a title embedding and a body embedding, or a dense vector plus a sparse vector (SPLADE or BM25 weights) for hybrid search. Engines like Qdrant, Milvus, Weaviate and Vespa support named or multiple vector fields.
In pgvector, the same thing is just a table:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id text PRIMARY KEY,
tenant_id text NOT NULL,
doc_id text NOT NULL,
acl_groups text[] NOT NULL,
updated_at timestamptz NOT NULL,
body text NOT NULL,
embedding vector(1024) NOT NULL
);
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 200);
CREATE INDEX ON chunks (tenant_id);
SET hnsw.ef_search = 100;
SELECT id, body
FROM chunks
WHERE tenant_id = 'acme' AND acl_groups && ARRAY['legal']
ORDER BY embedding <=> $1 -- <=> is cosine distance
LIMIT 10;
That last query is the whole appeal of pgvector: vectors, filters, joins and transactions in one place, with SQL you already know.
Changing the Embedding Model
Sooner or later you'll switch to a better embedding model, and every vector has to be recomputed. You can't do it in place, since old and new vectors aren't comparable. The safe pattern is the same as any large backfill:
- Create a new collection for the new model.
- Dual-write: new and changed items get embedded with both models.
- Backfill the new collection from the source documents in a batch job.
- Shadow-test retrieval quality on the new collection, then switch reads (an alias swap, if the engine supports aliases).
- Drop the old collection.
Budget for it: re-embedding 500M chunks of 500 tokens is 250 billion tokens of embedding inference. That's a real batch job, measured in GPU-days (see Design an Offline Batch Inference Service).
Writes, Updates and Deletes
ANN indexes are built for reads. Graphs are expensive to modify and IVF lists are tied to trained centroids. So vector databases borrow the trick that LSM-tree databases use: don't modify the big index, write around it.
But what is actually happening under the hood? In a typical segment-based design (Milvus is the clearest example, and Lucene-based engines like Elasticsearch work similarly):
- A write goes to a write-ahead log first, so it's durable.
- It lands in a small, mutable growing segment that's searched by brute force or a light index.
- When the segment reaches a size threshold, it's sealed and a background worker builds a full HNSW or IVF index for it.
- Queries search every sealed segment's index plus the growing segment, and merge the results.
- Deletes are recorded as tombstones (a delete bitmap) and filtered out of results. Updates are a delete plus an insert.
- Compaction merges small segments and physically drops deleted vectors, then rebuilds indexes.
This is why most vector databases are eventually consistent for search by default: a vector you just upserted may take somewhere from milliseconds to a few seconds to show up in results, depending on the engine and its consistency setting. Some engines let you ask for stronger read-your-writes behavior per query at a latency cost. For RAG, a few seconds of lag is almost always fine. For a deduplication check that must see the item inserted a moment ago, it isn't, and you should say how you'd handle it (a consistency level, or a check against the source of truth).
Heavy delete and update churn is the weak spot. Tombstoned vectors still cost memory and search time until compaction, and in HNSW they degrade the graph. If a workload rewrites most of its vectors every day, consider rebuilding the index from scratch on a schedule, or partitioning by time so old partitions can be dropped whole.
Architecture and Scaling
A single node with a few hundred GB of RAM handles tens of millions of full-precision vectors with HNSW, or a few hundred million with quantization. Beyond that, or for high QPS, you scale like any search engine.
Sharding for size. Split the collection across shards, by hash of ID (even spread) or by tenant (isolation and locality). A query fans out to every shard that could hold matches, each returns its local top k, and a coordinator merges them into the global top k. Sharding by tenant means a single-tenant query touches one shard, which is far cheaper than a fan-out to all of them.
Replication for QPS and availability. Each shard has several replicas, and the coordinator load-balances across them. HNSW search is CPU-bound, so throughput scales roughly with cores. If you need 10x QPS, add replicas; if you need 10x data, add shards.
Separating storage from compute. Newer designs keep the source of truth (vectors, payloads, WAL) in object storage like S3 and treat query nodes as caches that load index segments on demand. Milvus 2.x splits the system into stateless proxies, query nodes, data nodes and index-building nodes, with object storage underneath. Pinecone's serverless offering and engines like turbopuffer and LanceDB also lean on object storage. The benefit is cost: storage is cheap, and you pay for RAM only on the hot part of the data. The cost is cold-query latency when a segment isn't cached.
The back-of-the-envelope for a large corpus looks like this:
- 1B chunks × 1,024 dims × 4 bytes = 4 TB of float32 vectors.
- HNSW over full vectors: 4 TB+ of RAM, roughly 20 nodes with 256 GB each before replication. Expensive.
- int8 scalar quantization: 1 TB. PQ at 128 bytes per vector: 128 GB, which fits on one or two machines, with full vectors on SSD or S3 for rescoring.
- At 2,000 QPS with each query fanning out to 16 shards, the cluster handles 32,000 shard-queries per second. At a few milliseconds of CPU each, that's on the order of 100 cores, before replication for availability.
Hybrid Search
Embeddings are good at meaning and bad at exact tokens: product codes, error messages, names, rare jargon. Keyword search (BM25) is the reverse. Hybrid search runs both and merges the results, and it's the default for production retrieval.
The common merge is Reciprocal Rank Fusion (RRF): score each result by Σ 1 / (60 + rank) across the lists it appears in. It needs no score calibration, since BM25 scores and cosine similarities aren't on comparable scales. Weighted score fusion and learned rerankers are the alternatives.
You can do hybrid search two ways: in one engine that supports both (Elasticsearch, OpenSearch, Vespa, Weaviate, Milvus and Qdrant with sparse vectors, or Postgres with pgvector plus full-text search), or in two engines with a merge step in your service. One engine is simpler and lets one filter apply to both halves. RAG Fundamentals covers chunking, hybrid retrieval and reranking in depth.
The Options
There are many vector databases, and they converge more each year. In an interview, the useful distinction is the category, not the brand.
| Option | Type | Strengths | Watch out for |
|---|---|---|---|
| pgvector | Postgres extension | One database for vectors, metadata and transactions; SQL filters and joins; HNSW and IVFFlat | Single-node scaling (unless sharded with Citus or similar), filtered search tuning, index build memory |
| Pinecone | Managed service | No operations, namespaces for multi-tenancy, serverless pricing | Vendor lock-in, cost at very high QPS, less control over index internals |
| Milvus / Zilliz Cloud | Distributed open source / managed | Built for billions, many index types (HNSW, IVF, PQ, DiskANN, GPU), storage-compute separation | Many moving parts to operate yourself |
| Qdrant | Open source / managed | Strong filtered search, quantization, Rust performance | Smaller ecosystem than Postgres or Elastic |
| Weaviate | Open source / managed | Hybrid search, built-in vectorizer modules, multi-tenancy | Similar trade-offs to other dedicated engines |
| Elasticsearch / OpenSearch | Search engine with vectors | BM25 + vectors + filters + aggregations in one, mature operations | Heavier, vector performance depends on version and settings |
| Vespa | Search and ranking engine | Hybrid retrieval plus multi-stage ML ranking in one place | Steeper learning curve |
| Faiss / ScaNN / hnswlib | Libraries | Fastest building blocks, GPU support in Faiss | No persistence, filtering, sharding or API; you build the database |
| Redis, MongoDB Atlas, cloud DBs | Vector search added to an existing store | Use what you already run | Feature depth varies |
How to choose:
- Already on Postgres and under ~10-50M vectors? Use pgvector. Fewer systems, transactional consistency between vectors and metadata, and filters in SQL. This is the right first answer surprisingly often.
- Need keyword search too, or already run Elasticsearch? Use its vector support for hybrid search in one engine.
- Hundreds of millions to billions of vectors, or heavy filtered search at high QPS? A dedicated engine: Milvus, Qdrant, Weaviate, or a managed service.
- No team to run infrastructure? A managed service like Pinecone or a cloud provider's offering.
- Offline batch similarity (deduplication, clustering)? A library like Faiss on GPUs, no database at all.
Interviewers often test whether you'll add a new database by reflex. "We store the vectors in Postgres with pgvector, next to the documents, until we pass a few tens of millions of vectors or need more QPS than one primary and its replicas can serve, then move to a dedicated engine" is a stronger answer than naming the trendiest product.
Vector Databases in an Interview
When to Use It
- RAG and semantic search: storing chunk embeddings and retrieving candidates for a reranker and an LLM. See Design a RAG System and Design Natural-Language Search for a Food Delivery App.
- Candidate generation for recommendations: a two-tower model embeds users and items; the vector index returns the top 1,000 items for a user embedding in a few milliseconds.
- Deduplication and entity resolution: find near-duplicate images, listings or events; see Design a Duplicate Event Detector.
- Agent memory: retrieving past notes or conversations relevant to the current task.
Knowing Its Limitations
- It's only as good as the embeddings. The index finds the vectors nearest the query. Whether those are relevant depends on the model, the chunking and the query. Most retrieval failures aren't ANN failures.
- Approximate means misses. Even at 95% recall, one true neighbor in twenty is missed. If you need exact answers (a uniqueness check, a legal hold), use exact search on a filtered subset or a different index.
- Filters can wreck recall. Selective filters with post-filtering return too few results. Plan for filter-aware search or partitioning.
- RAM is the cost driver. Full-precision HNSW over a billion vectors is several terabytes of memory. Quantization and disk-based indexes are how you make it affordable.
- Not a system of record. Keep the source documents and metadata in a real database or object store, and treat the vector index as a derived, rebuildable view. You will rebuild it, at the very least when you change embedding models.
- Updates are eventually visible. Most engines index writes asynchronously.
Questions You Might Get
- "How does HNSW work?" Layers of proximity graphs, greedy descent from a sparse top layer, a beam search with
efcandidates at the bottom. NameM,efConstructionandefSearch. - "How do you fit a billion vectors?" Do the arithmetic (1B × 768 × 4 = 3 TB), then shard, quantize (PQ or int8), keep full vectors on SSD for rescoring, or use DiskANN.
- "Recall dropped after we added a tenant filter. Why?" Post-filtering over a graph index; fix it with filter-aware search, pre-filtering for small tenants, or per-tenant partitions.
- "How do you know your index is good enough?" Recall@k against exact search on sampled queries, at your latency budget, measured on filtered queries too, plus end-to-end retrieval metrics on labeled queries.
- "What happens when you change the embedding model?" A new collection, dual-writes, a backfill, shadow evaluation, then an alias swap.
Summary
A vector database stores embeddings with metadata and finds the nearest ones to a query without comparing against all of them. Flat search is exact and fine below a few million vectors. HNSW walks a layered neighbor graph and is the fast, high-recall default when the vectors fit in RAM. IVF scans only the clusters near the query, and product quantization shrinks vectors 10-30x so billions fit, with full-precision rescoring to recover recall. Every index has a dial between recall and latency, and you tune it by measuring recall@k against exact search.
The database around the index handles the hard production parts: filtering during the search rather than after it, segment-based writes with tombstones and compaction, sharding for size and replicas for QPS. Design the schema around your filters and partition by tenant when every query filters by tenant. And pick the simplest option that fits the numbers: pgvector or your existing search engine often does the job, and a dedicated engine earns its place at hundreds of millions of vectors or heavy filtered traffic.