quanglee/ field notes
← field notes
code20 min6 live figures#search#vectors#algorithms#infra

How HNSW works, and why constant writes are hard on it

HNSW is the default vector index in almost every database. This post explains the graph and why a search touches so few vectors, then why building it costs so much, what that does to databases that take writes all day, and how Elasticsearch, Qdrant, Milvus, Weaviate, pgvector, ClickHouse and newer designs deal with it.



  1. brute force
  2. small worlds
  3. the layers
  4. how many distances a search computes
  5. the neighbour rule
  6. the layers may not matter
  7. an insert is a search
  8. the variants
  9. writes that keep coming
  10. build times
  11. research on fresh data
  12. where it stands

Nearly every vector database ships HNSW as its default index: Elasticsearch, OpenSearch, Qdrant, Milvus, Weaviate, pgvector, Redis, Vespa and ClickHouse all have it. It answers a nearest-neighbour query over millions of vectors by looking at a few hundred of them. Adding one vector to the graph costs more than a query: a search plus some rewiring, and a database that receives new vectors every second spends a lot of CPU on that, sometimes enough to slow its searches down. Elasticsearch is known for it, and the problem turns up in most other systems too.

This post explains the graph first, then the write problem, then what each database and the recent research do about it.

brute force

A query vector qq and a table of NN vectors. The exact answer needs the distance from qq to every row: NN distance computations, each one dd multiply-adds. For a million 768-dimension vectors that is 768 million multiply-adds per query. It’s simple and it’s exact, and it gets slow in proportion to NN.

An approximate index trades a little recall (the share of the true nearest neighbours it finds) for doing far fewer distance computations.

small worlds

HNSW grew out of NSW, the navigable small world graph that Yury Malkov and three co-authors published in 20141. Every vector is a node, linked to some of its near neighbours. To search, start at any node, compute the distance from the query to each of its neighbours, move to the closest one, and repeat until no neighbour is closer than where you stand. That’s greedy routing.

Inserting into NSW is the same move: search for the new vector’s nearest neighbours and link it to them. Early nodes were inserted when the graph was sparse, so their links span long distances, and later nodes add short local links. The long links let a search cross the space in a few hops; the short ones let it finish precisely.

Plain NSW is slower than it needs to be. The long links pile up on a few early hub nodes whose number of links grows with NN, and a search that passes through a hub has to compute the distance to all its neighbours. Malkov and Yashunin measured the total work at polylogarithmic in NN2.

the layers

HNSW, from Malkov and Yashunin in 2016 (the journal version came out in 2018), sorts the links by length into layers2. Every vector is on layer 0. Each vector also gets a random top level, ⌊−ln⁡(u)⋅mL⌋\lfloor -\ln(u) \cdot m_L \rfloor with uu uniform in (0, 1), and it appears on every layer up to that level. With mL=1/ln⁡Mm_L = 1/\ln M, each layer holds about 1/M1/M of the layer below, so with M=16M = 16 a million vectors make about five layers. It’s a skip list made of graphs.

A search starts at the single entry point on the top layer, routes greedily to the node closest to the query, drops to the layer below at that node and routes again. On layer 0 it switches from pure greedy to a small beam search: it keeps the best ef candidates found so far and stops when none of their unexplored neighbours can improve the list. A bigger ef (ef_search in most databases) means better recall and a slower query.

Three panels show layer 2 (7 points), layer 1 (17 points) and layer 0 (all 60). The search starts at the top-layer point farthest from the query and makes one hop towards it. On layer 1 none of that point's neighbours is closer, so it drops straight down. On layer 0 it makes two hops and reaches the true nearest neighbour. It computed 15 distances, against 60 for brute force.

fig 1Greedy routing through three layers. Highlighted points are the ones whose distance the search computed. The graph links each point to its nearest neighbours in the layer (the small top layer is fully linked), and layer 0 uses plain greedy routing here, where HNSW keeps a beam of ef candidates.Sixty random points, levels drawn with M = 4.

Three parameters control the graph:

The links take memory on top of the vectors: the paper puts it at 60 to 450 bytes per vector for M between 6 and 482.

how many distances a search computes

The paper proves O(log⁡N)O(\log N) search only for low-dimensional data that has an exact Delaunay graph, and it notes that on 200 million SIFT vectors the measured scaling “deviates from the pure logarithm”2. I couldn’t find a published table of distance computations per query against NN, so I wrote a small HNSW in JavaScript that follows the paper’s algorithms and counted3. The data is 32-dimensional, drawn from 1,000 overlapping Gaussian clusters, with M = 16, ef_construction = 100 and ef_search = 64.

