Your enterprise RAG vector service indexes 12 million 1536-dim embeddings in an HNSW collection (M=16, efConstruction=128, efSearch=64). Every night, a document sync job deletes and re-upserts ~1.5 million changed chunks. Over two weeks, Recall@10 has degraded from 0.96 to 0.61 and p99 query latency spiked from 12 ms to 140 ms, even though active live vector count is still 12 million. Diagnose why HNSW degrades under heavy churn and design a zero-downtime compaction and re-indexing architecture.
From patterns to decisions.
HNSW soft-deletes leave tombstone nodes in the graph that trap efSearch beams in dead ends; fix it with inline tombstone-aware traversal, thresholded background segment compaction, and atomic blue-green index swaps.
Why HNSW Uses Soft-Delete Tombstones Instead of Edge Rewiring.
Physically deleting a node from an HNSW graph requires finding every incoming edge across Layers 0..L and running SelectNeighborsHeuristic on each affected neighbor to repair connectivity. Under concurrent read/write traffic, acquiring multi-node graph locks stalls queries.
Instead, engines mark deleted[node_id] = 1 in a bitset. After 14 days of 1.5M daily updates (each update = 1 tombstone + 1 new node), your 12M-live-vector index actually holds 33M total graph nodes, of which 63% are dead tombstones.
1.5M Daily Upserts -> 63% Tombstone Graph
1.:
2.:
Caption: Soft-deleting 1.5M vectors daily without compaction balloons the graph from 12M to 33M nodes, leaving 63% of Layer 0 edges pointing through dead tombstones.
How Tombstones Starve efSearch and Collapse Recall@10.
During Layer 0 beam search, efSearch = 64 caps the candidate frontier. When 63% of visited nodes are tombstones:
- Beam Pollution: Half the
efSearchslots fill with dead nodes that must be traversed to keep graph paths connected, leaving far fewer live candidates. - Broken Express Bridges: Upper-layer hub nodes marked deleted can no longer be returned, and if their live neighbors were pruned earlier, the beam gets trapped in suboptimal local minima (
Recall@10: 0.96 -> 0.61). - Latency Spike: The engine must expand deeper hops and still misses
K=10live matches, pushing p99 from12 msto140 ms.
Healthy Graph vs Tombstone-Clogged Beam
1.:
2.:
Caption: Tombstones consume efSearch beam slots and distance computations while yielding zero returnable results, collapsing Recall@10 from 0.96 to 0.61.
Segmented HNSW Indexing & Thresholded Background Compaction.
Rather than one 12M-node graph, partition the collection into 8–16 bounded segments (e.g., 1M–1.5M vectors each, similar to Qdrant/Milvus/Lucene):
- Tombstone Ratio Metric: Track
tombstone_ratio = deleted_count / total_nodesper segment. - Compaction Trigger (
> 20%): When a segment crosses 20% tombstones, a background worker reads only live vectors from that segment and builds a fresh HNSW sub-graph (M=16, efConstruction=128) on isolated CPU cores. - Atomic Segment Swap: Once built and verified, swap the segment pointer atomically in memory and free the old segment after active readers drain.
Per-Segment Rebuild & Atomic Swap
1.:
2.:
Caption: Partitioning HNSW into 1.5M-vector segments lets background workers rebuild dirty segments above 20% tombstones and swap them atomically with zero downtime.
Content-Hash Diffing to Cut Unnecessary Churn by 70–85%.
Many RAG pipelines blindly delete_by_doc_id + insert all chunks when a document's metadata updates. Adding a deterministic SHA-256 content hash per chunk lets the sync worker skip unchanged embeddings:
- Compare
(chunk_id, content_sha256)against stored payload metadata. - Only delete removed chunks and insert modified chunks—cutting daily tombstone generation from 1.5M to ~200K.
Blind Re-Upsert vs Content-Hash Diffing
1.:
2.:
Caption: Hashing chunk text before ingestion eliminates redundant delete-and-insert cycles, slashing daily HNSW tombstone creation by up to 85%.
Safe Background Compaction Controller with Recall Gate & Rollback.
A background compaction job must never swap in a corrupt or under-built segment, and must retry transient I/O errors with bounded backoff:
import random, time
from typing import Protocol
class SegmentAdmin(Protocol):
def tombstone_ratio(self, seg_id: str) -> float: ...
def build_clean_segment(self, seg_id: str) -> str: ...
def measure_recall(self, seg_id: str) -> float: ...
def atomic_swap(self, old_seg: str, new_seg: str) -> None: ...
def drop_segment(self, seg_id: str) -> None: ...
def compact_if_needed(admin: SegmentAdmin, seg_id: str, max_ratio: float = 0.20) -> bool:
if admin.tombstone_ratio(seg_id) <= max_ratio:
return False
new_seg = None
for attempt in range(3):
try:
new_seg = admin.build_clean_segment(seg_id)
if admin.measure_recall(new_seg) < 0.95:
admin.drop_segment(new_seg)
raise RuntimeError(f'Recall gate failed for {new_seg}; rolled back')
admin.atomic_swap(seg_id, new_seg)
return True
except OSError as exc:
if new_seg:
admin.drop_segment(new_seg)
if attempt == 2:
raise RuntimeError(f'Compaction failed for {seg_id}: {exc}') from exc
time.sleep((0.5 * (2 ** attempt)) + random.uniform(0, 0.2))
return FalseBuild -> Recall Gate (>=0.95) -> Atomic Swap
1.:
2.:
Caption: The compaction controller builds a clean shadow segment, gates cutover on >= 0.95 Recall@10, and cleans up shadow segments on failure.
Preventing Compaction CPU & Memory Contention on Live Traffic.
Building an HNSW graph (efConstruction=128) is heavily CPU- and memory-bandwidth-intensive. Running compaction on all cores alongside peak RAG traffic will spike p99 latency:
- Thread Pool Cap: Limit HNSW builder threads to
25%of host vCPUs (e.g., 4 of 16 cores) and nice priority. - Memory Headroom: Reserve
30%free RAM above the 12M live index size so shadow segment construction never triggers OS swap. - Staggered Segment Merging: Compact at most 1 segment per shard concurrently.
Unthrottled Rebuild vs Capped Background Pool
1.:
2.:
Caption: Capping builder threads to 25% of cores and reserving 30% RAM headroom keeps foreground query latency flat during background HNSW compaction.
Tracking Tombstone Ratio, Effective efSearch, and Recall SLOs.
Monitor three leading indicators so Recall@10 never silently drops again:
hnsw_segment_tombstone_ratio: Alert at> 0.25(indicates compaction is falling behind churn).hnsw_nodes_visited_per_query: Rising hop counts at constantefSearchsignal dead-node detours before p99 breaches.- Synthetic Golden Recall Probe: Run 100 fixed ground-truth queries against exact flat k-NN hourly and alert if
Recall@10 < 0.94.
Degraded State vs Compacted Steady State
1.:
2.:
Caption: Combining tombstone_ratio alerts, visited-hop telemetry, and hourly golden-set recall probes sustains 0.96 Recall@10 and 12 ms p99 latency.
Practice: Make the trade-off yourself.
Why is partitioning a 12M-vector HNSW index into 1.5M-vector segments better than rebuilding one monolithic 12M-node graph?