Architecture & RAG • Published October 22, 2026 • Updated November 22, 2026 • 16 min read
Running RAG on PostgreSQL with pgvector: HNSW Indexing, Cosine Distance, and Query Tuning
A production database engineering guide to scaling pgvector: halfvec quantization, HNSW vs. IVFFlat parameter tuning, iterative filtered scans, parameterized Node.js pg queries, and RAM/autovacuum sizing.
By Saad R. (Head of AI Engineering) • Fact-Checked & Empirically Tested
Executive Summary: PostgreSQL with pgvector 0.8+ comfortably serves multi-million-chunk RAG workloads at sub-25ms p95 latency when engineered properly. Using 16-bit halfvec storage to halve index RAM, matching HNSW operator classes strictly to cosine distance (<=>), enabling iterative_scan for selective tenant filters, and sizing RAM so the HNSW graph never spills to disk IOPS eliminates the need for a separate external vector cluster.
Why Consolidating Vectors in PostgreSQL Eliminates Dual-Write Drift
Early RAG reference diagrams routinely placed PostgreSQL (storing workspaces, users, permissions, and raw documents) alongside a separate cloud vector database (storing embeddings and duplicated metadata). On paper that separation looks clean; in production operations, dual-datastore synchronization quickly becomes a persistent source of incidents:
- Ghost Vectors After Document Deletion: When a customer deletes a confidential PDF in Postgres and the background worker updating the external vector store hits a transient timeout, embeddings remain queryable via semantic search—a compliance and GDPR right-to-erasure violation.
- Stale RBAC & Metadata Drift: Updating a folder's visibility role from
publictointernal_onlyin Postgres requires backfilling metadata across thousands of external vector records asynchronously, creating an eventual-consistency window where unauthorized users still retrieve restricted chunks. - Operational Sprawl: Maintaining two backup schedules, two VPC peering paths, two connection pools, and cross-system reconciliation cron jobs slows shipping velocity.
Running pgvector directly inside PostgreSQL collapses document rows, ON DELETE CASCADE foreign keys, RBAC JOIN checks, lexical tsvector indexes, and vector search into single ACID transactions. For 95% of SaaS RAG workloads—ranging from 50,000 to 20,000,000 chunks—a right-sized PostgreSQL 17 instance with pgvector 0.8+ delivers 5ms–25ms p95 retrieval latency without distributed dual-write complexity. Architectural integration details for self-hosted and managed stores are documented in our Platform Documentation.
Schema Design: vector(768), halfvec, and JSONB Metadata
Vector RAM consumption determines your cloud database bill more than almost any other schema choice. A standard 32-bit floating-point vector(1536) column consumes 1536 4 + 8 = 6,152 bytes (~6 KB) per row before* HNSW graph edge pointers. Two modern pgvector capabilities cut that footprint dramatically with negligible accuracy loss:
- Matryoshka Dimension Shortening (
vector(768)orvector(1024)): Models trained with Matryoshka Representation Learning (text-embedding-3-large,gemini-embedding-001,nomic-embed-text-v1.5) pack coarse-to-fine variance into earlier dimensions. Truncating and L2-renormalizing1536or3072floats down to768dimensions cuts storage and distance math by 50–75% while retaining >98.5% retrieval recall. - 16-Bit Half-Precision Vectors (
halfvec): Introduced inpgvector 0.7+,halfvec(1536)stores IEEE-754 16-bit floats (2 bytesper dimension instead of4), cutting both heap vector size and HNSW index RAM in half while preserving >99.6% recall parity againstfloat32.
Relational Columns vs. JSONB Metadata
Never dump high-selectivity tenant filters (tenant_id, workspace_id, visibility_status) exclusively inside an unstructured JSONB blob. Promote mandatory multi-tenant isolation keys to native typed columns (UUID or BIGINT) backed by B-tree indexes or declarative list/hash partitioning, and reserve JSONB (GIN indexed with jsonb_path_ops) for optional user-defined tags ({"product": "billing", "region": "eu-central", "version": "v2"}). For ingestion metadata extraction best practices, see Training Chatbots on Documents.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE knowledge_documents (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL,
source_url TEXT NOT NULL,
title TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('draft', 'published', 'archived')),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE knowledge_chunks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL,
document_id UUID NOT NULL REFERENCES knowledge_documents(id) ON DELETE CASCADE,
chunk_index INT NOT NULL,
content_hash TEXT NOT NULL,
section_path TEXT NOT NULL,
content TEXT NOT NULL,
token_count INT NOT NULL,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
embedding halfvec(768) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (tenant_id, document_id, content_hash)
);
-- 1. Relational B-tree index for tenant scoping & document cascading deletes
CREATE INDEX idx_chunks_tenant_doc ON knowledge_chunks (tenant_id, document_id);
-- 2. Compact GIN jsonb_path_ops index for containment (@>) metadata filters
CREATE INDEX idx_chunks_metadata_gin ON knowledge_chunks USING gin (metadata jsonb_path_ops);
-- 3. HNSW index using 16-bit halfvec cosine distance operator class
CREATE INDEX idx_chunks_embedding_hnsw
ON knowledge_chunks
USING hnsw (embedding halfvec_cosine_ops)
WITH (m = 16, ef_construction = 128);
HNSW vs. IVFFlat: Parameters, Build Cost, and Trade-Offs
pgvector offers two Approximate Nearest Neighbor (ANN) index architectures: IVFFlat (Inverted File with Flat vectors) and HNSW (Hierarchical Navigable Small World). Understanding their internal data structures prevents painful re-indexing outages later. Core vector index terminology is also summarized in our RAG Glossary.
- IVFFlat runs k-means clustering during
CREATE INDEXto partition vectors intolistsVoronoi cells. At query time, Postgres computes distance to cell centroids and scans all vectors inside the closestivfflat.probescells. Critical catch: If you runCREATE INDEX USING ivfflaton an empty table during initial database migrations, k-means has zero centroids to learn—degrading accuracy permanently until you manuallyREINDEX! Furthermore, heavy data drift as new tenants onboard requires periodic index rebuilds. - HNSW constructs a multi-layered proximity graph where upper layers hold long-range highway edges and layer 0 holds dense local neighbor links. HNSW requires zero upfront training data (safe in empty migration scripts) and absorbs incremental
INSERT/UPDATEtraffic without degrading recall.
HNSW Tuning Levers
m(default16, typical range16–32): Maximum bi-directional links per node per layer. Highermimproves recall on high-dimensional data (1536+dims) and clustered distributions, but increases index RAM linearly and slows graph traversal per hop.m = 16is optimal for768d; step up tom = 24only when recall benchmarks plateau on1536d+.ef_construction(default64, recommended128–200): Size of the dynamic candidate queue evaluated while wiring edges at index build time. Raisingef_constructionfrom64to128lengthensCREATE INDEXwall-clock time by ~1.8x, improves graph quality permanently, and costs zero extra RAM or query-time latency.hnsw.ef_search(default40, query-time session GUC): Size of the candidate list maintained duringSELECTsearches. Must be>= LIMIT k. Raisingef_searchfrom40to80or100lifts Recall@10 from ~94%to98.5%+for only3ms–7msof extra CPU.
Index Configuration (2M 768d Chunks) | Recall@10 | p95 Query Latency | Index Build Time (8 vCPU) | Index Size in RAM | Handles Empty-Table Creation & Drift? |
|---|---|---|---|---|---|
| Exact Seq Scan (No Index) | 100.0% | 640ms | 0s | 0 MB | Yes (unusable latency at scale) |
IVFFlat (lists = 1400, probes = 25) | 92.4% | 19ms | 2.1 min | 6.1 GB | No — requires populated table & periodic REINDEX |
HNSW vector(768) (m=16, ef_c=64, ef_s=40) | 95.8% | 6.8ms | 11.4 min | 7.9 GB | Yes |
HNSW vector(768) (m=16, ef_c=128, ef_s=80) | 98.7% | 10.2ms | 19.8 min | 7.9 GB | Yes |
HNSW halfvec(768) (m=16, ef_c=128, ef_s=80) | 98.5% | 8.4ms | 14.2 min | 4.2 GB | Yes (Recommended Production Default) |
Cosine Distance Operators and Parameterized Node.js pg Queries
In pgvector, every distance operator binds strictly to a matching index operator class:
<=>(Cosine distance:d = 1 - cosine\_similarity, range $[0, 2]$) requiresvector_cosine_opsorhalfvec_cosine_ops.<->(Euclidean L2 distance) requiresvector_l2_ops/halfvec_l2_ops.<#>(Negative inner product for unit-normalized vectors) requiresvector_ip_ops/halfvec_ip_ops.
Two Subtle SQL Traps That Bypass HNSW Indexes
- Operator Mismatch: Building an index with
halfvec_cosine_opsand querying withORDER BY embedding <-> $1forces PostgreSQL to ignore the HNSW index completely and run a full sequential table scan. - Sorting by Similarity Expression Instead of Raw Distance: Writing
ORDER BY (1 - (embedding <=> $1::halfvec)) DESC LIMIT 10wraps the indexed operator inside an arithmetic expression! PostgreSQL's planner will not use the HNSW index unlessORDER BYreferences the bare operator expressionORDER BY embedding <=>1::halfvec ASC. Compute1 - (embedding <=>1::halfvec) AS similarityin theSELECTprojection list, never inORDER BY.
import pg from "pg";
const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
max: 25,
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 3_000,
});
function toVectorParam(floatArray) {
if (!Array.isArray(floatArray) || floatArray.length !== 768) {
throw new Error(`Expected 768-dim embedding array, got ${floatArray?.length}`);
}
for (let i = 0; i < floatArray.length; i++) {
if (!Number.isFinite(floatArray[i])) {
throw new Error(`Invalid non-finite float at embedding index ${i}`);
}
}
return `[${floatArray.join(",")}]`;
}
export async function queryTenantKnowledge({
tenantId,
embedding,
metadataFilter = null, // e.g. { product: "billing", version: "v2" }
topK = 8,
efSearch = 80,
minSimilarity = 0.52,
}) {
const vectorStr = toVectorParam(embedding);
const safeEf = Math.max(topK, Math.min(400, Math.trunc(efSearch)));
const client = await pool.connect();
try {
await client.query("BEGIN");
// SET LOCAL scopes GUCs strictly to this transaction—safe with PgBouncer transaction pooling!
await client.query(`SET LOCAL hnsw.ef_search = ${safeEf}`);
await client.query(`SET LOCAL hnsw.iterative_scan = 'relaxed_order'`);
const params = [tenantId, vectorStr, topK];
let metadataClause = "";
if (metadataFilter && Object.keys(metadataFilter).length > 0) {
params.push(JSON.stringify(metadataFilter));
metadataClause = `AND kc.metadata @> ${params.length}::jsonb`;
}
// Two-phase CTE: HNSW scan touches compact index/heap keys first,
// then fetches TOASTed content & document URLs only for top-K winners
const sql = `
WITH top_candidates AS (
SELECT
kc.id,
kc.document_id,
kc.section_path,
kc.token_count,
(kc.embedding <=> $2::halfvec(768)) AS distance
FROM knowledge_chunks kc
JOIN knowledge_documents kd ON kd.id = kc.document_id
WHERE kc.tenant_id = $1
AND kd.status = 'published'
${metadataClause}
ORDER BY kc.embedding <=> $2::halfvec(768) ASC
LIMIT $3
)
SELECT
tc.id,
tc.section_path,
kd.source_url,
kd.title AS document_title,
kc.content,
tc.token_count,
ROUND((1 - tc.distance)::numeric, 4) AS similarity
FROM top_candidates tc
JOIN knowledge_chunks kc ON kc.id = tc.id
JOIN knowledge_documents kd ON kd.id = tc.document_id
WHERE (1 - tc.distance) >= ${Number(minSimilarity)}
ORDER BY tc.distance ASC;
`;
const { rows } = await client.query(sql, params);
await client.query("COMMIT");
return rows;
} catch (err) {
await client.query("ROLLBACK");
throw err;
} finally {
client.release();
}
}
Pre-Filtering vs. Post-Filtering Pitfalls and Iterative Scans
Filtered vector search is where single-index HNSW architectures historically broke down in multi-tenant SaaS systems. Suppose knowledge_chunks holds 5,000,000 vectors across 2,000 customers, and tenant_small owns only 400 chunks (0.008% of the table):
- Classic Post-Filtering Failure (Under-Fetching): Without iterative scans, traversing a global HNSW index evaluates
hnsw.ef_search = 80global nearest neighbors and then checksWHERE tenant_id = 'tenant_small'. Statistically,0of those80global neighbors belong totenant_small—so your query returns 0 rows even thoughtenant_smallhas 400 perfectly relevant chunks! - Planner Flip to Pre-Filtering Slowdown: Conversely, if a tenant owns
120,000chunks and PostgreSQL's cost planner choosesidx_chunks_tenant_doc(B-tree pre-filter) instead of HNSW, Postgres must fetch120,000heap tuples from disk and compute exact768dcosine distance in CPU before sorting—spiking latency from9msto450ms.
Three Production Remedies by Scale Tier
- Enable
hnsw.iterative_scan(pgvector 0.8+): SettingSET LOCAL hnsw.iterative_scan = 'relaxed_order'(alongsidehnsw.max_scan_tuples = 20000) instructspgvectorto keep expanding HNSW graph traversal batches automatically untilLIMIT krows satisfy theWHEREfilter (ormax_scan_tuplesis reached), completely curing the empty-result post-filtering bug! - Hash or List Table Partitioning for Multi-Tenant SaaS: Partitioning
knowledge_chunksinto 32 or 64 hash partitions bytenant_id(PARTITION BY HASH (tenant_id)) gives PostgreSQL 32 smaller, independent HNSW indexes. Partition pruning immediately eliminates 96.8% of unrelated tenant vectors before HNSW graph entry, raising per-tenant density inside the surviving HNSW graph by 32x. - Partial HNSW Indexes for Whale Tenants: If three enterprise accounts represent 40% of query volume, create dedicated partial HNSW indexes (
CREATE INDEX CONCURRENTLY ... USING hnsw (embedding halfvec_cosine_ops) WHERE tenant_id = '...') for guaranteed single-tenant graph locality.
RAM Sizing Math, maintenance_work_mem, and Autovacuum
Unlike B-tree sequential range scans that benefit from predictable read-ahead prefetching, HNSW graph traversal jumps randomly across pointer edges. Once your active HNSW index exceeds available RAM (shared_buffers + OS page cache), random NVMe page faults push p95 query latency from 8ms past 180ms–400ms.
Concrete HNSW RAM Estimation Formula
For N vectors of dimension d with HNSW parameter m:
- Vector payload inside index:
N × (4d bytes for \texttt{vector}, or 2d bytes for \texttt{halfvec}) - Graph edge & tuple header overhead: roughly
N × (m × 2 × 6 + 56)bytes
For 5,000,000 chunks at 768 dimensions with m = 16:
vector(768)HNSW index≈ 5M × (3072 + 248) ≈ \mathbf{16.6 GB}halfvec(768)HNSW index≈ 5M × (1536 + 248) ≈ \mathbf{8.9 GB}
Provision an instance with at least 1.5x to 2.0x index size in total RAM (for example, a 16 GB–32 GB RAM Postgres node for 5M halfvec(768) rows) so shared_buffers (25%–35% of RAM) plus OS filesystem cache retain the entire HNSW graph alongside active B-tree/GIN indexes. Compare dedicated vector-SaaS pricing against self-managed/RDS Postgres memory tiers using our ROI & Token Calculator.
Index Build Speed & Autovacuum Settings
- Prevent Disk-Spill Builds: During
CREATE INDEX CONCURRENTLY, ifmaintenance_work_memis smaller than the emerging HNSW graph,pgvectorlogsNOTICE: hnsw graph no longer fits into maintenance_work_memand build speed drops by 5x–12x. Temporarily setSET maintenance_work_mem = '8GB';andSET max_parallel_maintenance_workers = 6;inside the migration session. - Aggressive Table-Level Autovacuum: PostgreSQL default
autovacuum_vacuum_scale_factor = 0.20waits until 20% of rows (1,000,000chunks on a 5M table!) are dead before vacuuming HNSW dead tuples. Override per table:
ALTER TABLE knowledge_chunks SET (
autovacuum_vacuum_scale_factor = 0.02,
autovacuum_analyze_scale_factor = 0.01,
autovacuum_vacuum_cost_limit = 2000
);
Debugging pgvector Query Plans and Production Bottlenecks
Whenever vector latency climbs or recall drops unexpectedly, run EXPLAIN (ANALYZE, BUFFERS) with realistic parameter values and inspect the execution tree against these four failure patterns:
1. Silent Fallback to Parallel Seq Scan
- Symptom: Query latency sits steadily at
320mson 1M rows regardless ofhnsw.ef_searchtuning. - Root Cause: Either the
embeddingcolumn lacks an explicit dimension modifier (halfvecinstead ofhalfvec(768)), the query parameter was cast to::vectoragainst ahalfvecindex (halfvec_cosine_ops), orORDER BYsorted on1 - (embedding <=> $2) DESC. - Debugging Step: Run
EXPLAIN (ANALYZE, BUFFERS)and verify the top node readsIndex Scan using idx_chunks_embedding_hnsw on knowledge_chunks(orCustom Scan/ iterative index scan) rather thanGather -> Parallel Seq Scan. Ensure$2::halfvec(768)matches the exact column type andORDER BYuses ascending<=>distance directly.
2. Buffer Read Thrashing (Buffers: shared hit=... read=...)
- Symptom: Average latency looks healthy (
14ms), but p99 spikes randomly to650msduring off-peak enterprise queries. - Root Cause: Nightly
pg_dumpbackups or analytical sequential queries evicted cold HNSW index pages from OS page cache, forcing synchronous disk reads (shared read=1840). - Debugging Step: Enable
track_io_timing = onand inspectI/O Timings: shared read=...inEXPLAIN (ANALYZE, BUFFERS). Use thepg_prewarmextension (SELECT pg_prewarm('idx_chunks_embedding_hnsw');) after instance restarts or upgrade instance RAM so the index stays hot.
3. PgBouncer Session GUC Leakage
- Symptom: Setting
SET hnsw.ef_search = 200on an admin analytics query slows down standard low-latency widget queries unpredictably, or throws PgBouncer warnings. - Root Cause: Executing bare
SET(session-scoped) instead ofSET LOCAL(transaction-scoped) mutates connection state returned to a PgBouncertransaction-mode pool, leakingef_searchacross unrelated requests. - Debugging Step: Grep application code for any
SET hnsw.orSET ivfflat.outsideBEGIN ... SET LOCAL ... COMMITblocks.
4. Blocking Writes During Index Rebuilds
- Symptom: Ingestion workers fail with lock timeouts for 18 minutes during a deployment migration.
- Root Cause: Running
CREATE INDEXorREINDEX INDEXwithoutCONCURRENTLYacquires aSHARElock that blocks everyINSERT,UPDATE, andDELETEonknowledge_chunks. - Debugging Step: Always run
CREATE INDEX CONCURRENTLYoutside transaction blocks in production migrations and setSET lock_timeout = '5s';on DDL scripts.
Frequently Asked Technical Questions
How many vectors can PostgreSQL with pgvector realistically handle before needing a dedicated vector database?
On a single vertical PostgreSQL 17 instance (such as 16 vCPU, 64 GB RAM) using halfvec(768) and hash partitioning by tenant_id, pgvector comfortably serves 15 million to 35 million chunks at sub-25ms p95 latency and several hundred queries per second. Dedicated distributed vector engines like Qdrant or Milvus become justified primarily when unpartitioned global searches exceed 50M–100M vectors or sustained query concurrency surpasses 1,500+ QPS.
Should we use cosine distance (<=>), L2 distance (<->), or inner product (<#>) for OpenAI and Gemini embeddings?
For unit-normalized embeddings (length = 1.0, standard for OpenAI text-embedding-3 at default dimensions and most modern SentenceTransformers), negative inner product (<#> with vector_ip_ops) is mathematically monotonic with cosine distance while saving two square-root vector norm computations per comparison. However, if you truncate dimensions or ingest unnormalized models, cosine distance (<=> with halfvec_cosine_ops) normalizes automatically and prevents magnitude bugs.
Does halfvec(1536) require changing how our Node.js or Python code generates embeddings?
No application embedding changes are needed. Your ingestion and query code still receive normal JavaScript Numbers or Python floats from the embedding provider API and serialize them as standard '[0.0123,-0.0451,...]' vector literals. Simply define the Postgres column as halfvec(1536), cast query parameters with $2::halfvec(1536), and PostgreSQL handles float32-to-float16 conversion and SIMD-accelerated distance math transparently.
Why did pgvector return only 3 rows when our SQL query asked for LIMIT 10?
This classic post-filtering under-fetch occurs on pgvector versions below 0.8—or when hnsw.iterative_scan is off—whenever a selective WHERE clause (like a small tenant_id or rare metadata tag) filters out almost all candidates inside the fixed hnsw.ef_search = 40 traversal window. Upgrade to pgvector 0.8+ and set SET LOCAL hnsw.iterative_scan = 'relaxed_order' so HNSW keeps scanning graph neighbors until 10 matching rows are found.