Build a Real-Time Vector Index with Incremental Updates


databases performance data-engineering

AI System Design Deep Dive

Real-Time Vector Index

An HNSW graph is fastest when nothing changes. Freshness is the one requirement it was never designed for.

⏱ 14 min read 📐 Advanced 🗃️ Vector Search

A vector index is a road network, and HNSW builds a very good one. Short local streets connect near neighbours, a few long-haul highways span the whole space, and a query drops onto a highway, exits progressively onto smaller roads, and arrives at its destination in a few dozen hops. The build process gets to see the entire city before it lays a single road. That global view is exactly what makes the graph good, and it is exactly what a real-time system does not have.

Now put 400 million embeddings of dimension 1024 in that city and let 12,000 new ones arrive every second, forever. A support ticket filed at 09:14:03 needs to be retrievable by a similarity query at 09:14:04, not at tomorrow’s rebuild. Deletions arrive too, because a document got unshared or a customer exercised a deletion request, and they need to stop appearing in results within the same second. Meanwhile 2,500 searches per second want recall@10 above 0.92 at a 45ms p99.

Each of the naive designs fails in a different place, which is the useful part. Rebuild the whole graph on a schedule and freshness is whatever your cadence is: a nightly rebuild of 400M vectors at 1,500 distance computations per insert is 600 billion distance computations, roughly 9.3 hours on 32 cores, so the index is always somewhere between one and ten hours stale. Insert into a single live HNSW graph and you hit two walls at once: the graph’s quality degrades because early insertions picked their neighbours from a nearly empty space and never revisit that choice, and every insertion mutates the adjacency lists that concurrent readers are traversing. Keep a small fresh index next to a big stale one and search both, and the design works beautifully until the small one is not small any more.

Deletes are worse than inserts, and it is not obvious why. You cannot remove a node from an HNSW graph by freeing it, because that node may be the only bridge between two regions of the graph. Delete a few thousand well-connected hubs and recall does not degrade gracefully, it falls off a cliff for the queries whose targets are now on the far side of a severed link.

So we need to solve for three things simultaneously: bounded visibility lag from write acknowledgement to searchable, bounded query fan-out so that freshness does not turn one search into thirty, and bounded write amplification so that keeping the graph good does not cost more CPU than answering queries with it.

Requirements and Constraints

Functional Requirements

  • upsert(doc_id, vector, payload) is idempotent on doc_id; a re-upsert replaces the previous vector and its payload atomically from the reader’s perspective
  • delete(doc_id) stops the record from appearing in any result set, including in-flight buffered writes not yet sealed
  • search(vector, k, filter) returns approximate top-k across every committed segment plus the live mutable buffer, with a single consistent view of segment state
  • search_at(vector, k, lsn) supports read-your-writes: a client that received log sequence number L from an upsert can demand a view that includes L
  • Payload filters (tenant_id, source, updated_after) are applied during graph traversal, not after the top-k is assembled
  • The index survives process restart with no data loss for any acknowledged write

Non-Functional Requirements

  • Visibility lag: p50 under 80ms, p99 under 190ms from 202 ACK to searchable. This is the metric the whole design exists to serve
  • Durability: fsync before ACK, p99 write ACK under 12ms
  • Write throughput: 12,000 upserts/s sustained, 40,000/s burst for 60 seconds without visibility lag exceeding 2s
  • Search throughput: 2,500 QPS at k=10, p50 18ms, p99 45ms
  • Quality: recall@10 at or above 0.92 against exact search, measured continuously, never dropping below 0.88 even immediately after a merge
  • Capacity: 400M vectors resident, 268 bytes per vector including graph, so 107 GB of RAM in the index plus overhead
  • Cost: under $0.55 per million upserts and under $0.85 per million queries
  • Segment fan-out: at most 32 searchable segments at steady state

Constraints

  • Embeddings are 1024-dimensional float32 produced upstream; we own storage and search, not the embedding model
  • Distance metric is cosine, precomputed as normalized inner product
  • Hardware: r7i.8xlarge class nodes, 32 vCPU and 256 GB RAM, local NVMe for segment files
  • Product quantization to 128-byte codes is assumed, with a full-precision rerank of the top 100 candidates from object storage
  • Out of scope: multi-region replication, the embedding pipeline itself, and hybrid keyword fusion
  • Out of scope: GPU-accelerated index construction. The merge budget here is CPU

High-Level Architecture

The design that works is the one databases settled on decades ago for exactly this tension: never mutate a large structure in place, write small immutable pieces and merge them in the background. An LSM tree for vectors. Writes land in a small mutable graph, that graph gets frozen into an immutable segment on a timer, and a background compactor merges small segments into big ones so that the number of things a query must touch stays bounded.

Architecture of a real-time vector index with a write path through WAL and mutable buffer, an LSM segment set across four levels, a fan-out read path, and a control plane

Six components carry the system. The upsert API assigns a log sequence number and deduplicates on doc_id. The WAL makes the write durable with a group fsync and is the only thing on the blocking path. The mutable buffer is a small live HNSW graph, capped at 96,000 vectors, that a tail follower populates asynchronously from the WAL. The sealer freezes that buffer every 8 seconds and writes it out as an immutable L0 segment. The compactor merges eight segments of one level into one segment of the next, rebuilding the graph from scratch each time. The query coordinator fans a search across every live segment plus the buffer, splits the efSearch budget between them, and merges the per-segment result lists after dropping tombstoned hits.

