Course contents

16. AI System Design Lesson 3 of 10

Vector Database Architecture

How vector databases find nearest neighbours fast: HNSW, the recall vs latency dial, filtered search, replicas for read scaling, and sharding for size.

16 minAdvanced8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Exact search compares the query with every vector: accurate, O(N), too slow at scale.
  • HNSW walks a layered neighbour graph and touches a tiny fraction of the vectors.
  • Recall and latency are one dial (efSearch); measure recall on your own data.
  • Filter during the search; post-filtering silently returns too few results.
  • Replicate for throughput and availability, shard or quantise for size.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A vector database stores vectors (with an id, the source text and metadata) and answers similarity queries: given a query vector, return the k stored vectors closest to it by cosine similarity, dot product or Euclidean distance. Under the hood it is an approximate nearest-neighbour (ANN) index plus the usual database concerns: persistence, filtering, replication, sharding and writes.

Why it exists

Semantic search and retrieval-augmented generation reduce text to vectors and look for close ones. Comparing a query with every stored vector is exact but linear in the data: 10 million 768-dimensional vectors cost billions of multiply-adds per query. ANN indexes make that sub-linear, at the price of occasionally missing a true neighbour. A vector database packages such indexes so applications do not have to.

How it works

HNSW. Hierarchical navigable small world graphs are the most widely used ANN index. Every vector is a node linked to up to M close neighbours. Higher layers contain exponentially fewer nodes and act as long-distance shortcuts. A search starts at an entry point in the top layer, greedily moves to whichever neighbour is closest to the query, drops a layer when it cannot improve, and at the bottom layer keeps a candidate list of size efSearch to collect the final top-k. Inserts walk the graph the same way to find neighbours to link.

Recall. Quality is measured as recall@k against exact search on a sample of real queries. Knobs: efSearch at query time (more candidates, better recall, more CPU), M and efConstruction at build time (more links, better recall, more memory and slower inserts). Recall depends on the data, so measure it; typical targets are in the 0.9–0.99 range.

Other index types. IVF clusters vectors and searches only the nearest clusters (nprobe). DiskANN-style indexes keep the graph on SSD for indexes bigger than RAM. Flat (exact) indexes are fine for small collections or heavily filtered subsets.

Quantisation. Store vectors in fewer bits: float16, int8 (a quarter of float32), binary (a thirty-second) or product quantisation. Memory and bandwidth drop sharply; recall drops a little, often recovered by re-scoring the top candidates with full-precision vectors.

Filtering. Applying a metadata filter after the ANN search (post-filtering) returns too few results when the filter is selective. Filtered search applies the condition during traversal, and planners switch to an exact scan of the matching subset when it is small. pgvector added iterative index scans (0.8) for the same reason.

Replicas and shards. ANN queries are CPU-bound and want the index in memory. Replicas hold full copies and multiply read throughput. Shards split the collection; a query fans out to every shard in parallel, each returns its local top-k, and a coordinator merges them, so latency follows the slowest shard.

When to use it

  • Semantic search and RAG over more vectors than an in-process index handles comfortably.
  • When you need filtering, multi-tenancy, replication and operational tooling around ANN search.
  • Recommendations and deduplication by similarity (near-duplicate detection, “more like this”).

When not to

  • Thousands to a few million vectors with modest traffic: an extension or vector type in the database you already run (pgvector in PostgreSQL, vector support in SQL Server 2025, Azure SQL, MongoDB, Redis or your search engine) avoids a new system and keeps data and permissions in one place.
  • Exact matches or keyword queries: a B-tree or full-text index does it better.
  • When results must be exact and complete (compliance search): ANN can miss items by design.

Trade-offs

Choice You gain You pay
Higher efSearch Better recall More CPU per query, higher latency
Higher M / efConstruction Better recall ceiling More memory, slower inserts and builds
Quantisation Several-fold less memory Some recall, unless you re-score
Replicas Read throughput, availability Full index in RAM on every replica; writes applied everywhere
Shards Indexes bigger than one machine Fan-out on every query; tail latency of the slowest shard
Dedicated vector DB Scale, features, performance Another system to run and keep in sync