A log-log chart of distance computations against the number of vectors, from 1,000 to 300,000. Brute force is a straight line equal to N. An HNSW query stays between about 600 and 1,100 distance computations at every size, with recall@10 above 0.99. An HNSW insert, averaged over each step of growth, costs between 700 and 2,300 distance computations.

fig 2Work per query and per insert as the index grows. Each insert point is the mean over the inserts that grew the index to that size. Hover a point for the exact count and the recall.My measurement with scripts/hnsw-count.mjs: 32-d clustered data, 200 queries per size, recall@10 against brute force.

At 100,000 vectors a query computed 727 distances and found 99.8% of the true top 10. Brute force computed 100,000. Across sizes the count moves between 600 and 1,100 with no upward trend. The Faiss wiki has the same picture in wall-clock time on SIFT1M: HNSW answers in 0.033 ms at 0.978 recall@1 with efSearch = 64, and an IVF index needs 0.344 ms to reach 0.9864.

the neighbour rule

Linking each new node to its M nearest neighbours works badly on clustered data. All M links land inside the node’s own cluster and nothing points out of it. HNSW’s insert uses a heuristic instead (Algorithm 4 in the paper)2. It goes through the candidates nearest first and keeps one only if it is closer to the new node than to every neighbour already kept. A second candidate in the same direction as a kept one gets skipped, so the links spread out in different directions and some of them reach the next cluster.

Every one of those checks is another distance computation, which is part of why inserts cost more than queries in fig 2.

the layers may not matter

In December 2024 Blaise Munyampirwa, Vihan Lakshman and Benjamin Coleman tested a flat version of HNSW, layer 0 alone, against the full hierarchy on 13 datasets up to 100 million vectors5. They found “no consistent and discernable gap” in median or p99 latency at the same recall, and conclude that the hierarchy speeds up search only below about 32 dimensions. The flat graph used up to 39% less peak memory while building on the 100-million-vector datasets.

Their explanation is a hub highway: in high dimensions a small set of nodes (1 to 5% of them) end up linked mostly to each other, and searches use them heavily in their first 5 to 10% of steps. The hubs do the job the upper layers were designed for. Embeddings have hundreds of dimensions, so on embedding data the upper layers add memory without making search faster.

Adding a vector runs the whole search descent with ef_construction as the beam (100 to 500 is usual, against 40 to 100 for ef_search). On each layer the new node gets linked, and every neighbour whose link list is now over the cap runs the neighbour rule again to drop a link.

A new point appears in the middle of a graph. A greedy search walks three hops towards it from the far side, computing 10 distances. The new point links to the three nearest points that search found; the true third-nearest point was never reached. Two of those neighbours now have five links, one over the cap of four, and each drops its longest link: one to another node, the other to the new point. Links in HNSW are directed, so the node at the other end keeps its side and both dropped links stay as one-way links, drawn dashed. The pruning computes 10 more distances.

fig 3The three parts of an insert. The search here is greedy and the new point links to the nearest three it found, which misses the true third-nearest point; real HNSW searches with a beam of ef_construction candidates, which usually finds it, and picks links with the neighbour rule. A dashed link is one-way: one end dropped it and the other end still keeps it.Thirty-four random points.

In my measurement inserts averaged between 700 and 2,300 distances each while the index grew to 300,000 vectors, 1.1 to 2.7 times as many as a query at the same size. Building the 100,000-vector index computed about 200 million distances in total, as much work as 2,000 brute-force queries over the same data. Building is slow at real scale too:

A brute-force query needs no preparation, so under frequent writes an index has to answer many queries before its build cost pays off.

deletes

HNSW has no real delete. hnswlib marks a deleted node so it’s left out of results while it stays in the graph to keep routes working8. Removing nodes for real breaks routes. Xiao and co-authors deleted and reinserted 5% of SIFT1M per round: after about 3,000 rounds, 3 to 4% of the points could no longer be reached from the entry point and recall had dropped about 3%9. Databases clean up marked nodes in background jobs that rewire their neighbours, and those jobs are expensive.

the variants