A write flows like this. The client posts a vector, gets an lsn back, and its bytes are durable in the WAL 4ms later. At that instant the record is not searchable, and the API is honest about that: the response carries the lsn so a client that needs read-your-writes can pass it to search_at. Asynchronously, a tail follower reads the WAL, quantizes the vector to a 128-byte PQ code, and inserts it into the mutable buffer’s graph. That insert costs about 1,500 distance computations at efConstruction=200, roughly 90 microseconds, and when the neighbour pointers are swapped in the record becomes searchable. End to end, 190ms at p99, almost all of it queueing rather than work.

A search flows the other direction. The coordinator reads the current manifest version, giving it a fixed list of segments for the life of the query. It divides an efSearch budget across them, runs an independent graph descent in each, and merges. The subtlety is that segments are wildly different sizes, so an equal split is wrong: a 49M-vector L3 segment needs far more of the budget than a 96,000-vector L0 segment to reach the same local recall.

Key Insight

Freshness is not an index property, it is a segment-count property. Every design decision below is really a decision about how many separate graphs a query has to descend, because that count is what converts write freshness into read latency.

The Write Path and the Mutable Buffer

This component’s job is to make a write durable fast and searchable soon, and to keep those two deadlines completely independent of each other.

Write flow showing a durability leg completing in 4ms, an asynchronous visibility leg completing in 190ms, and a seal leg firing every 8 seconds

The thing a smart engineer assumes here that turns out to be wrong: that the graph insert belongs on the request path. It does not, and putting it there is the single most common way this design gets ruined. A graph insert at efConstruction=200 is 90 microseconds of pure CPU, which sounds cheap until 12,000 of them per second need 1.1 vCPU of dedicated work that now competes with query serving inside the request handler’s thread pool. Worse, insert cost is not constant. It scales with the log of the buffer’s size and it spikes when an insert triggers neighbour pruning on a high-degree node. Put that variance on the request path and your write p99 inherits the graph’s worst case.

So the request path does three things only: assign lsn, append to WAL, fsync. Group commit batches about 48 writes per fsync at 12,000/s, which is what keeps ACK latency at 4ms instead of the 0.4ms per-write fsync cost times 12,000.

# Durability leg: append-and-group-fsync, the only synchronous work on an upsert.
import asyncio, struct, time

class WriteAheadLog:
    def __init__(self, fh, max_batch=64, max_delay_s=0.004):
        self.fh = fh
        self.max_batch = max_batch
        self.max_delay_s = max_delay_s
        self.next_lsn = 1
        self.pending: list[tuple[int, bytes, asyncio.Future]] = []
        self.flusher = asyncio.create_task(self._flush_loop())

    async def append(self, doc_id: str, code: bytes, payload: bytes) -> int:
        lsn = self.next_lsn
        self.next_lsn += 1
        did = doc_id.encode()
        record = struct.pack("<QHHH", lsn, len(did), len(code), len(payload))
        record += did + code + payload
        fut = asyncio.get_running_loop().create_future()
        self.pending.append((lsn, record, fut))
        if len(self.pending) >= self.max_batch:
            self._drain()
        return await fut

    def _drain(self) -> None:
        if not self.pending:
            return
        batch, self.pending = self.pending, []
        for _, record, _ in batch:
            self.fh.write(record)
        self.fh.flush()
        import os
        os.fsync(self.fh.fileno())
        for lsn, _, fut in batch:
            if not fut.done():
                fut.set_result(lsn)

    async def _flush_loop(self) -> None:
        while True:
            await asyncio.sleep(self.max_delay_s)
            self._drain()

The mutable buffer on the other side is a normal HNSW graph with one unusual property: it is bounded. Capping it at 96,000 vectors is not an arbitrary number, it is the point where the buffer’s own search cost stops being negligible. A 96,000-node graph has four layers and a descent touches maybe 350 nodes at efSearch=64, about 0.4ms. Let the buffer reach a million vectors and that becomes 0.9ms and the buffer stops being the cheap part of the fan-out.

Sizing the buffer is a choice between two costs, and the arithmetic is short. At 12,000 writes/s, a cap of 96,000 vectors means a seal every 8 seconds, which means 450 L0 segments per hour arriving into a compactor that must consume them. Halve the cap to 48,000 and you double the seal rate and the L0 compaction rate. Double it to 192,000 and you halve compaction pressure but the buffer’s contribution to query latency roughly doubles.

Real World

Vespa takes the opposite path and mutates a single `HNSW` graph in place, using generation-based memory reclamation so readers never take a lock. It buys sub-second freshness with no segment fan-out at all, and pays for it with graph quality drift that eventually needs a redistribution, plus a much harder concurrency story. Lucene, and therefore Elasticsearch and OpenSearch, take the segment path this design takes: a per-segment `HNSW` graph, rebuilt entirely on merge.

Premium Content

Unlock the full article along with everything else in the archive — all in one place.

In-depth analysis Expert insights Full archive access
Unlock Full Article