← All OpenAI & Gemini Vectorization Guides

OPTIMIZE 12 // PGVECTOR HNSW MULTI-TENANT TUNING

pgvector HNSW Tuning & Filtered Iterative Scans: Fixing Multi-Tenant Under-Return (< k Rows)

Prior to pgvector 0.8.0, combining an HNSW ORDER BY <=> LIMIT k query with a selective WHERE tenant_id = $1 filter applied post-filtering over a fixed ef_search candidate pool, routinely returning 0 to 3 rows when a tenant owned < 1% of the table. Enabling hnsw.iterative_scan = relaxed_order with tuned max_scan_tuples fixes multi-tenant recall, while Voxell Forge enforces fail-closed tenant isolation natively.

Anatomy of the Multi-Tenant Post-Filtering Bug

In a shared 10,000,000-row SaaS table (doc_chunks) with 500 tenants:

  • Tenant A (40% of rows): ef_search = 40 global candidates yields ~16 valid rows -> looks fine in staging.
  • Tenant B (0.2% of rows = 20,000 chunks): ef_search = 40 global candidates yields zero rows ([]) even though Tenant B has 20,000 valid documents! Or worse, PostgreSQL’s cost planner abandons HNSW entirely and falls back to a 4,200 ms sequential heap scan over 20,000 wide halfvec tuples.

Three-Tier Multi-Tenant pgvector 0.8.0+ Architecture

Choose your indexing pattern based on tenant selectivity and tenant cardinality:

Tenant Skew Tier Selectivity (rows / total) Optimal pgvector 0.8.0+ Strategy P95 Query Latency (10M Rows) Recall@20
Large Tenants > 5% of table Shared HNSW + iterative_scan = relaxed_order 11 - 24 ms 98.6%
Mid-Sized Tenants 0.1% - 5% of table Shared HNSW + relaxed_order + max_scan_tuples = 20000 18 - 58 ms 97.4%
Micro Tenants (< 2,500 vecs) < 0.025% of table Composite B-tree (tenant_id, id) exact scan (faster than graph!) 3 - 9 ms 100.0% (Exact)
Whale Enterprise Tenants Dedicated SLA Partial HNSW index WHERE tenant_id = '...' or list partition 6 - 14 ms 99.2%
Voxell Forge Spaces / Corpora Any tenant distribution Fail-closed namespace + 64-bit CUDA AMQ pre-filter 87 ms P50 end-to-end 99.04% (0.8849 w/ Max)

Runnable SQL: Fast Index Build + pgvector 0.8.0 Iterative Scan Session Wrapper

-- 1. Build-time tuning: prevent disk spill during HNSW graph construction!
-- PostgreSQL logs a NOTICE if the graph exceeds maintenance_work_mem.
BEGIN;
SET LOCAL maintenance_work_mem = '32GB';
SET LOCAL max_parallel_maintenance_workers = 7;

CREATE INDEX idx_chunks_tenant_btree ON doc_chunks (tenant_id);
CREATE INDEX idx_chunks_emb_hnsw
  ON doc_chunks
  USING hnsw (embedding halfvec_cosine_ops)
  WITH (m = 16, ef_construction = 128);
COMMIT;

-- 2. Query-time multi-tenant transaction wrapper (pgvector >= 0.8.0)
BEGIN;
SET LOCAL hnsw.ef_search = 80;
SET LOCAL hnsw.iterative_scan = relaxed_order;
SET LOCAL hnsw.max_scan_tuples = 25000;   -- Cap worst-case graph walk on empty-match queries
SET LOCAL hnsw.scan_mem_multiplier = 2;   -- Allow work_mem headroom for visited-set bitmaps

-- Optional materialization wrapper so relaxed_order re-sorts exact cosine at top-20:
WITH candidates AS MATERIALIZED (
  SELECT id, title, body, (embedding <=> $1::halfvec(3072)) AS dist
  FROM doc_chunks
  WHERE tenant_id = $2
  ORDER BY embedding <=> $1::halfvec(3072)
  LIMIT 20
)
SELECT id, title, body, 1 - dist AS cosine_similarity
FROM candidates
ORDER BY dist ASC;
COMMIT;

Eliminating Planner Flip-Flops With Fail-Closed GPU Isolation

Even on pgvector 0.8.0, PostgreSQL’s planner periodically misestimates compound predicates (WHERE tenant_id = $2 AND acl_role = ANY($3) AND effective_date <= $4), flipping between slow B-tree bitmap scans and capped max_scan_tuples walks under vacuum churn.

