AI ENGINEERING · RETRIEVAL AND RAG IN DEPTH · INDEXING · 22 OF 35

Vector Databases and HNSW Explained

What a vector database stores and how a top-k query works, why exact search costs O(n·d), and how approximate indexes fix it: HNSW layered graphs with a worked walk and its M and ef knobs, IVF and product quantization, recall at k, filtering before or after search for access control, Postgres versus a dedicated store, updates and re-indexing, and memory sizing.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
1 / 19

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • id + vector + metadata
  • exact is O(n
  • d)
  • HNSW layers + greedy walk
  • tune ef
  • filter inside
  • size the RAM

Notes

What it stores

A vector database stores records. Each record has an id, the embedding vector, some metadata and usually the chunk text itself. The vector comes from the embedding model, say one thousand and twenty four numbers. The metadata holds things you will filter on, like the tenant, the source document and the date. Keeping the text alongside means one lookup gives you everything for the prompt.

One record
id:       "policy-7#3"
vector:   [0.12, -0.40, 0.03, ...]
          1024 float32 numbers
metadata: { tenant: "acme",
            doc: "refund-policy",
            updated: "2026-05-01" }
text:     "Refunds are allowed
           within 30 days..."

The query

The query side is short. Embed the user's question with the same model you used for the chunks, then ask the database for the k nearest vectors. Nearest means cosine similarity, dot product or straight line distance. A useful fact: if every vector is normalised to length one, all three give exactly the same ranking. So most systems normalise once at write time and use the cheap dot product.

Nearest neighbours
  • find the k records whose
  • vectors are closest to q
  • cosine: angle between them
  • dot product: q · v
  • L2: straight-line distance
  • normalise every vector to length 1 and all three give
  • the same ranking

Exact search cost

The simplest search compares the query with every stored vector. That costs n times d multiply adds, so O of n times d. Take one million vectors of one thousand and twenty four dimensions. That is about a billion multiply adds and four gigabytes of data to read for every single query. That is a few hundred milliseconds. Under about a hundred thousand vectors it is fine. At millions, with real traffic, it is not.

Brute force, worked
n = 1,000,000 vectors
d = 1024 dimensions
work = n × d ≈ 1 billion multiply-adds
data = n × d × 4 bytes ≈ 4 GB read

at ~10-20 GB/s memory bandwidth
  ≈ 0.2-0.4 s per query, one machine

100k vectors: ~20-40 ms, often fine
100M vectors: hopeless

The idea

Here is the idea. We do not need the exact top ten. Embeddings are already a fuzzy measure of meaning, so missing the tenth best chunk now and then barely matters. Approximate nearest neighbour indexes, A N N for short, build a structure ahead of time that lets a query touch only a tiny fraction of the vectors. You typically get ninety five to ninety nine percent of the true results in a few milliseconds.

Approximate nearest neighbour
  • exact: always the true top k, touches every vector
  • ANN: an index that touches a tiny fraction of vectors and returns almost the true top k
  • ~95-99% of the true results
  • in a few milliseconds

HNSW layers

The most popular index is H N S W, hierarchical navigable small world. Picture a graph where every vector links to its nearest neighbours. Searching means hopping to whichever neighbour is closer to the query. A flat graph needs many hops, so H N S W stacks layers. The bottom layer holds every vector. Each layer up keeps only about one in M of the nodes below. Top layers make long jumps, the bottom makes fine steps, much like a skip list.

Hierarchical small world
  • layer 0: every vector, each linked to ~M near neighbours
  • higher layers: a random few ~1 in M reach each layer up
  • M = 16, 1M vectors: L1 ~62,000 L2 ~3,900 L3 ~240 L4 ~15 L5 ~1
  • top = long jumps, bottom = fine steps. Like a skip list

A tiny walk

Let us walk it. Start at entry point A on the top layer, distance nine. Its neighbour F is closer, five, so hop there. Nothing near F is closer, so drop a layer, starting from F. There, H is at distance two. Drop again. On the bottom layer, G is at distance one. Here the search widens into a beam of size e f. It returns G and H, after visiting a handful of nodes instead of a million.

Walk to query q
distance to q in brackets
L2: start A(9) → F(5)   no closer, drop
L1: F(5) → H(2)         no closer, drop
L0: H(2) → G(1)         best so far
    beam of ef = 4 explores
    neighbours: keeps G, H, I, J

answer, k = 2:  G(1), H(2)
visited ~8 nodes, not all of them

The knobs