indexyearideaheadline result
NSG102017one navigating entry point, pruned graphdeployed in Taobao search
DiskANN (Vamana)112019flat graph with relaxed pruning, kept on SSD, compressed vectors in RAM1 billion SIFT vectors on a 64 GB machine, over 5,000 QPS at 95% recall@1
FreshDiskANN122021small in-memory graph for new data, merged into the SSD graph in batchesthousands of inserts and deletes per second at over 95% recall
SPANN132021clusters: centroids in RAM, lists of vectors on SSD2× faster than DiskANN at 90% recall, same memory
SPFresh142023SPANN with clusters split and reassigned in place1% of the DRAM and under 10% of the cores of a global rebuild
ACORN152024HNSW that checks filters during the walk2 to 1,000× more throughput at fixed recall on filtered queries
CAGRA162024graph built and searched on GPUbuilds 2.2 to 27× faster than CPU HNSW
RaBitQ172024one bit per dimension with an error bound32× smaller vectors; Elastic’s BBQ derives from it
Jasper182026GPU Vamana with lock-free streaming insertsabout 7× faster build than CAGRA
LSM-VEC192025graph stored in an LSM tree on diskup to 15× fewer bytes written per insert than FreshDiskANN and SPFresh

The graph indexes (NSG, DiskANN, CAGRA) are all close relatives of HNSW with one flat layer. The others replace the graph with clusters, an IVF index: assign each vector to its nearest centroid, then search only the few closest clusters. IVF searches slower than a graph at very high recall, but adding a vector to IVF means one comparison against the centroids and an append, so inserts cost far less.

writes that keep coming

Most databases don’t keep one big graph. Lucene (inside Elasticsearch and OpenSearch), Qdrant, Milvus and ClickHouse write data into immutable segments and merge small segments into bigger ones in the background. Each segment has its own HNSW graph, and a merge needs a graph for the new segment. The simple way is to build it again from all the vectors, so a vector that goes through three rounds of merges gets inserted into a graph four times.

Lines show graph insertions per vector written as a million vectors arrive in batches of a thousand. A single mutable graph stays at one. Rebuilding on every merge climbs in steps and reaches four at a million, when every vector has been through three rounds of merges. Reusing the largest input graph reaches 3.7, and joining graphs, at about 30% less work than reuse, reaches 2.9. All three keep climbing with each further round.

fig 4Write amplification of the graph under segment merges. Merges of equal-size segments gain little from reusing the largest graph, because every input is the same size.My simulation: one segment per thousand vectors, merges of ten same-size segments; join is modelled as 30% less work than reuse, as Lucene measured it. Lucene's real merge policy picks segments by size and caps them at 5 GB.

Three things go wrong under constant writes:

  1. The CPU spent on graph building competes with searches on the same nodes.
  2. New data waits for its graph. A database either searches it by brute force, which is slow, or hides it, which means the newest writes are missing from results.
  3. Many small segments each have their own graph, and a query has to search all of them.

elasticsearch

Every refresh (once per second by default) writes a new segment with a new graph, and merges combine about ten segments at a time. Elastic says it plainly: “Merging segments requires recomputing HNSW graphs, incurring index-time overhead”20. An update to any field of a document reindexes the whole document, vector included21. A user with 90 million 768-dimension vectors reported that heavy indexing pushed the graphs out of memory and kNN searches turned into “insanely high disk IO”; Elastic’s advice was to build on separate nodes and switch an alias22.

The fixes so far, in order:

opensearch

OpenSearch 3.1 made remote GPU index builds generally available. Large segments are sent to a GPU service at flush and merge time, and one benchmark went from 273.8 minutes on CPU to 29.1 on GPU26. The jVector plugin (3.5 and later) merges graphs incrementally “with no full graph rebuilds” and builds in parallel, 6.5× faster than one thread on 100,000 vectors27.

qdrant

Qdrant indexes a segment only after its unindexed vectors pass indexing_threshold; until then it scans them. Its docs measure what that does on 1.76 million 1,024-dimension vectors28:

Median search latency on a log scale. Fully indexed: 4.3 ms. While the optimizer indexes new data with prevent_unoptimized on, which hides unindexed points: 10.2 ms, p95 81 ms. With indexing turned off: 256.6 ms. While the optimizer indexes new data in the default mode: 780 ms, p95 2 seconds.

fig 5The same collection, four states. The default mode searches new data by brute force until it's indexed; prevent_unoptimized keeps it out of results instead.Qdrant docs, predictable search latency (2026).

Search was 180 times slower while the optimizer caught up (780 ms against 4.3 ms). The prevent_unoptimized option (experimental since 1.17.1) brings that down to 10.2 ms by leaving the newest points out of results until their graph exists. Qdrant also builds on GPUs since 1.13, 12.4 seconds on an L4 against 97.5 on 8 CPU cores for 1 million 1,536-dimension vectors29, and since 1.14 a merge extends an existing graph instead of rebuilding it, though deletes and updates still trigger a full rebuild30.

milvus

