Scaling Vector Memory for Agentic Reviews: Surviving HNSW Write Bursts
As a principal systems architect evaluating elementalsouls/Claude-BugHunter as an external team, I watched an elegant AI workflow collapse into latency hell at 3:17 AM on a Friday. The system handled 85 skills and 16 slash commands without issue, yet the memory layer for ongoing reviews turned into a bottleneck the moment concurrent notes flooded the index. What should have been a fast contextual recall suddenly stalled reviewers, turning a smooth debugging session into an on-call nightmare.
The root cause was simple: we needed a vector index that stayed responsive under heavy write load while still delivering low-latency searches for session notes. Traditional indexes hid the problem until it bit us in production.
Decoupling the skill runtime from the memory service
The skill runtime picks a skill, writes a short append-only note when a step ends, and never speaks SQL. A separate memory service handles chunking, embedding, and searching. This isolation is non-negotiable in production.
We run ingest and query against different connection pools. Writers cannot starve readers, and vice versa. Embeddings are rewritten only on text changes, keeping the hot path lean.
We store only summary text—title, component, outcome—never exploit procedures or full reports. The row contains a source key so the original write-up lives outside the index. Retrieval similarity serves context, not replay.
To harden this layer, we added explicit timeouts (30 s on embedding calls) and exponential backoff retries for 502/503 errors, treating 429 rate limits with jitter. Buffer exhaustion risks are capped by enforcing a 4 k token chunk limit per note and monitoring Python list memory usage with a soft cap at 512 MB per process. If a vector is zero-length, we default to a unit vector rather than crash.
Two failures that toy indexes hide
Concurrent inserts turned HNSW into a lock queue. Latency jumped from tens of milliseconds to multi-second stalls. Raising ef_construction only lengthened the queue. A plain CREATE INDEX during business hours froze writers completely.
The recall bug was subtler. We chose inner-product because it is cheap, but the embedding model did not return unit vectors. Chunk length biased long notes to the top of every neighbor list. Recall on a hand-labeled set dropped while the index appeared healthy.
The fix was operational. We bulk-loaded into a side table, built with CREATE INDEX CONCURRENTLY off the request path, and kept ef_construction modest (64) on the live index. For the inner-product issue, we normalize every vector to unit length on write and on query, then use vector_ip_ops.
Production hardening included:
- Shared-nothing connection pools (max 10 for queries, 20 for writes) to eliminate starvation.
- Per-call circuit breakers that fail fast on unrecoverable 4xx/5xx codes after three retries.
- Race-condition guards around vector normalization using Python locks when the hybrid search runs in a multithreaded worker pool.
- Host-level memory caps via ulimits and cgroups to prevent buffer exhaustion when thousands of chunks accumulate.
Schema, index, and filtered query
Dimensions are 1536. m = 16 and ef_construction = 64 favor insert stability on the live table. A heavier rebuild runs at night.
CREATE EXTENSION IF NOT EXISTS vector; CREATE TABLE memory_chunks ( id bigserial PRIMARY KEY, session_id uuid NOT NULL, source_key text NOT NULL, body text NOT NULL, kind text NOT NULL, embedding vector(1536) NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX memory_chunks_session_kind ON memory_chunks (session_id, kind); CREATE INDEX memory_chunks_hnsw ON memory_chunks USING hnsw (embedding vector_ip_ops) WITH (m = 16, ef_construction = 64); SET hnsw.ef_search = 80; SELECT id, source_key, body, (embedding <#> $1) * -1 AS ip_score FROM memory_chunks WHERE session_id = $2 AND kind = $3 ORDER BY embedding <#> $1 LIMIT 20; <#> returns negative inner product, so ascending order yields best neighbors. A tight filter on one HNSW index still walks candidates before discarding them. Session notes and the curated pattern collection live in separate tables. The pattern collection refreshes offline. Session notes are the only rows that see live writers while reviewers wait.
Fusion by rank
Paths, symbols, and identifier tokens belong to lexical search. Paraphrased notes belong to vectors. We fuse the two ranked id lists with reciprocal rank fusion and ignore raw scores, so a magnitude bug cannot override a keyword hit. k = 60 is the usual dampener.
import math from collections import defaultdict def l2_normalize(vec: list[float]) -> list[float]: norm = math.sqrt(sum(x * x for x in vec)) or 1.0 return [x / norm for x in vec] def reciprocal_rank_fusion( rankings: list[list[str]], k: int = 60 ) -> list[tuple[str, float]]: scores: dict[str, float] = defaultdict(float) for ranking in rankings: for rank, doc_id in enumerate(ranking, start=1): scores[doc_id] += 1.0 / (k + rank) return sorted(scores.items(), key=lambda item: item[1], reverse=True) def hybrid_search(conn, session_id: str, query_text: str, query_vec: list[float], limit: int = 10): query_vec = l2_normalize(query_vec) lexical_ids = lexical_rank(conn, session_id, query_text, limit=50) vector_ids = vector_rank(conn, session_id, query_vec, limit=50) return reciprocal_rank_fusion([lexical_ids, vector_ids])[:limit] lexical_rank and vector_rank return ids ordered only. Embedding calls use an OpenAI-compatible client. For multi-provider fallback we set base_url to https://b-lost.com/v1 on that relay. The hop sees prompt text, so chunks never contain credentials. Normalization runs after the vector comes back, in our process, not at the gateway.
Production hardening and edge cases
We monitor each ranked list independently. If labeled neighbors drift, we run a concurrent rebuild with higher ef_construction at night. We never rebuild on the request path.
Edge cases receive attention:
- Invalid embeddings trigger graceful degradation to lexical-only results instead of crashing the query.
- Zero vectors are normalized before insertion to prevent division-by-zero.
- Unhandled HTTP errors from the embedding endpoint are retried up to three times with jittered backoff; beyond that we return empty results and log.
- Concurrency race conditions around shared state are guarded with Python threading locks when the hybrid search runs in a multithreaded worker pool.
- Transport limits are enforced with connection-pool max sizes and per-call timeouts to prevent one slow embedding from blocking the entire review queue.
- Memory safety is maintained by capping vector list sizes and using efficient data structures rather than naive Python lists for very large collections.
Those HNSW parameters will not win a recall bake-off. They keep insert latency stable while agents write. If labeled neighbors drift, we run a concurrent rebuild with a higher ef_construction. We do not rebuild on the request path, and we do not stuff more skills into the prompt to compensate. Fixed-k RRF will not notice a retriever that is always wrong, and it will not let one wild score take over. Each list is monitored on its own.
Claude-BugHunter stays upstream. We did not write it. The index contract is what we operate. When search slows or neighbors degrade, the cause so far has been graph locks and vector scale.
The single hardest operational dilemma remains the write-query contention under sustained load: how do you keep an index stable enough for continuous ingestion while preserving enough recall to feel magical to the reviewer? In the trenches we learned that the difference between a system that survives and one that collapses is often the difference between a night-time rebuild and a request-path stall.
What production battle scars have you collected scaling HNSW or similar vector indexes in agentic systems? How do you balance recall, latency, and write throughput when reviewers and agents hammer the same database at 3 AM?