Console Login

pgvector or a dedicated vector DB when HNSW outgrows RAM

The problem

You start a semantic search feature on PostgreSQL with pgvector, build an HNSW index, and queries return in a couple of milliseconds. Months later the table has grown, or the host is shared with other work, and the same query with the same plan is several times slower. Index builds that used to be quick now crawl. Nothing in the SQL changed. This article reproduces both symptoms in a sandbox and measures them.

The question behind it is whether it is time to leave pgvector for a dedicated vector database. I could only test the PostgreSQL side here, so I narrowed the scope: I did not install any dedicated vector database and I make no measured claim about one. What I can show is how pgvector behaves when the HNSW index outgrows memory, and which cheaper fixes exist before a migration.

Why it happens

An HNSW index is a graph. A query starts at an entry point and hops between neighbours, comparing the query against every vector it visits. Those vectors are stored inside the index pages, so the index carries a full copy of the embeddings plus neighbour lists; here the index is 781 MB against a 625 MB table. The hops jump around the file with little locality, so a query needs pages scattered across the whole index.

When the index fits in the page cache and shared buffers, those reads are memory hits. When it does not, each miss becomes a random disk read, and the operating system evicts pages the next query needs again. One query I inspected with EXPLAIN (ANALYZE, BUFFERS) touched 412 buffers of 8 kB, roughly 3 MB spread over the graph.

         Order By: (embedding <=> $0)
         Buffers: shared hit=411 read=1

Index builds have a second cliff. pgvector builds the graph in memory while it can and falls back to a much slower path once the graph exceeds maintenance_work_mem. The default of 64 MB is small next to a graph of hundreds of megabytes, so a build degrades long before the table looks big.

Reproducing the build cliff

I checked this first, using the setup described in the sandbox section below. The first index used default parameters (m 16, ef_construction 64) and the default maintenance_work_mem of 64 MB. I then dropped it and rebuilt it with SET maintenance_work_mem = '2GB'; in the session.

cat /work/build_small.sql
CREATE INDEX items_hnsw ON items USING hnsw (embedding vector_cosine_ops);
su postgres -c "psql -d vec -f /work/build_small.sql"
psql:/work/build_small.sql:4: NOTICE:  hnsw graph no longer fits into maintenance_work_mem after 28358 tuples
DETAIL:  Building will take significantly more time.
CREATE INDEX
Time: 333443.118 ms (05:33.443)
su postgres -c "psql -d vec -f /work/build_big.sql"
Time: 70495.905 ms (01:10.496)

The notice disappeared in the second build, which finished in about a fifth of the time. Both runs produced the same 781 MB index, so the only difference was whether the graph was assembled in memory, which is the effect the README describes.

Source of truth

The behaviour is documented in the pgvector README. The project is released under the PostgreSQL license; its LICENSE file carries the PostgreSQL Global Development Group copyright lines. I used tag v0.8.7 built from source. The README confirms four things that matter here.

  • Its FAQ on whether indexes must fit into memory answers: "No, but like other index types, you’ll likely see better performance if they do." It points to half-precision indexing or binary quantization for smaller indexes.
  • Builds are significantly faster when the graph fits into maintenance_work_mem, and a notice is raised when it no longer does.
  • Half-precision indexing is an expression index on embedding::halfvec(n).
  • Binary quantization is an expression index using binary_quantize, optionally re-ranked by the original vectors, and the README recommends it to keep indexes in memory at scale.

For the dedicated-database side I rely on vendor documentation only. Qdrant's optimization guide describes keeping vectors and the HNSW index on disk, or using quantization so more vectors stay in memory, and its memory tiers page advises against putting the HNSW index itself on the cold tier. For the memory limit I used the Linux cgroup v1 memory controller, and for load pgbench.

Approaches compared

Give PostgreSQL more memory

The simplest fix is to make the index fit: a larger machine, fewer neighbours on the host, or a better split between shared_buffers and the operating system cache. It changes no data or queries and keeps recall identical, but the memory needed grows with the row count and vertical scaling has a ceiling.

Shrink the index inside pgvector

Half-precision indexing stores two bytes per dimension instead of four, and binary quantization one bit. Both are expression indexes over the existing column, and binary quantization needs a re-ranking step that fetches heap rows. IVFFlat is another option: the README says it builds faster and uses less memory than HNSW, with a worse speed and recall trade-off. I did not test IVFFlat.

Move to a dedicated vector database

Dedicated engines add on-disk layouts, quantization with rescoring, and sharding across nodes. That helps when the data will not fit on one node even compressed. The price is a second system to operate and keep in sync. I did not test any of them, so the measurements below cover only the pgvector options.

Why this fix

I chose to shrink the index inside pgvector, starting with half-precision indexing. It is one statement, and because it is an expression index over the existing column it needs no table rewrite and can be dropped again if recall disappoints. The graph structure is the same as before, only the stored coordinates are narrower, so the risk is limited to a small loss of precision in distance calculations. That makes it the cheapest experiment that tests whether a smaller index restores latency.

