DEV Community

Cover image for Defending Vector Search Latency: A Performance Budget for pgvector
Amit chakraborty
Amit chakraborty

Posted on Originally published at amitchakraborty.dev

Defending Vector Search Latency: A Performance Budget for pgvector

Say you are the lead engineer on a RAG (Retrieval-Augmented Generation) pipeline. Your application started with 10,000 document chunks, and vector search was instantaneous. As the product team ingested more data, the collection grew to 500,000 vectors. Suddenly, your P99 latency for search queries jumped from 40ms to 1,200ms. The LLM integration is now timing out, users are seeing "Internal Server Error" messages, and the database CPU is pinned at 100% during peak hours.

You are no longer looking for "better" search; you are fighting to keep the service alive. This is the moment where "make it faster" must be replaced by a performance budget: a strict ceiling on latency and a floor on recall that the engineering team commits to defending as the dataset scales.

Why vector search fails at scale

PostgreSQL is a relational database first. When you add pgvector (specifically version 0.7.0 or 0.8.0), you are asking it to perform high-dimensional geometry.

By default, without an index, pgvector performs an exact nearest neighbour search. It calculates the distance between your query vector and every single row in the table. This is a sequential scan. If you have 500,000 vectors of 1,536 dimensions (the standard for OpenAI text-embedding-3-small), a single query requires calculating roughly 768 million floating-point operations.

As the table grows, the time taken for these calculations increases linearly. You hit a wall where the CPU cannot compute distances fast enough to satisfy concurrent web requests.

The solution is an Approximate Nearest Neighbour (ANN) index, such as HNSW (Hierarchical Navigable Small Worlds) or IVFFlat. However, these indexes introduce a trade-off that the documentation often glosses over: you trade accuracy (recall) for speed. If you tune the index for maximum speed, you might return the 10th or 20th best matches instead of the top 3, breaking the context for your LLM and resulting in "hallucinations" because the retrieved data is irrelevant.

The Fix: Step-by-Step Index Tuning

To fix this, you must move from a sequential scan to an HNSW index while maintaining a performance budget. We will target a budget of <100ms P99 latency with >90% recall.

1. Establish the baseline recall

Before building an index, you must know what "perfect" looks like. Run a query without an index and save the IDs of the top 10 results. This is your ground truth.

-- Disable index usage for the session to get ground truth
SET enable_indexscan = off;

SELECT id FROM items 
ORDER BY embedding <=> '[0.12, 0.05, ...]' 
LIMIT 10;
Enter fullscreen mode Exit fullscreen mode

2. Choose the index type

For production workloads where query speed is the priority and you have sufficient RAM, HNSW is almost always the correct choice over IVFFlat. IVFFlat requires you to "train" the index with lists and has a performance cliff if the distribution of your vectors shifts. HNSW is more robust but uses more memory.

3. Build the HNSW index with a performance budget

The two critical parameters during index creation are m (max connections per node) and ef_construction (how hard the builder tries to find the best connections).

A common mistake is using the defaults (m=16, ef_construction=64) for large datasets. This often results in poor recall.

-- Increase maintenance_work_mem to speed up index builds
SET maintenance_work_mem = '2GB';

CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops)
WITH (m = 24, ef_construction = 100);
Enter fullscreen mode Exit fullscreen mode
  • What to do: Set m between 16 and 32. Set ef_construction between 64 and 200.
  • Why: Higher m increases the "connectivity" of the graph, improving recall but increasing the index size on disk. Higher ef_construction makes the index build slower but results in a better-organised graph.
  • How to confirm: Check the index size after creation.

    SELECT pg_size_pretty(pg_relation_size('items_embedding_idx'));
    

An HNSW index for 500k vectors at 1536 dimensions with m=24 will occupy roughly 4-6GB of RAM/disk.

4. Tune the search performance (ef_search)

This is the most important step for your performance budget. The parameter hnsw.ef_search determines how many nodes the engine explores during a query.

  • A low ef_search (e.g., 20) is extremely fast but might only return 60% of the true nearest neighbours.
  • A high ef_search (e.g., 400) is slower but approaches 99% recall.

You must find the "knee of the curve" where latency is acceptable and recall is sufficient.

-- Test a query with a specific ef_search
SET hnsw.ef_search = 100;

EXPLAIN ANALYZE 
SELECT id FROM items 
ORDER BY embedding <=> '[0.12, 0.05, ...]' 
LIMIT 10;
Enter fullscreen mode Exit fullscreen mode

Look for: In the EXPLAIN ANALYZE output, check the Execution Time. If it is 30ms and your budget is 100ms, you have "headroom" to increase ef_search to improve recall. If it is 150ms, you must decrease ef_search or increase your hardware specs.

