Hierarchical Navigable Small World (HNSW) is a graph-based algorithm for approximate nearest neighbor (ANN) search that builds a multi-layered proximity graph where each layer represents a different granularity of the data space. The top layers contain long-range edges for coarse navigation, while bottom layers capture fine-grained local connectivity, enabling greedy routing that skips across large distances before descending to precise matches in logarithmic time.
Glossary
HNSW (Hierarchical Navigable Small World)

What is HNSW (Hierarchical Navigable Small World)?
HNSW is a graph-based algorithm for approximate nearest neighbor search that constructs a multi-layered navigable structure to achieve logarithmic time complexity during retrieval.
During insertion, each vector is assigned a random integer level using an exponentially decaying probability distribution, then connected to its M nearest neighbors at that layer and all layers below. Search begins at the top layer's entry point, performs a best-first greedy traversal at each level, and descends when a local minimum is reached—repeating until the bottom layer yields the final ef_search candidates. This structure avoids the curse of dimensionality that cripples tree-based indices, making HNSW the default choice in libraries like FAISS and hnswlib for high-recall, low-latency vector retrieval.
Key Features of HNSW
HNSW achieves logarithmic time complexity for approximate nearest neighbor search by constructing a multi-layered, navigable graph structure that naturally separates long-range and short-range connections.
Hierarchical Layered Structure
HNSW organizes vectors into a multi-layer graph where each layer represents a different density of connections. The bottom layer (layer 0) contains all data points with short-range links, while higher layers contain exponentially fewer nodes with long-range connections. This mimics the structure of skip lists, enabling O(log N) search complexity.
- Layer assignment uses an exponentially decaying probability distribution
- Higher layers act as express lanes for rapid coarse navigation
- The top layer typically contains only a single entry point node
Greedy Search with Beam Width
Retrieval uses a best-first greedy search that traverses the graph by always moving to the neighbor closest to the query vector. The algorithm maintains a dynamic candidate list of size ef (exploration factor) to prevent getting trapped in local minima.
ef_searchcontrols the beam width during query time- Higher
efvalues improve recall at the cost of latency - The search starts at the top-layer entry point and descends layer by layer
Incremental Insertion with No Rebuilds
HNSW supports fully incremental indexing — new vectors are inserted one at a time without requiring global index rebuilds. Each insertion finds the nearest neighbors across layers and establishes bidirectional connections, maintaining the graph's navigability.
- M parameter controls the maximum number of outgoing connections per node
- M_max0 (typically 2 × M) sets connections at the base layer
- Insertion triggers local connection pruning to maintain the small-world property
Small-World Navigability Property
The graph maintains the navigable small-world property where any node can reach any other node in a small number of hops. This is achieved through a heuristic that selects neighbors based on distance diversity rather than just proximity, preventing redundant connections.
- Heuristic pruning removes edges that don't shorten paths to other regions
- Maintains logarithmic diameter of the graph
- Naturally handles high-dimensional data without dimensionality reduction
Memory vs. Recall Trade-off
HNSW provides tunable control over the memory-accuracy trade-off through its construction parameters. The M parameter directly controls graph degree and memory footprint, while ef_construction governs index build quality.
- Typical
Mvalues range from 16 to 64 - Memory scales as O(M × N) where N is the number of vectors
- Achieves 95-99% recall at sub-millisecond query latencies on million-scale datasets
Deletion Handling via Tombstones
HNSW natively supports soft deletion through tombstones — deleted nodes are marked as inactive but remain in the graph structure to preserve navigability for other nodes. This avoids the costly operation of repairing broken graph connectivity.
- Deleted nodes are skipped during search traversal
- Periodic compaction can physically remove tombstones
- Enables CRUD operations without degrading search performance
HNSW vs. Other ANN Algorithms
A technical comparison of HNSW against other prominent approximate nearest neighbor algorithms across critical performance and operational dimensions.
| Feature | HNSW | FAISS (IVF-PQ) | Annoy | LSH |
|---|---|---|---|---|
Index Structure | Multi-layer navigable small-world graph | Inverted file with product quantization | Forest of random projection trees | Hash tables with locality-sensitive functions |
Query Time Complexity | O(log N) | O(sqrt(N)) | O(log N) | Sub-linear O(1) to O(N) |
Recall@10 (Typical) |
| 90-95% | 80-90% | 60-85% |
Memory Footprint | High (raw vectors + graph edges) | Low (compressed codes) | Medium (tree structures) | Low (compact hash codes) |
Incremental Insertion | ||||
Deletion Support | ||||
GPU Acceleration | ||||
Distance Metrics Supported | Euclidean, Cosine, Inner Product | Euclidean, Inner Product | Euclidean, Angular, Manhattan | Jaccard, Hamming, Cosine |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Frequently Asked Questions
Explore the mechanics, performance characteristics, and implementation details of the Hierarchical Navigable Small World algorithm, the dominant indexing structure for high-performance vector databases.
HNSW (Hierarchical Navigable Small World) is a graph-based algorithm for approximate nearest neighbor (ANN) search that constructs a multi-layered, proximity graph to achieve logarithmic time complexity during retrieval. It works by building a hierarchy of navigable small world (NSW) graphs, where each layer represents a different granularity of the data. The bottom layer (layer 0) contains all data points, while higher layers contain progressively fewer points, acting as an express highway for the search. A query starts at the top layer, greedily traverses to the nearest neighbor, then descends to the next layer, using the entry point from the previous layer. This skip-list-like mechanism allows the algorithm to quickly navigate to the dense region of interest, bypassing vast swaths of irrelevant data. The graph edges are built using a parameter M (maximum connections per node) and efConstruction (search width during construction), which balance recall against memory usage and build time.
Related Terms
Core concepts and algorithms that interact with or underpin the HNSW graph-based indexing structure for high-performance approximate nearest neighbor search.
Approximate Nearest Neighbor (ANN)
The algorithmic class to which HNSW belongs. ANN trades a small, controlled loss in recall for orders-of-magnitude speed improvements over exact k-NN search.
- Core trade-off: Accuracy vs. latency vs. memory
- HNSW is a leading graph-based ANN method
- Enables sub-linear search time: O(log N) complexity
- Critical for billion-scale vector databases
Product Quantization (PQ)
A vector compression technique frequently paired with HNSW to reduce memory footprint. PQ decomposes the original high-dimensional space into a Cartesian product of lower-dimensional subspaces and quantizes each independently.
- Reduces memory by 10-30x with minimal recall loss
- Often used as a secondary compression layer on top of HNSW graphs
- Enables billion-scale indices on commodity hardware
- Complements HNSW's in-memory graph structure
Cosine Similarity
The primary distance metric used in HNSW-based semantic search. Measures the cosine of the angle between two non-zero vectors, providing magnitude-invariant similarity scoring.
- Range: -1 (opposite) to 1 (identical)
- HNSW supports cosine, Euclidean, and inner product spaces
- Normalized embeddings make inner product equivalent to cosine similarity
- Essential for comparing dense text embeddings
Curse of Dimensionality
The fundamental problem HNSW is designed to solve. As dimensions increase, the concept of distance becomes less meaningful—all points appear equidistant, breaking traditional spatial indexes like k-d trees.
- HNSW's graph structure mitigates this by navigating through proximity layers
- Traditional tree structures degrade to O(N) in high dimensions
- Embedding dimensions typically range from 384 to 4096
- HNSW maintains logarithmic scaling despite dimensionality
Hybrid Search & Reciprocal Rank Fusion
A retrieval architecture that combines HNSW-based dense vector search with sparse keyword search (BM25). Reciprocal Rank Fusion (RRF) merges the two result sets into a single ranking.
- HNSW handles semantic understanding
- BM25 handles exact keyword matching
- RRF formula:
score(d) = Σ 1/(k + rank_i(d)) - Outperforms either method alone on complex queries

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us