I added binary quantization with re-ranking as the aggressive comparison, because it gives a far smaller index and shows where the heap becomes the next bottleneck. I did not test "just add RAM"; it stays a valid production answer when the index only just misses memory. I also left IVFFlat and a dedicated database out of the measurements, so the decision rule I use is empirical: keep the working index under the memory limit, and check recall afterwards.

Doing it in the sandbox

The environment

Everything below ran in a clean container provided by the sandbox, and I report only what the commands print. I make no claim about the storage behind the disk beyond the numbers I measured. The four commands below print the kernel, the distribution, the processor count and the memory.

uname -a
Linux vm 6.18.44-fc-v819 #1 SMP PREEMPT_DYNAMIC @0 x86_64 x86_64 x86_64 GNU/Linux
cat /etc/os-release
PRETTY_NAME="Ubuntu 24.04.5 LTS"
nproc
4
free -m
               total        used        free      shared  buff/cache   available
Mem:           16087         473       15668         152         318       15613

Installing PostgreSQL and pgvector

Ubuntu's package installed PostgreSQL 16 with pgvector 0.6.0, which predates the halfvec type and binary quantization that the project changelog lists as added in 0.7.0. I therefore built v0.8.7 from the repository over it and asked the database which version it runs.

apt-get install -y postgresql-16 postgresql-16-pgvector 2>&1 | tail -5
Setting up postgresql-16-pgvector (0.6.0-1) ...
git clone --depth 1 --branch v0.8.7 https://github.com/pgvector/pgvector.git
make install
su postgres -c "psql -d vec -Atc \"SELECT extversion FROM pg_extension WHERE extname='vector'\""
0.8.7

The data

Real embeddings were not available offline, so I generated 400,000 synthetic vectors of 384 dimensions with python3 gen.py: 2,000 random cluster centres plus Gaussian noise, normalised to unit length, and 200 query vectors from the same distribution. Before any index existed I computed the exact top 10 for every query with a sequential scan and stored it as ground truth for recall. Synthetic clusters differ from real embeddings, so the recall numbers apply only to this data.

Limiting memory with a cgroup

The sandbox has 16 GB, so the index would always be cached. To simulate a smaller host I used the cgroup v1 memory controller that this container exposes. A helper script stops PostgreSQL, drops the page cache, sets the limit, moves itself into the cgroup and starts PostgreSQL there, so the postmaster and its children inherit the limit. A second helper, bench.sh, restarts under a given limit and runs pgbench with one client for 60 seconds. It also records the block device read counter and the per-query latency log.

cat /work/knn.sql
\set qid random(1,200)
SELECT id FROM items ORDER BY embedding <=> (SELECT v FROM queries WHERE qid = :qid) LIMIT 10;

Baseline: the full-precision index

The index is 781 MB and the heap 625 MB. I ran the benchmark under limits of 1 GB, 512 MB and 256 MB. Each run starts cold, so the 60 seconds include warm-up, and the limit has to cover shared_buffers (128 MB) and the backends as well as the cache.

cd /work && for L in 1G 512M 256M; do echo "== limit $L"; ./bench.sh lim$L $L 60; done
== limit 1G
queries=37323  avg=1.6 ms  p50=1.4 ms  p95=2.8 ms  p99=4.2 ms  max=50.8 ms
disk read during run: 492 MiB
== limit 512M
queries=10216  avg=5.9 ms  p50=3.3 ms  p95=17.9 ms  p99=28.3 ms  max=113.6 ms
disk read during run: 7830 MiB
== limit 256M
queries=4315  avg=13.9 ms  p50=13.8 ms  p95=31.4 ms  p99=40.7 ms  max=64.4 ms
disk read during run: 8659 MiB

That is the failure. With a 1 GB limit the run read 492 MiB from disk once and then served from cache. At 512 MB, below the index size, the same workload read 7,830 MiB in 60 seconds and p95 rose from 2.8 ms to 17.9 ms. At 256 MB the average was 13.9 ms. The cache refilled continuously instead of warming once.

Fix one: a half-precision index

I built an expression index that casts to halfvec and left the table column as it was. The query must repeat the same cast so the planner can match the index; the benchmark script differs from the baseline only in that cast.

CREATE INDEX items_hnsw_half ON items USING hnsw ((embedding::halfvec(384)) halfvec_cosine_ops);
for L in 512M 256M; do echo "== halfvec limit $L"; SQLF=knn_half.sql ./bench.sh half$L $L 60; done
== halfvec limit 512M
queries=39823  avg=1.5 ms  p50=1.3 ms  p95=2.6 ms  p99=4.4 ms  max=48.3 ms
disk read during run: 664 MiB
== halfvec limit 256M
queries=5257  avg=11.4 ms  p50=11.4 ms  p95=24.8 ms  p99=31.7 ms  max=135.5 ms
disk read during run: 8843 MiB