5. Calculate Recall vs Budget

Compare the IDs from Step 4 with the IDs from Step 1.
Recall = (Number of matches in both sets) / (Total requested, e.g., 10)

If your recall is 0.7 (70%), and your budget requires 0.9 (90%), you must increase ef_search. If increasing ef_search pushes your latency above 100ms, you have two choices:

  1. Reduce the dimensionality of your vectors (e.g., use Matryoshka embeddings).
  2. Upgrade the CPU/RAM of the database instance.

What it costs, and when not to do it

Tuning pgvector is not free. There are three primary costs:

1. Memory Overhead

HNSW indexes must ideally fit in RAM (specifically within the filesystem cache or shared_buffers). If the index is 8GB and your RDS instance only has 4GB of RAM, PostgreSQL will swap to disk. In my experience, once an HNSW search hits the disk (EBS/SSD), latency spikes from ~20ms to >200ms. This is the most common "3am failure" where a background process ingests enough data to push the index out of memory, causing the entire site to crawl.

The Number: Expect HNSW to require approximately (4 * dimension + 8 * m) * rows bytes of memory. For 1M vectors at 1536 dimensions with m=24, that is roughly 6.1GB for the index alone, excluding the table data.

2. Build Time and Locking

Building an HNSW index on a large table is CPU-intensive and slow. On a 4-vCPU machine, 500k vectors can take 20-40 minutes to index. While CREATE INDEX can be run CONCURRENTLY, it still puts immense pressure on IOPS and CPU. Never trigger an index rebuild or a significant m change during peak traffic.

3. The "New Data" Problem

As you insert new rows, the HNSW graph updates. Over time, if the distribution of new data is significantly different from the initial data, the graph can become "suboptimal." You may see recall slowly degrade over months. A performance budget requires you to re-run your recall benchmarks weekly to detect this drift.

At your level

Starting out

If you are a student or a junior engineer, don't over-optimise early. Use the default HNSW settings. The one thing you should do next is run EXPLAIN ANALYZE on your search query. If you see "Seq Scan" in the output, your index isn't being used, and your app will break as soon as you have more than a few thousand rows. Check that your distance operator (<=> for cosine, <-> for L2) matches the operator used in your CREATE INDEX statement.

Working engineer

You own the service, so you must own the metrics. Do not trust "it feels fast." Implement a script that calculates recall against a ground-truth set of 100 queries. Set your hnsw.ef_search at the session level based on the specific needs of the query (e.g., a "high accuracy" research mode vs. a "fast" autocomplete mode).

Senior or staff

You own the architecture and the budget. Your task is to prevent the "RAM Cliff." Monitor the Buffer Cache Hit Ratio for your vector indexes. If it drops below 99%, you are hitting the disk, and your performance budget is already blown. You should also evaluate "Matryoshka" embeddings (supported by models like OpenAI text-embedding-3-small) which allow you to truncate vectors from 1536 to 256 dimensions with minimal recall loss, reducing your memory footprint by 80%.

Lead or director

You own the budget and the roadmap. Vector databases are expensive. An RDS instance with enough RAM to hold 10 million high-dimensional vectors in memory can cost thousands of pounds per month. Ensure your team is not just "making it faster" but is quantifying the cost-per-query. Ask the team: "What is our cost to maintain 95% recall at 5x our current data volume?" If the answer involves a linear increase in high-memory instances, it’s time to discuss dimensionality reduction or tiered storage strategies.

In the interview

The question

"Our vector search is getting slow as we add more users and data. How would you approach tuning it?"

The weak answer

"I would add an index like HNSW or IVFFlat. HNSW is a popular algorithm that makes things faster by creating a graph. I'd also look at upgrading the database instance to have more CPU."

Why it’s weak: It lacks specific constraints. It doesn't acknowledge that "fast" is meaningless without "recall." It treats the database as a black box rather than a resource-constrained system.

The strong answer

A strong answer identifies the three-way trade-off: Latency, Recall, and Memory.

"I'd first establish a performance budget—for example, 50ms latency at 90% recall. I'd use HNSW because it offers the best query-time performance for most production workloads. I’d tune m and ef_construction during index creation to ensure the graph is well-connected, then use hnsw.ef_search as a runtime lever to hit our latency target. Crucially, I'd monitor the index size to ensure it stays within the


Amit Chakraborty is a founding engineer and senior architect — React Native, AI/RAG systems and production architecture. Portfolio: www.amitchakraborty.dev · LinkedIn · GitHub. Open to senior and founding engineering roles, remote worldwide.

Top comments (0)