I am indexing a table with 2,000,000 vectors (1,536 dimensions, OpenAI text-embedding-3-small) in PostgreSQL 16 using the pgvector extension. When executing:
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);The query runs for 45 minutes, consumes all 32 GB of system RAM, and is terminated by the Linux OOM Killer: server closed the connection unexpectedly (Signal 9 / SIGKILL). Why does HNSW indexing consume so much RAM in PostgreSQL, and how should database parameters be tuned to successfully build vector indexes on large datasets without crashing?
Direct Technical Solution: Unlike IVFFlat (which partitions vector spaces with k-means centroids), HNSW (Hierarchical Navigable Small World) constructs a multi-layer proximity graph in physical RAM during build time. For 2,000,000 vectors with 1,536 dimensions, the raw vectors alone occupy
2,000,000 × 1,536 × 4 bytes = 12.28 GB. Adding the HNSW graph neighbor connectivity lists (with m=16) increases total build RAM requirement to approximately 18 to 22 GB.1. The Formula to Calculate Required `maintenance_work_mem`
2. PostgreSQL Configuration Tuning
Temporarily allocate sufficient RAM to the session before triggering the index build, and utilize parallel CPU worker cores to accelerate graph edge exploration:
3. When to Use IVFFlat vs HNSW