H N S W has three knobs. M is how many links each node keeps. Around sixteen is common. More links raise recall but cost memory. E f construction is the beam width used while building the graph. Bigger means a better graph and a slower build. E f search is the beam width at query time, and it must be at least k. It is the easy dial: more recall, more latency, and it can change per query without a rebuild.

HNSW parameters
  • M: links per node ~16 (8-64). More = better recall, more memory
  • ef_construction: beam at build ~64-400. More = better graph, slower build
  • ef_search: beam at query ~40-200, must be ≥ k more = better recall, slower
  • tune ef_search per query

IVF and PQ

Two other ideas. I V F, the inverted file, groups vectors into clusters with k means. A query checks the nearest few clusters, say ten out of a thousand, and scans only those, about one percent of the data. Product quantization shrinks vectors. Split each one into sixty four pieces and replace each piece with a one byte code. Four thousand bytes become sixty four. Distances get rougher, so you re score the best few hundred with the full vectors.

Two other tools
  • IVF: k-means into ~1,000 clusters; probe the 10 nearest; scan ~1% of data
  • PQ: split 1024 dims into 64 pieces of 16; store each as a 1-byte code 4,096 bytes → 64 bytes
  • then re-score the best few
  • hundred with full vectors

Recall at k

How do you know the index is good enough? Recall at k. Take a sample of real queries, compute the true top ten with brute force, then run the index. If it returns nine of those ten, recall at ten is zero point nine. Average over about a thousand queries. Then raise e f search and plot recall against latency, and pick the point where extra latency stops buying recall. Note this measures the index, not whether the chunks are relevant.

Measuring an ANN index
true top 10 (brute force):
  {a b c d e f g h i j}
index returned:
  {a b c d e f g h i x}
recall@10 = 9 / 10 = 0.9

average over ~1,000 real queries
plot recall vs latency as you
raise ef_search, pick the knee

Filter before or after

Real queries come with conditions, like this tenant or this year. You can filter after the search or before it. Say a tenant owns one percent of a million chunks. Search globally for the top ten, then drop other tenants, and you expect about zero point one survivors. Usually nothing. Filtering first, during the walk, keeps k results. And when the allowed set is small, like ten thousand vectors, plain brute force over it is fast and exact.

One tenant, 1% of 1M chunks
  • post-filter: global top 10, then drop other tenants expect ~0.1 survivors
  • pre-filter: search only allowed vectors. Filtered graph walk, or brute force over the 10,000 allowed
  • small subsets: brute force
  • is fast and exact

Access control

Filtering is also your security boundary. Retrieved text goes into the prompt, so a chunk the user may not see is a leak. Store permission fields on every record. Build the filter on the server from the signed in user, never from anything the model wrote, and apply it inside the search on every call. When access is revoked, update the metadata quickly.

Do not leak chunks
  • store ACL fields with each record: tenant, groups
  • build the filter from the signed-in user, server side
  • apply it inside the search, every time
  • big tenants: a partition or namespace each deleted access: re-sync fast

Postgres or dedicated

Where should vectors live? Often in the database you already run. Postgres with a vector extension such as P G vector gives you H N S W and I V F indexes next to your normal tables. You get SQL filters, joins, transactions and one backup story, up to tens of millions of vectors. A dedicated vector database earns its place at larger scale: sharding across machines, built in quantization and hybrid search, and very high query rates.

Where to keep vectors
  • Postgres + vector extension (pgvector): one system, SQL joins and filters, transactions, same backups fine to ~tens of millions
  • dedicated vector database: sharding, quantization, built-in hybrid search, high query rates, billions

Updates and deletes

Data changes. Inserting into H N S W is cheap: add a node and link it to neighbours. An update is a delete plus an insert. Deletes are usually tombstones, marked as gone but still in the graph, so quality slowly drops and you compact or rebuild now and then. I V F clusters go stale as data drifts. And a new embedding model means re-embedding everything into a fresh index, then switching reads over.

Keeping the index healthy
  • insert: add a node, link it to neighbours. Cheap
  • update: delete + insert
  • delete: usually a tombstone; the graph degrades slowly, so compact or rebuild
  • IVF: re-train clusters as data drifts
  • new embedding model: re-embed all, build new index, swap

Memory sizing

Ten million chunks at one thousand and twenty four dimensions, stored as four byte floats, is about forty one gigabytes. The graph adds around thirty two links per node at four bytes each, roughly 1.3 gigabytes. H N S W wants the vectors and the graph in memory to stay fast. Storing vectors as one byte integers cuts them by four times, binary codes by thirty two, at some cost in recall.