The 446 MB index fits under the 512 MB limit, and latency returned to the level of the 1 GB run. At 256 MB it does not fit either and degrades much like the full index. The fix moves the cliff; it does not remove it.

Fix two: binary quantization with re-ranking

The binary index keeps one bit per dimension. The query takes 100 candidates by Hamming distance and re-ranks them by exact cosine distance against the stored vectors. My first benchmark left hnsw.ef_search at its default of 40 while asking for 100 candidates, which silently caps the list, so I discarded it and added SET hnsw.ef_search = 100; to the script before measuring again.

CREATE INDEX items_hnsw_bin ON items USING hnsw ((binary_quantize(embedding)::bit(384)) bit_hamming_ops);
su postgres -c "psql -d vec -c \"SELECT relname, pg_size_pretty(pg_relation_size(oid)) AS size FROM pg_class WHERE relname IN ('items','items_hnsw','items_hnsw_half','items_hnsw_bin') ORDER BY pg_relation_size(oid) DESC\""
 items_hnsw      | 781 MB
 items           | 625 MB
 items_hnsw_half | 446 MB
 items_hnsw_bin  | 133 MB
for L in 512M 256M; do echo "== binary+rerank ef100 limit $L"; SQLF=knn_bin.sql ./bench.sh bin2$L $L 60; done
== binary+rerank ef100 limit 512M
queries=28705  avg=2.1 ms  p50=1.9 ms  p95=3.3 ms  p99=4.9 ms  max=67.9 ms
disk read during run: 280 MiB
== binary+rerank ef100 limit 256M
queries=7146  avg=8.4 ms  p50=8.7 ms  p95=15.1 ms  p99=20.2 ms  max=116.1 ms
disk read during run: 7497 MiB

At 256 MB the 133 MB index is no longer the problem. Each query fetches 100 candidate rows from the 625 MB heap to re-rank them, and those random heap reads dominate, though this run still beat the other two indexes at that limit.

Checking recall

Latency means little if the answers got worse, so I measured recall at 10 against the exact results at two values of hnsw.ef_search. The full-precision index here is a second build with identical parameters, made after the first was dropped.

cd /work && for EF in 40 100; do for V in recall recall_half; do echo "ef_search=$EF file=$V"; (echo "SET hnsw.ef_search = $EF;"; cat $V.sql) > /tmp/r.sql; su postgres -c "psql -d vec -f /tmp/r.sql" | grep -E "^ +0\."; done; done
ef_search=40 file=recall
       0.8925
ef_search=40 file=recall_half
       0.8865
ef_search=100 file=recall
       0.9560
ef_search=100 file=recall_half
       0.9570

The half-precision index matched the full one within noise: the first full-precision build with the same parameters scored 0.9110 at ef_search 40, so two builds differed about as much as the half-precision index differed from either. The binary index, with ef_search 100 and 100 candidates re-ranked, scored 0.8235 against the same ground truth.

Limits and alternatives

This table gathers what I measured above. Latencies are in milliseconds, average and p95, from a single client with a cold start and 60 seconds per run. Recall is measured, for all three indexes, against the exact top 10 of the 200 queries.

IndexSize512 MB limit256 MB limitRecall at 10
vector, HNSW781 MB5.9 / 17.913.9 / 31.40.8925 (ef 40), 0.9560 (ef 100)
halfvec expression, HNSW446 MB1.5 / 2.611.4 / 24.80.8865 (ef 40), 0.9570 (ef 100)
binary plus re-rank, HNSW133 MB2.1 / 3.38.4 / 15.10.8235 (ef 100, 100 candidates)

What worked

The cliff is easy to reproduce: latency tracks whether the index fits in the memory available, not the row count. A half-precision expression index cut the index by about 43% and, on this data, kept recall while restoring latency under a 512 MB limit. Raising maintenance_work_mem cut the build from 5 minutes 33 seconds to 1 minute 10 seconds.

Limits of this experiment

This is one synthetic dataset, one client and one 60-second run per configuration with no repeats, so small gaps such as 1.5 versus 1.6 ms are noise. The cgroup limit counts page cache, shared buffers and backend memory together, which is not how every production host is set up. I never ran a dedicated vector database, and I did not test sharding, IVFFlat, a lower m or dimensionality reduction, so nothing here says where a migration pays off.

When to choose another method

Plain extra RAM is the right answer when the index only just misses memory. Binary quantization suits a tight memory budget where the recall drop is acceptable, but keep the heap in mind. A dedicated engine is worth evaluating when even a compressed index will not fit on one node, or when vector search needs its own scaling. Qdrant's documentation describes on-disk vectors and quantization for that case; benchmark your own data first.