Milvus splits the job across node types. Fresh data sits in growing segments on streaming nodes; sealed segments get their real index built by data nodes and handed to query nodes31. To keep fresh data from being a full scan, an interim IVF index (128 clusters, 16 probed) is built on growing segments and on sealed segments that are still waiting, for about 15% extra memory32. GPU builds with CAGRA have been available since 2.4.

weaviate

Weaviate’s async indexing accepts the write first and inserts into the graph from a queue. The dynamic index starts as a flat list and switches to HNSW at 10,000 objects. Deletes are marked and cleaned up periodically, and the docs warn that cleanup on large indexes “may take longer” and need more resources33; users have reported 500% CPU after deleting 36,000 objects34. HFresh, generally available in 1.38, is an SPFresh-style index: clusters on disk with a small graph over the centroids, split and reassigned in the background with “no full rebuilds”. It used 239 MB on dbpedia 1M against 6.67 GB for uncompressed HNSW, and Weaviate says HNSW still has “substantially higher throughput” at the same recall35.

pgvector

pgvector keeps one graph per index with no segments, so there are no merges. The README says HNSW has “slower build times and uses more memory” than IVFFlat and recommends creating the index after the initial load36. Parallel builds in 0.6 cut the dbpedia 1M build from 7,479 to 252 seconds across versions7. Each insert still pays the full graph search inside the writing transaction, and deleted rows leave work for VACUUM, which “can take a while for HNSW indexes”36.

clickhouse

ClickHouse builds a graph per part on insert and again on every merge, and its docs say HNSW “is known to provide slow inserts”. materialize_skip_indexes_on_insert = 0 defers the build to merges. RFC #104122, open since May 2026, aims at 100 to 10,000 new vectors every 30 seconds, searchable within 30 seconds; its long-term sketch is a global IVF index with delta lists and a compactor, after SPFresh37. I covered the rest of its design in the ClickHouse post.

one mutable graph

Vespa and Redis keep a single mutable HNSW per field and node, so no merges. Vespa documents real-time updates with the distance work spread over its indexing threads38. Redis 8 sustained 66,000 inserts per second into a 1-billion-vector index with M = 16 and ef_construction = 32, without saying on how many machines39. The cost per insert is the same search as everywhere else; the design avoids paying it again at merge time.

buffers on object storage

turbopuffer, LanceDB and Pinecone serverless keep new data in a write buffer and index it later. turbopuffer writes to a log on object storage and indexes asynchronously into an SPFresh-style index; strongly consistent queries scan the unindexed part, eventually consistent ones read at most 128 MiB of it40. LanceDB scans new rows until optimize() adds them to the index, and fast_search() skips them41. Pinecone keeps up to about 10,000 fresh vectors in memory, searched exactly, and compacts them into indexed slabs in the background42.

build times

Five before-and-after build times on a log scale. pgvector 0.5.0 to 0.6.2 on dbpedia 1M: 7,479 to 252 seconds, 29.7 times faster. OpenSearch CPU to remote GPU build: 273.8 to 29.1 minutes, 9.4 times. Elasticsearch HNSW-BBQ to DiskBBQ on 1M vectors: 1,054 to 94 seconds, 11.2 times. Lucene merge on gist int8, reusing the largest graph to joining graphs: 536 to 279 seconds, 1.9 times. Qdrant on 1M 1,536-dimension vectors, 8 CPU cores to an L4 GPU: 97.5 to 12.4 seconds, 7.9 times.

fig 6What each fix bought. The rows use different data and hardware, so compare the ratios, not the positions across rows.Vendor numbers: Supabase/jkatz for pgvector, OpenSearch 3.1 release post, Elastic Search Labs, Qdrant 1.13 release post.

The biggest gains come from three places: parallel and SIMD code, GPUs, and dropping the graph for clusters. Graph reuse and joins inside Lucene save between a few percent and about half of the merge time, depending on segment sizes.

research on fresh data

The research since 2021 attacks the same problem from both sides:

The NeurIPS 2023 Big-ANN competition had a streaming track with inserts, deletes and searches under 8 GB of RAM. The winner, PyANNS, used DiskANN-style streaming with 8-bit quantization and reached 0.887 recall against the baseline’s 0.72246.

where it stands

The problem isn’t solved. Every database has made the rebuild cheaper or moved it somewhere else, and each move costs something:

approachwhowhat it costs
faster rebuilds: graph reuse and joins, SIMD, quantization, GPUsLucene, OpenSearch, Qdrant, MilvusGPUs and licences; merges still rebuild most of the graph
scan new data, or hide itQdrant, LanceDB, Pinecone, turbopuffer, Milvus interim indexslow queries while indexing catches up, or results without the newest writes
clusters instead of a graphElasticsearch DiskBBQ, Weaviate HFresh, turbopuffer, ClickHouse RFClower throughput at very high recall
one mutable graphVespa, Redis, pgvectorevery insert still runs a graph search; deletes need clean-up

Deletes are the weakest part everywhere. Qdrant’s incremental merge skips segments with deletes, Weaviate needs tombstone clean-up, and in-place graph deletes exist only in papers. There is also no neutral benchmark that measures ingest rate, latency during ingest and recall together; VDBBench’s streaming case is the closest and it’s run by Zilliz.

For a table that takes writes all day I’d start with a cluster index (DiskBBQ on Elasticsearch, HFresh on Weaviate, or turbopuffer) and keep HNSW for collections that change rarely and need recall above 95%. On Qdrant I’d turn on prevent_unoptimized when a few seconds of staleness is fine, which is most search features.

sources
  1. Malkov, Ponomarenko, Logvinov, Krylov, Approximate nearest neighbor algorithm based on navigable small world graphs, Information Systems 45 (2014)
  2. Malkov and Yashunin, Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs (arXiv 1603.09320, 2016; IEEE TPAMI 2018)
  3. scripts/hnsw-count.mjs, the measurement behind fig 2
  4. Faiss wiki, indexing 1M vectors
  5. Munyampirwa, Lakshman, Coleman, Down with the Hierarchy: The 'H' in HNSW Stands for "Hubs" (arXiv 2412.01940, December 2024)
  6. Elastic, introducing DiskBBQ (23 October 2025)
  7. Jonathan Katz, pgvector 150x speedup (30 April 2024) and Supabase, pgvector 0.6.0 fast builds (30 January 2024)
  8. hnswlib README
  9. Xiao et al., Enhancing HNSW Index for Real-Time Updates (arXiv 2407.07871, July 2024)
  10. Fu, Xiang, Wang, Cai, Fast approximate nearest neighbor search with the navigating spreading-out graph (arXiv 1707.00143)
  11. Subramanya et al., DiskANN (NeurIPS 2019)
  12. Singh et al., FreshDiskANN (arXiv 2105.09613, May 2021)
  13. Chen et al., SPANN (NeurIPS 2021)
  14. Xu et al., SPFresh (SOSP 2023)
  15. Patel, Kraft, Guestrin, Zaharia, ACORN (SIGMOD 2024)
  16. Ootomo et al., CAGRA (ICDE 2024)
  17. Gao and Long, RaBitQ (SIGMOD 2024) and Elastic, BBQ (11 November 2024)
  18. McCoy, Wang, Pandey, Jasper (arXiv 2601.07048, v5 July 2026)
  19. Mo et al., LSM-VEC (arXiv 2505.17152, v3 October 2026)
  20. Elastic, Lucene and Elasticsearch vector database gains (26 April 2024)
  21. Elastic forum, indexing performance on indices with vector fields (2024)
  22. Elastic forum, manage heavy indexing in kNN indexes (11 October 2023)
  23. Lucene PR #12050, reuse HNSW graph on merge (February 2023)
  24. Elastic, speeding up HNSW graph merging (7 April 2025)
  25. Elastic, GPU-accelerated vector indexing with NVIDIA (3 December 2025)
  26. OpenSearch, get started with 3.1
  27. OpenSearch, concurrent vector graph construction and jVector plugin docs
  28. Qdrant docs, predictable search latency and optimizer docs
  29. Qdrant 1.13 release (23 January 2025)
  30. Qdrant 1.14 release (22 April 2025)
  31. Milvus architecture overview
  32. Milvus query node configuration
  33. Weaviate vector index configuration
  34. Weaviate forum, CPU during tombstone cleanup
  35. Weaviate, HFresh (9 September 2026)
  36. pgvector README (0.8.7)
  37. ClickHouse RFC #104122, vector similarity index 2.0 (May 2026) and vector index docs
  38. Vespa, approximate nearest neighbor search using HNSW
  39. Redis, searching 1 billion vectors with Redis 8 (7 March 2025)
  40. turbopuffer architecture
  41. LanceDB, reindexing
  42. Pinecone architecture
  43. IP-DiskANN, in-place deletes (arXiv 2502.13826, February 2025)
  44. UBIS (arXiv 2602.00563, January 2026)
  45. Slipstream (arXiv 2606.02992, June 2026)
  46. Simhadri et al., Results of the Big ANN NeurIPS'23 competition (arXiv 2409.17424)