10M chunks, 1024 dims
float32: 10M × 1024 × 4 ≈ 41 GB
graph:   10M × 32 links × 4 B
         (M = 16) ≈ 1.3 GB
text + metadata: often ~10-20 GB

int8 vectors:   ≈ 10 GB  (4× less)
binary vectors: ≈ 1.3 GB (32× less)

HNSW wants vectors and graph
in RAM to stay fast

Numbers worth knowing

Numbers worth knowing. Brute force is fine up to about a hundred thousand vectors. An H N S W query over a million vectors takes roughly one to ten milliseconds. Aim for recall at ten between zero point nine five and zero point nine nine. M around sixteen, e f search between forty and two hundred. Each vector costs four bytes per dimension, so a million at one thousand and twenty four dimensions is about four gigabytes.

Ballparks
brute force fine up to   ~100k vectors
HNSW query, 1M vectors   ~1-10 ms
typical recall@10 target ~0.95-0.99
M                        ~16 (8-64)
ef_search                ~40-200
float32 vector           4 bytes × d
1M × 1024 float32         ≈ 4 GB
Postgres extension       ~tens of M
build time, 1M vectors   ~minutes

Common mistakes

A few mistakes cause most problems. Embedding the query and the chunks with different models or versions, which quietly ruins every search. Mixing normalised and unnormalised vectors. Post filtering with a small k and wondering why results vanish. Letting anything the model writes decide the permission filter. Never measuring recall. And forgetting that the whole index must fit in memory.

Avoid these
  • query and chunks embedded with different models
  • cosine index, unnormalised vectors
  • post-filtering with a small k
  • ACL filter built by the LLM
  • never measuring recall
  • ef_search below k
  • forgetting the RAM bill

Say it like this

How to say it. We store ten million chunks with normalised one thousand and twenty four dimension embeddings in Postgres, using an H N S W index with M of sixteen. The tenant filter comes from the signed in session and is applied inside the search. We tuned e f search to one hundred, which gave recall at ten of zero point nine seven at about eight milliseconds. It needs about forty five gigabytes of memory.

In the interview
  • "Ten million chunks, 1024-dim, normalised, in Postgres with an HNSW index, M of 16. The tenant filter is applied inside the search from the session, not the model. We tuned ef_search to 100 for recall@10 of 0.97 at ~8 ms. About 45 GB of RAM."

Interview questions

Q1What does a vector database store and what query does it answer?

Records of an id, an embedding vector, metadata for filtering and usually the source text. Its core query is: given a query vector and an optional filter, return the k records whose vectors are nearest by cosine, dot product or Euclidean distance.

Q2Why not just compare the query with every vector?

Exact search costs O(n·d) per query. For 1M vectors of 1024 dimensions that is about a billion multiply-adds and 4 GB read per query, hundreds of milliseconds. It is fine below roughly 100k vectors or on small filtered subsets, but not at millions with real traffic.

Q3How does HNSW search work?

HNSW is a stack of proximity graphs: the bottom layer holds every vector and each higher layer a random ~1/M subset. A query starts at an entry point on the top layer, greedily hops to closer neighbours, drops a layer when none is closer, and on the bottom layer runs a beam search of width ef_search to return the top k.

Q4What do M, ef_construction and ef_search control?

M is the number of links per node: higher raises recall and memory. ef_construction is the candidate beam while building: higher gives a better graph but slower builds. ef_search is the beam at query time, at least k: higher raises recall and latency, and can be tuned per query without a rebuild.

Q5How do you measure the quality of an ANN index?

Recall at k: for a sample of real queries, compute the true top k with brute force and measure what fraction the index returns. Plot recall against latency while varying ef_search and pick the knee, often recall@10 around 0.95 to 0.99.

Q6Should metadata filters run before or after the vector search?

Before or during. Post-filtering a global top k can leave almost nothing when the filter is selective, for example a tenant with 1 percent of the data. Filter inside the search, or brute-force the small allowed subset; for access control, build the filter from the authenticated user, never from model output.

Q7When would you use Postgres with a vector extension instead of a dedicated vector database?

When you already run Postgres and have up to roughly tens of millions of vectors: you get SQL filters, joins, transactions and one backup story. Move to a dedicated store for billions of vectors, sharding, heavy quantization or very high query rates.

Q8How much memory does a vector index need?

Roughly vectors × dimensions × bytes per number, plus the graph. 10M vectors of 1024 float32 dimensions is about 41 GB, plus around 1.3 GB of HNSW links at M=16. int8 or binary quantization cuts the vector part by 4× or 32×.