Alternatives

  • Keyword search (BM25) alone, or combined with vectors (hybrid search): strong for exact terms, codes and names that embeddings blur.
  • In-process libraries (FAISS, hnswlib and similar): fastest for a single service with a static index; you handle persistence and scaling.
  • Managed search services with vector fields: one system for keyword, vector and filtered queries.

Failure modes

  • Silent recall loss: a parameter change, a new embedding model or data drift lowers recall; nothing errors, answers just get worse. Monitor recall on a fixed query set.
  • Selective filters return nothing: post-filtering or a planner that guesses wrong.
  • Memory pressure: the index outgrows RAM and pages to disk; latency jumps by orders of magnitude.
  • Hot shard: one shard is slower (more data, noisy neighbour, compaction) and every fan-out query waits for it.
  • Delete debt: deletes as tombstones bloat the graph and slow queries until compaction or a rebuild.
  • Replica lag: a vector written a moment ago is visible on one replica and not another.

In production

Track P50/P95 query latency, queries per second per node, memory headroom and, crucially, recall on an evaluation set after every index or model change. Size capacity per node as cores ÷ CPU time per query at your efSearch, and memory as vectors × dimensions × bytes per dimension plus graph overhead. Put tenant and permission fields on every vector and filter inside the search. Plan index rebuilds (new model, new parameters) as blue/green migrations with an alias switch.

Common misconceptions

  • "ANN is just a faster exact search." It returns approximately the nearest neighbours; recall below 1 is the deal.
  • "Replicas let the index use less memory." Each replica is a full copy; shards or quantisation reduce memory.
  • "Filters are free." Selective filters change which algorithm is efficient and can wreck recall if applied afterwards.
  • "We need a vector database for RAG." Often a vector column in the database you already run is enough.
  • "Cosine similarity score 0.8 means relevant." Scores are only comparable within one model and index; use rank and evaluation, not fixed thresholds across models.

Interview angle

Expect to explain ANN vs exact search, sketch HNSW, and discuss the recall/latency/memory triangle. Estimate memory (count × dimensions × 4 bytes) and decide between replicas, shards and quantisation from it. Explain filtered search for multi-tenancy and permissions, and how you would measure recall. Point out when an existing database with vector support is the simpler choice.

Model assumptions

