Why This Matters at Engineering Leadership Scale
Building a RAG prototype takes a weekend; building a multi-tenant RAG support system for 500 enterprise tenants under SOC 2 or APRA CPS 234 scrutiny is a serious distributed-systems challenge. One misconfigured vector filter leaking Bank A's policy into Bank B's answer is an existential security breach.
At L6/L7 engineering leadership scale, you must balance strict RBAC isolation, <1.5s p95 latency, accurate retrieval of exact error codes, and sane operational cost without running bloated dual-database sync pipelines.
Core Mental Model & Architecture
Anchor the design in concrete capacity and latency math upfront:
- Scale & SLOs: 500 tenants, 50k docs/tenant (25M docs), 500 QPS peak (~165 QPS avg),
p95 < 1.5s, strict RBAC + tenant isolation. - Storage Math: ~4 chunks/doc = 100M chunks. Using 1,536-dim
halfvec(float16, ~3 KB/vector) gives ~300 GB raw vectors; adding text,tsvector, and HNSW graph overhead (~2.5x) totals ~900 GB to 1.1 TB. - Latency Budget (1,500ms): Auth + query embedding (120ms) + hybrid DB search (60ms) + cross-encoder reranker (150ms) + LLM generation (850ms) = ~1,180ms with headroom.
| Storage Option | ACL & Tenant Isolation | Ops Overhead | Hybrid Search | Best Fit |
|---|---|---|---|---|
| Separate Vector DB + Postgres | Risky (dual-write ACL drift) | High (2 clusters + CDC) | Vendor-dependent | 1B+ vectors, loose ACLs |
Partitioned Postgres pgvector + tsvector | Strong (ACID + pre-filter + RLS) | Low (standard RDS) | Native (HNSW + GIN + RRF) | 10M to 250M chunks, strict RBAC |
Silo-Pool Hybrid (pgvector + VIP DB) | Strongest (physical VIP DB) | Moderate (routing table) | Native | Multi-tenant SaaS with skew |
Default to hash-partitioned Postgres + pgvector behind a tenant routing table so massive VIPs graduate to isolated silos cleanly.
Step-by-Step Implementation Tutorial
1. Separate Async Ingestion From Live Queries
Decouple chunking and embedding from live search so bulk uploads never spike query latency.
INGESTION (Async, Per-Tenant SQS):
S3 -> EventBridge -> Chunker (1024 parent / 256 child) -> Batch Embedder -> Atomic Postgres Upsert
QUERY (p95 < 1.5s):
API Gateway (JWT -> tenant_id + acl_roles[]) -> Redis Cache (rag:{tenant}:{role_hash}:{q_hash})
-> Pre-Filtered Hybrid Search (pgvector HNSW + tsvector BM25) -> RRF (Top 25)
-> Cross-Encoder Rerank (Top 5) -> Grounded LLM ([chunk_id] citations)2. Enforce Pre-Filtered RBAC and Hybrid RRF in SQL
Never post-filter ACLs after top-K vector search; unauthorized rows crowd out valid matches and risk leakage. Combine SQL pre-filtering with Postgres Row-Level Security (RLS).
CREATE TABLE chunks (
tenant_id UUID NOT NULL,
chunk_id UUID NOT NULL,
parent_id UUID NOT NULL,
content TEXT NOT NULL,
acl_roles TEXT[] NOT NULL,
embedding HALFVEC(1536) NOT NULL,
tsv TSVECTOR GENERATED ALWAYS AS (to_tsvector('english', content)) STORED,
PRIMARY KEY (tenant_id, chunk_id)
) PARTITION BY HASH (tenant_id);
-- Pre-filtered Hybrid Search with Reciprocal Rank Fusion (RRF)
WITH vec AS (
SELECT chunk_id, content, ROW_NUMBER() OVER (ORDER BY embedding <=> $3::halfvec) AS r
FROM chunks WHERE tenant_id = $1 AND acl_roles && $2::text[]
ORDER BY embedding <=> $3::halfvec LIMIT 40
),
lex AS (
SELECT chunk_id, content, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(tsv, plainto_tsquery('english', $4)) DESC) AS r
FROM chunks WHERE tenant_id = $1 AND acl_roles && $2::text[] AND tsv @@ plainto_tsquery('english', $4)
LIMIT 40
)
SELECT COALESCE(v.chunk_id, l.chunk_id) AS chunk_id,
COALESCE(v.content, l.content) AS content,
COALESCE(1.0 / (60 + v.r), 0) + COALESCE(1.0 / (60 + l.r), 0) AS rrf
FROM vec v FULL OUTER JOIN lex l USING (chunk_id)
ORDER BY rrf DESC LIMIT 25;3. Handle the Minute-25 Curveball: The 100M-Document VIP Bank
"A massive bank signs up with 100M documents (20x bigger than all other tenants) and demands zero noisy-neighbor latency impact."
Activate Silo-Pool Hybrid: keep the 499 standard tenants on the shared partitioned Postgres pool, provision a dedicated Postgres/pgvector instance + isolated SQS worker queue for the VIP bank, and update one row in tenant_routing_directory (tenant_id -> dsn). Zero code rewrite required.
4. Split Multi-Squad Ownership
- Squad A (Ingestion & Search Platform, 6 engineers): Owns S3 event pipelines, parent/child chunking, partitioned
pgvector+ hybrid RRF, and CI RAGAS faithfulness evals. - Squad B (AI Assistant Experience, 6 engineers): Owns query orchestration, tenant-scoped Redis semantic caching, reranking, inline
[chunk_id]citation UI, and prompt guardrails.
Worked Production Scenario: Before vs. After
An enterprise SaaS assistant initially synced Postgres permissions to a standalone vector DB via nightly batch jobs using vector-only retrieval. Exact regulatory codes (CPS-234-19) scored poorly, revoked docs remained searchable for up to 24 hours, and one client's PDF upload degraded search globally.
Migrating to partitioned Postgres pgvector + tsvector RRF, atomic ACL upserts, tenant-scoped Redis caching, and per-tenant SQS ingestion quotas fixed all three issues.
| Metric | Before (Separate Vector DB) | After (Hybrid pgvector + Pre-Filter) | Net Impact |
|---|---|---|---|
| ACL Revocation Lag | Up to 24 hours | <50ms (ACID transaction) | Zero stale-ACL exposure |
| Exact Error-Code Recall@5 | 58% | 94% (BM25 + Vector + Rerank) | +36 pts recall |
| Query p95 Latency (500 QPS) | 2.8s | 1.15s (32% Redis cache hit) | Meets <1.5s SLO |
| Monthly Vector Infra Cost | $6,400 / month | $2,350 / month | -63% TCO |
Common Failure Modes & Anti-Patterns
1. Omitting tenant_id and acl_roles From Cache Keys
The trap: Keying Redis semantic cache solely on hash(query) leaks Tenant A's cached answers to Tenant B.
The structural fix: Enforce strict keys rag:{tenant_id}:{sorted_role_hash}:{query_hash} plus automated CI cross-tenant isolation tests.
2. Vector-Only Search on Technical Support Docs
The trap: Dense embeddings miss exact invoice IDs, error codes, and SKU strings.
The structural fix: Always run hybrid retrieval (pgvector + tsvector BM25) merged via RRF and refined by a cross-encoder reranker.
3. Bulk Re-Indexing Starving Live Queries
The trap: A tenant re-indexes 50,000 PDFs, saturating primary DB write IOPS and pushing query p95 above 5 seconds. The structural fix: Enforce per-tenant SQS ingestion quotas and route live search queries to dedicated read replicas isolated from bulk write load.
How to Handle Pushback in the Room
Staff Engineer: "Postgres pgvector won't scale if we hit 100x growth next year. Why not use a dedicated distributed vector DB from Day 1?"
Calm Executive Response: "Our 3-year scale is 100M chunks (~1 TB on halfvec), which partitioned Postgres handles comfortably while keeping ACLs and embeddings ACID-consistent at 1/3 the on-call cost. Wrapping search behind a clean SearchRepository interface lets us swap to a specialized store via Strangler-Fig only if real volume ever crosses 500M chunks."
Security Officer: "How do you guarantee a developer bug cannot omit the tenant_id WHERE clause?"
Calm Executive Response: "Defense in depth: JWT claims set tenant_id at the API gateway, and Postgres Row-Level Security policies enforce tenant_id = current_setting('app.tenant_id') at the engine level so an unfiltered query returns zero cross-tenant rows."
Key Takeaways & This Week's Action Rep
- Keep ACLs and vectors transactional: Postgres
pgvectoreliminates dual-write security drift up to ~250M chunks. - Pre-filter every query and scope every cache key: Pair JWT-extracted SQL filters with Postgres RLS and tenant-scoped Redis keys.
- Hybrid search + reranking wins enterprise recall: Fuse
pgvectorandtsvectorvia RRF before top-5 reranking. - Design for skew with Silo-Pool Hybrid: Use a tenant routing table to isolate 100M-doc VIP banks cleanly.
- This Week's Action Rep: Run a 45-minute timed whiteboard walkthrough of this RAG design out loud, completing capacity math by Minute 8 and handling the 100M-doc VIP curveball at Minute 25.