ChatCraft

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 public to internal_only in 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:

  1. Matryoshka Dimension Shortening (vector(768) or vector(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-renormalizing 1536 or 3072 floats down to 768 dimensions cuts storage and distance math by 50–75% while retaining >98.5% retrieval recall.
  2. 16-Bit Half-Precision Vectors (halfvec): Introduced in pgvector 0.7+, halfvec(1536) stores IEEE-754 16-bit floats (2 bytes per dimension instead of 4), cutting both heap vector size and HNSW index RAM in half while preserving >99.6% recall parity against float32.

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 INDEX to partition vectors into lists Voronoi cells. At query time, Postgres computes distance to cell centroids and scans all vectors inside the closest ivfflat.probes cells. Critical catch: If you run CREATE INDEX USING ivfflat on an empty table during initial database migrations, k-means has zero centroids to learn—degrading accuracy permanently until you manually REINDEX! 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 / UPDATE traffic without degrading recall.

HNSW Tuning Levers

  • m (default 16, typical range 16–32): Maximum bi-directional links per node per layer. Higher m improves recall on high-dimensional data (1536+ dims) and clustered distributions, but increases index RAM linearly and slows graph traversal per hop. m = 16 is optimal for 768d; step up to m = 24 only when recall benchmarks plateau on 1536d+.
  • ef_construction (default 64, recommended 128–200): Size of the dynamic candidate queue evaluated while wiring edges at index build time. Raising ef_construction from 64 to 128 lengthens CREATE INDEX wall-clock time by ~1.8x, improves graph quality permanently, and costs zero extra RAM or query-time latency.
  • hnsw.ef_search (default 40, query-time session GUC): Size of the candidate list maintained during SELECT searches. Must be >= LIMIT k. Raising ef_search from 40 to 80 or 100 lifts Recall@10 from ~94% to 98.5%+ for only 3ms–7ms of extra CPU.
Index Configuration (2M 768d Chunks)Recall@10p95 Query LatencyIndex Build Time (8 vCPU)Index Size in RAMHandles Empty-Table Creation & Drift?
Exact Seq Scan (No Index)100.0%640ms0s0 MBYes (unusable latency at scale)
IVFFlat (lists = 1400, probes = 25)92.4%19ms2.1 min6.1 GBNo — requires populated table & periodic REINDEX
HNSW vector(768) (m=16, ef_c=64, ef_s=40)95.8%6.8ms11.4 min7.9 GBYes
HNSW vector(768) (m=16, ef_c=128, ef_s=80)98.7%10.2ms19.8 min7.9 GBYes
HNSW halfvec(768) (m=16, ef_c=128, ef_s=80)98.5%8.4ms14.2 min4.2 GBYes (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]$) requires vector_cosine_ops or halfvec_cosine_ops.
  • <-> (Euclidean L2 distance) requires vector_l2_ops / halfvec_l2_ops.
  • <#> (Negative inner product for unit-normalized vectors) requires vector_ip_ops / halfvec_ip_ops.

Two Subtle SQL Traps That Bypass HNSW Indexes

  1. Operator Mismatch: Building an index with halfvec_cosine_ops and querying with ORDER BY embedding <-> $1 forces PostgreSQL to ignore the HNSW index completely and run a full sequential table scan.
  2. Sorting by Similarity Expression Instead of Raw Distance: Writing ORDER BY (1 - (embedding <=> $1::halfvec)) DESC LIMIT 10 wraps the indexed operator inside an arithmetic expression! PostgreSQL's planner will not use the HNSW index unless ORDER BY references the bare operator expression ORDER BY embedding <=> 1::halfvec ASC. Compute 1 - (embedding <=>1::halfvec) AS similarity in the SELECT projection list, never in ORDER 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 = 80 global nearest neighbors and then checks WHERE tenant_id = 'tenant_small'. Statistically, 0 of those 80 global neighbors belong to tenant_small—so your query returns 0 rows even though tenant_small has 400 perfectly relevant chunks!
  • Planner Flip to Pre-Filtering Slowdown: Conversely, if a tenant owns 120,000 chunks and PostgreSQL's cost planner chooses idx_chunks_tenant_doc (B-tree pre-filter) instead of HNSW, Postgres must fetch 120,000 heap tuples from disk and compute exact 768d cosine distance in CPU before sorting—spiking latency from 9ms to 450ms.

Three Production Remedies by Scale Tier

  1. Enable hnsw.iterative_scan (pgvector 0.8+): Setting SET LOCAL hnsw.iterative_scan = 'relaxed_order' (alongside hnsw.max_scan_tuples = 20000) instructs pgvector to keep expanding HNSW graph traversal batches automatically until LIMIT k rows satisfy the WHERE filter (or max_scan_tuples is reached), completely curing the empty-result post-filtering bug!
  2. Hash or List Table Partitioning for Multi-Tenant SaaS: Partitioning knowledge_chunks into 32 or 64 hash partitions by tenant_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.
  3. 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, if maintenance_work_mem is smaller than the emerging HNSW graph, pgvector logs NOTICE: hnsw graph no longer fits into maintenance_work_mem and build speed drops by 5x–12x. Temporarily set SET maintenance_work_mem = '8GB'; and SET max_parallel_maintenance_workers = 6; inside the migration session.
  • Aggressive Table-Level Autovacuum: PostgreSQL default autovacuum_vacuum_scale_factor = 0.20 waits until 20% of rows (1,000,000 chunks 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 320ms on 1M rows regardless of hnsw.ef_search tuning.
  • Root Cause: Either the embedding column lacks an explicit dimension modifier (halfvec instead of halfvec(768)), the query parameter was cast to ::vector against a halfvec index (halfvec_cosine_ops), or ORDER BY sorted on 1 - (embedding <=> $2) DESC.
  • Debugging Step: Run EXPLAIN (ANALYZE, BUFFERS) and verify the top node reads Index Scan using idx_chunks_embedding_hnsw on knowledge_chunks (or Custom Scan / iterative index scan) rather than Gather -> Parallel Seq Scan. Ensure $2::halfvec(768) matches the exact column type and ORDER BY uses ascending <=> distance directly.

2. Buffer Read Thrashing (Buffers: shared hit=... read=...)

  • Symptom: Average latency looks healthy (14ms), but p99 spikes randomly to 650ms during off-peak enterprise queries.
  • Root Cause: Nightly pg_dump backups 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 = on and inspect I/O Timings: shared read=... in EXPLAIN (ANALYZE, BUFFERS). Use the pg_prewarm extension (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 = 200 on an admin analytics query slows down standard low-latency widget queries unpredictably, or throws PgBouncer warnings.
  • Root Cause: Executing bare SET (session-scoped) instead of SET LOCAL (transaction-scoped) mutates connection state returned to a PgBouncer transaction-mode pool, leaking ef_search across unrelated requests.
  • Debugging Step: Grep application code for any SET hnsw. or SET ivfflat. outside BEGIN ... SET LOCAL ... COMMIT blocks.

4. Blocking Writes During Index Rebuilds

  • Symptom: Ingestion workers fail with lock timeouts for 18 minutes during a deployment migration.
  • Root Cause: Running CREATE INDEX or REINDEX INDEX without CONCURRENTLY acquires a SHARE lock that blocks every INSERT, UPDATE, and DELETE on knowledge_chunks.
  • Debugging Step: Always run CREATE INDEX CONCURRENTLY outside transaction blocks in production migrations and set SET 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.

Related Engineering Guides