Voxell Forge isolates corpora and Spaces fail-closed at the storage and Play 1 64-bit CUDA Cuckoo AMQ layer, sustaining 87 ms P50 dense retrieval (99.04% Recall@20) and 0.8849 nDCG@10 Stage-2 reranking without DBA maintenance_work_mem babysitting (from $39/mo annual; $0 reader and MCP agent seats). Verify live right now:

curl -sS -X POST https://api.voxell.ai/api/v1/agent/bakeoff \
  -H "Content-Type: application/json" \
  -d '{
    "documents": [
      {"name": "pgvector-070.md", "text": "Prior to pgvector 0.8.0, HNSW post-filtering over ef_search=40 could return fewer than k rows on selective WHERE predicates."},
      {"name": "pgvector-080.md", "text": "pgvector 0.8.0 introduced hnsw.iterative_scan = relaxed_order and hnsw.max_scan_tuples to expand filtered graph walks."}
    ],
    "queries": ["Which pgvector 0.8.0 setting prevents HNSW filtered queries from returning fewer than k rows?"]
  }'

Size your Postgres instance RAM in the Vector RAM & TCO Calculator, compare Zero-Seat-Tax Enterprise Spaces, or open the Forge Console (v4.0 Pricing).

Frequently Asked Questions

Why did my pgvector query return only 2 rows when LIMIT 20 was requested and the tenant has 5,000 rows?

Standard HNSW graph traversal evaluates ef_search (default 40) nearest neighbors globally across all tenants first, then discards rows failing WHERE tenant_id = $1. If that tenant represents 0.5% of a 10M-row table, 40 global candidates statistically yield ~0.2 matching rows!

Should I use strict_order or relaxed_order for pgvector hnsw.iterative_scan?

Use SET LOCAL hnsw.iterative_scan = relaxed_order in almost all RAG workloads. relaxed_order lets pgvector keep expanding the HNSW graph search batch-by-batch until LIMIT k matching rows are found with minimal CPU overhead, achieving 95%-99% recall at 2x-4x lower latency than strict_order.

How do I stop CREATE INDEX USING hnsw from taking 9 hours on 10M vectors?

HNSW graph construction slows down 10x-30x the instant the working graph spills past maintenance_work_mem to disk. Raise SET LOCAL maintenance_work_mem = '16GB' (or larger than the target index size) and SET LOCAL max_parallel_maintenance_workers = 7 before running CREATE INDEX.

AUTONOMOUS AGENT & DEVELOPER VERIFICATION // ZERO SIGNUP

Run a live keyless bake-off right now

Do not take a vendor table on faith. Run your own passages and queries against Voxell Forge (Pro 2560d + C_corpus zero-LLM ingest dialect conditioning + Max two-stage neural reranking) over REST or Zero-Install Remote Streamable HTTP MCP with zero API key.

1. REST Retrieval Bake-Off & Corpus X-Ray
curl -sS -X POST https://api.voxell.ai/api/v1/agent/bakeoff \
  -H "Content-Type: application/json" \
  -d '{
    "documents": [
      {"name": "policy-a.md", "text": "Standard subscriptions include a 30-day refund window."},
      {"name": "msa-b.md", "text": "Enterprise annual contracts carry a 14-day cancellation notice rule."}
    ],
    "queries": ["What is the standard subscription refund window?"]
  }'

curl -sS -X POST https://api.voxell.ai/api/v1/agent/xray \
  -H "Content-Type: application/json" \
  -d '{
    "documents": [
      {"name": "sla-2025.md", "text": "P1 response SLA is 4 hours."},
      {"name": "sla-2026.md", "text": "P1 response SLA is 15 minutes."}
    ]
  }'
2. Zero-Install Remote HTTP MCP (POST /mcp/try)
claude mcp add --transport http voxell-forge https://api.voxell.ai/mcp/try
# mcp.json: {"mcpServers":{"voxell-forge":{"url":"https://api.voxell.ai/mcp/try"}}}

curl -sS -X POST https://api.voxell.ai/mcp/try \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "forge_bakeoff_compare",
      "arguments": {
        "documents": [
          {"name": "vpc.md", "text": "Forge Local runs on 1x 24 GB GPU inside your Sovereign VPC with zero egress."}
        ],
        "queries": ["How many GPUs does Forge Local require?"]
      }
    }
  }'
# Tools exposed: forge_bakeoff_compare, forge_xray_audit