The simulation is a simplified model, not a benchmark. A vector database node is a server with 4 query slots (cores) and room for 16 waiting queries. Query work is lognormal (cv 0.25): ~400 ms for an exact scan of the illustrative 10-million-vector index, ~8 ms with HNSW at efSearch 40, ~20 ms at efSearch 200. Recall figures are illustrative annotations; the engine does not compute recall. Queries arrive randomly (Poisson). Replicas sit behind a load balancer with health checks. The HNSW descent, metadata filtering and shard fan-out are scripted illustrations, not simulated. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Compare the query with everything

    A vector database answers one question: which stored vectors are closest to this query vector (by cosine similarity or dot product)? The exact way is to compare the query with every vector. For 10 million 768-dimensional vectors that is about 7.7 billion multiply-adds per query.

    In this model that costs ~400 ms per query on a node with 4 cores, so at 8 queries per second the node is busy most of the time and P50 is above 400 ms. Exact search is perfectly accurate, and its cost grows linearly with the data.

    Scene: The Search API sends 8 queries per second to one vector database that compares each query with all 10 million vectors. The node is busy most of the time and queries take over 400 ms.

    Key idea: Exact nearest-neighbour search is O(N) per query: accurate, but too slow and too expensive at scale.

  2. 2. An index that skips most of the data

    Approximate nearest-neighbour (ANN) indexes trade a little accuracy for a lot of speed. The most common one, HNSW (hierarchical navigable small world), links each vector to its close neighbours in a graph with several layers: the top layers are sparse “highways”, the bottom layer contains every vector.

    A search enters at the top, greedily hops towards the query, drops a layer, and repeats (scripted packets show the descent). It visits a few thousand vectors instead of ten million. Queries now take ~8 ms of work and the node is nearly idle at the same traffic.

    Scene: An HNSW index is added. Scripted packets show a search entering at the sparse top layer and descending to the bottom layer. Queries now take a few milliseconds of work and the node is almost idle.

    Key idea: HNSW finds near neighbours by walking a layered graph, touching a tiny fraction of the vectors.

  3. 3. Approximate means it can miss

    HNSW can miss a true nearest neighbour when the greedy walk takes a wrong turn. Quality is measured as recall@k: of the true top-10, how many did the index return? The main query-time knob is the size of the candidate list (efSearch in most engines). Bigger explores more of the graph.

    Raising efSearch from 40 to 200 lifts recall from roughly 0.95 to 0.99 here (illustrative; it depends on data and build settings) and costs ~2.5× the work per query: P50 rises. Build-time settings (M, efConstruction) trade memory and indexing time the same way.

    Scene: efSearch is raised from 40 to 200. Each query does about two and a half times more work, so median latency rises; recall improves.

    Key idea: Recall and latency are one dial: more candidates, better recall, slower queries. Measure recall on your data.

  4. 4. Search only what the user may see

    Real queries come with conditions: tenant = acme, language = de, documents this user may read. Applying the filter after the ANN search (post-filtering) is simple but breaks with selective filters: the top 10 neighbours might include only one Acme document.

    The scripted packets show both. First post-filtering: 10 hits come back and 9 are thrown away. Then filtered search: the engine looks up which ids match the filter and the graph walk only accepts those, so 10 valid results come back. Most current vector databases (and pgvector with iterative scans) support filtered traversal; very selective filters may fall back to an exact scan of the matching subset.

    Scene: Scripted: a post-filtered search returns ten neighbours of which only one matches the tenant filter. Then a filtered search first resolves the allowed ids in the metadata index and walks the graph only through them, returning ten valid results.

    Key idea: Filter during the search, not after it, or selective filters silently return too few results.

  5. 5. One node, 250 queries per second

    The search feature is a success: 250 queries per second. One node with 4 cores at ~20 ms per query can do about 200. It saturates, queries wait, and once its waiting line is full it rejects them.

    ANN search is CPU-bound and needs the index in memory. A bigger machine buys some time; the usual next step is more copies of the index.

    Scene: At 250 queries per second the single vector database node is saturated, its queue is full and some queries are rejected.

    Key idea: Vector search is CPU-bound per query: capacity ≈ cores ÷ work per query.

  6. 6. Replicas scale reads

    Three replicas, each holding the full index, sit behind a load balancer. Each takes a third of the 250 queries per second and runs about 40% busy; the rejections stop and P95 falls back to a few tens of milliseconds.

    Replicas multiply read throughput and survive a node failure, but every replica needs the whole index in RAM, and every write must be applied to every replica (so new vectors become searchable a little later on some of them).

    Scene: A load balancer spreads 250 queries per second over three replicas of the index. Each is about 40% busy and no queries fail.

    Key idea: Replicas add query throughput and availability; they do not make the index fit in less memory.

  7. 7. When the index outgrows a machine

    Now the corpus grows to 100 million 1,024-dimensional vectors: about 410 GB of raw float32 vectors before graph links. HNSW performs best in memory, so the index is split into shards, each on its own machine (and each shard replicated as before).

    A query must go to every shard in parallel; each returns its local top-k and a coordinator merges them (scripted packets). Latency is set by the slowest shard, so one hot or slow shard drags every query. Quantisation (int8, binary, product quantisation) is the other lever: it shrinks vectors several-fold at some recall cost, often recovered by re-scoring the top candidates with full vectors.

    Scene: Scripted: the query coordinator sends a query to three shards at once. Shards A and B answer quickly, the hot shard C much later; the coordinator answers only after merging all three.

    Key idea: Shard for size, replicate for throughput. A sharded query waits for its slowest shard.

  8. 8. Choosing and running a vector store

    The decisions: index type and its knobs (recall vs latency vs memory), filtering done inside the search, replicas for read throughput and availability, shards and quantisation for size. Writes matter too: inserts are slower than queries, deletes are often tombstones cleaned up later, and freshly written vectors may not be visible on every replica at once.

    You may not need a separate product: PostgreSQL with pgvector, or the vector support in a search engine or document database you already run, often covers millions of vectors. Dedicated vector databases earn their place with very large indexes, heavy filtered traffic or strict latency targets.

    Scene: Three replicas behind a load balancer serve 250 queries per second; the sharded layout is shown alongside.

    Key idea: Pick the index for your recall target, filter inside the search, replicate for reads, shard or quantise for size.