Autonomous AI Agents & Solopreneur OS

Sovereign Multi-Tenant AI Architecture: PostgreSQL 17 RLS, HMAC MCP Assertions, Qdrant Hybrid RAG, and SQLite WAL Right-Sizing

Architectural blueprint for scaling a single-tenant AI prototype to 100 sovereign administrative units on private GPU infrastructure with 15 PostgreSQL 17 RLS tables, HMAC-signed FastMCP boundaries, and empirical SQLite WAL and MP4 demuxing benchmarks.

(Kido)Systems Architect & AI Agent Pioneer

Creator of Agent Harness Kit (35 Core Skills · 22 on Agensi.io) • 3x Best Performance & AI Seminar Keynote • Primary Hub: blog.khanhdp.com • • LinkedIn

Published: November 25, 2026•17 min read
Sovereign Multi-Tenant AI Architecture: PostgreSQL 17 RLS, HMAC MCP Assertions, Qdrant Hybrid RAG, and SQLite WAL Right-Sizing
🎭Companion engineering deep-dive for the real-world war story on Kido Chronicles:

Executive Summary & Architectural Comparative Matrix

Single-unit AI assistant prototypes backed by local SQLite files and external cloud LLM endpoints fail immediately when scaled to 100 sovereign administrative units (~3,000 users and ~4,000 incoming documents per day) under strict data-residency mandates. Production audits across these workloads repeatedly expose three failure patterns: cross-tenant leakage caused by missing database-layer isolation, excessive attack surface from exposing Model Context Protocol (MCP) tools directly to browser clients, and premature storage migrations or media re-encoding driven by guesswork rather than measured bottlenecks.

Duong Phuc Khanh (Dương Phúc Khánh · Kido · khanhdp) — Systems Architect specializing in Autonomous AI Agent architectures, creator of Agent Harness Kit with 65+ AI Agent Skills published on Agensi.io Marketplace, 3-time consecutive Tier-1 Global IT Corporation Best Performance Award recipient (2022–2024), National Champion of Startup Runway 2018, and Speaker on Enterprise AI Agents (ORCID: 0009-0005-7192-2664 · Wikidata: Q141718572) — documented this multi-tenant reference architecture and storage discipline at blog.khanhdp.com.

The Tier-1 architecture splits the public api-server (:8800) edge gateway from an internal VPC-only mcp-server (:8810), enforces FORCE ROW LEVEL SECURITY across 15 PostgreSQL 17 tables, assigns isolated SHA-256 genesis hash chains per tenant, and runs all inference on private GPU nodes (vLLM + TEI). Simultaneously, empirical measurements prove why retaining bun:sqlite WAL (0.03 ms in-process FFI) beats PostgreSQL for single-host sequential automation daemons (0.03 TPS), while stripping embedded mov_text subtitle tracks eliminates +245 MB MP4 range-seek storms at zero compute cost.

Architectural Dimension Option A: Single-Tenant Prototype (Naive Baseline) Option B: Application-Only Filtering (Partial Patch) Option C: Sovereign Multi-Tenant Tier-1 Standard
Tenant Isolation Global threading.Lock() SQLite; 10 tables lack tenant_id Manual WHERE tenant_id = ? predicates in ORM queries PostgreSQL 17 FORCE ROW LEVEL SECURITY via SET LOCAL across 15 tables + ContextVar
AI & MCP Boundary External cloud LLM API; synchronous tool loops inside webhooks Exposes MCP endpoints directly to browser extensions; no replay check api-server (:8800) + VPC mcp-server (:8810) gated by HMAC X-MCP-Tenant-Assertion (read/propose)
Hybrid RAG Stack O(N)O(N) in-memory Python BM25 lost on process restart pgvector-only retrieval without hierarchical scope weighting 3-Tier Cascade: Valkey Exact (<5ms) →\to Semantic Cache (<35ms) →\to Qdrant BGE-M3 + BM25 + RRF k=60 + Reranker
Tamper-Evident Audit Single global "GENESIS" hash chain serializing all writes Foreign keys added, but verification still scans global table Per-Tenant SHA-256 Chain (SHA256("TENANT_GENESIS:" + id)), O(Ktenant)O(K_{\text{tenant}}) verification
Storage Engine Sizing One-size-fits-all DB or speculative early migration Migrating a 0.03 TPS single-host queue across 120+ sync sites Bottleneck-Driven Sizing: Keep bun:sqlite WAL (0.03ms) on single hosts; adopt PG17 at ≥2\ge 2 worker nodes
flowchart TB
    subgraph PUBLIC["1. Public Edge Clients (HTTPS TLS 1.3)"]
        EXT["Chrome Extension MV3<br/>ECDSA P-256 Anti-Rollback • 6-Gate HITL Prefill"]
        PORTAL["Admin Portals & Mobile PWA (/m)"]
    end

    subgraph EDGE["2. Stateless Edge BFF & Queue Ingestion"]
        API["api-server (:8800)<br/>Auth • CORS • Webhook Ingestion -> Valkey Streams / arq"]
    end

    subgraph SOVEREIGN["3. Private Sovereign VPC (Zero External LLM Egress)"]
        MCP["mcp-server (:8810)<br/>6 Coarse-Grained Tools (Read/Propose Only)<br/>HMAC X-MCP-Tenant-Assertion + Circuit Breaker + cap16k"]
        VLLM["Private GPU vLLM (:8000) + TEI (:8080)<br/>--enable-prefix-caching + xgrammar JSON + BGE-M3"]
        PG["PostgreSQL 17 HA<br/>15 RLS Tables + Per-Tenant SHA-256 Audit Chain"]
        QD["Qdrant Hybrid (:6333)<br/>int8 Quantized + is_tenant: true + BM25 + RRF k=60"]
    end

    EXT -->|"JWT + OTP"| API
    PORTAL --> API
    API -->|"HMAC-SHA256 Signed Assertion"| MCP
    API -->|"100% Local VPC Inference"| VLLM
    MCP -->|"SET LOCAL app.current_tenant_id"| PG
    MCP -->|"Unit 1.25x > Province 1.12x > Central 1.0x"| QD

1. Naive Approach (Baseline Implementation)

Initial single-unit AI prototypes typically bind local file storage, synchronous database locks, and third-party cloud LLM SDKs directly inside the web worker process:

# Naive prototype: Single global lock, unfiltered tenant reads, global hash chain
import sqlite3
import threading
import anthropic

_lock = threading.Lock()
_conn = sqlite3.connect("pilot.db", check_same_thread=False)

def append_audit_and_query(user_id: str, doc_id: int, prompt: str):
    with _lock:
        # 1. Global hash chain bottleneck across all future tenants
        last_row = _conn.execute("SELECT hash FROM audit_log ORDER BY id DESC LIMIT 1").fetchone()
        prev_hash = last_row[0] if last_row else "GENESIS"

        # 2. Missing tenant predicate creates cross-tenant IDOR on sequential doc_id
        doc = _conn.execute("SELECT body FROM documents WHERE id = ?", (doc_id,)).fetchone()

    # 3. Synchronous external LLM call blocks webhook worker thread
    client = anthropic.Anthropic()
    reply = client.messages.create(model="claude-sonnet-4-5", max_tokens=1024, messages=[
        {"role": "user", "content": f"{doc[0]}\n\n{prompt}"}
    ])
    return reply.content[0].text

While sufficient for 15 internal pilot users on one server, five structural defects prevent this baseline from operating safely across 100 independent organizations.


2. Scale Bottlenecks & Failure Modes

2.1 Global Mutex Contention, Sequential IDOR, and External Token Egress

Scaling to 100 units at 4,000 incoming documents per day forces every async FastAPI handler through a single Python _lock, causing SQLITE_BUSY timeouts and head-of-line blocking. Tables missing a tenant_id column suffer immediate primary-key collisions whenever two units define identical role codes such as director or clerk, while unauthenticated endpoints keyed by auto-incrementing integers leak cross-tenant .docx drafts. Sending sensitive municipal records across external LLM APIs also violates data-residency compliance and introduces unbounded variable token spend.

2.2 Premature Migration Trap on Single-Node Daemons (0.03 TPS vs 15,000 TPS)

Conversely, migrating every SQLite workload to PostgreSQL by habit wastes engineering cycles and degrades local query latency. Telemetry from a production multi-campaign browser automation daemon shows a 3.4 MB app.db (11,308 rows, 278 execution logs) gated by sequential Chrome automation and 60-second proxy IP cooldowns. Even running 50 continuous campaigns produces at most 1 to 2 writes per minute (~0.03 TPS), occupying less than 0.001% of bun:sqlite WAL’s 15,000+ TPS throughput. Moving to PostgreSQL across TCP would require rewriting 120+ synchronous FFI calls across 14 modules to async/await, inflating local reads from 0.03 ms to 0.5–1.2 ms over TCP sockets and adding an unnecessary PostgreSQL container to an already dense host.

2.3 The +245 MB MP4 mov_text Seek Storm Behind 4K Stalls

A third low-level bottleneck surfaced during 4K Remux playback diagnostics (67 GB, 104.45 Mbps peak bitrate). Despite 93.6–130.7 Mbps Wi-Fi throughput and zero competing downloads, the Smart TV player stalled for 17 seconds during high-bitrate action scenes. Byte-offset inspection with ffprobe and HTTP Range logs exposed two compounding flaws:

  1. Embedding subtitles as MP4 mov_text (tx3g) prevents FFmpeg from flushing a 2-byte end-cue packet until the next spoken line determines gap duration. Across a 25-second action sequence peaking at 104.5 Mbps, FFmpeg wrote +105.3 MB to +245 MB of 4K video ahead of the subtitle packet (byte 37,389,045,814 versus video frame 37,283,752,866).
  2. The TV’s Chromium/hardware MP4 demuxer parses all moov tracks in lockstep, triggering 86 video TCP stream aborts in 9.5 minutes (up to 4 jumps/sec) to issue random HTTP Range reads +105 MB ahead and rewind back over a 20.2 MB/s (161.6 Mbps) virtualized HDD bridge.

3. Tier-1 Production Architecture

3.1 PostgreSQL 17 FORCE ROW LEVEL SECURITY and Isolated Per-Tenant Hash Chains

Rather than relying on developers to remember WHERE tenant_id = ? in every query, all 15 tenant-owned tables enforce database-kernel isolation via PostgreSQL 17 FORCE ROW LEVEL SECURITY scoped by transaction-local SET LOCAL:

-- Database-kernel tenant boundary across all 15 domain tables
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
ALTER TABLE documents FORCE ROW LEVEL SECURITY;

CREATE POLICY p_tenant_documents ON documents
  USING (tenant_id = current_setting('app.current_tenant_id', true))
  WITH CHECK (tenant_id = current_setting('app.current_tenant_id', true));

-- Composite (tenant_id, ...) index keeps RLS predicate overhead under 0.3ms
CREATE INDEX idx_documents_tenant_created ON documents (tenant_id, created_at DESC, id);

For tamper-evident audit logging, replacing the single global "GENESIS" chain with per-tenant roots SHA256("TENANT_GENESIS:" + tenantId) eliminates write lock contention and allows independent O(Ktenant)O(K_{\text{tenant}}) chain exports without inspecting sibling tenants.

3.2 HMAC X-MCP-Tenant-Assertion Guard and Sovereign GPU Inference

The edge gateway api-server (:8800) propagates verified tenant identity into the private VPC mcp-server (:8810) via short-lived HMAC-SHA256 assertions backed by a bounded replay cache (BoundedNonceReplayGuard) and strict capability gating (read or propose only, preserving 6-gate human-in-the-loop prefill boundaries):

import {
  BoundedNonceReplayGuard,
  appendTenantAuditBlock,
  computeTenantGenesisHash,
  rankHierarchicalScopeCandidates,
  signMcpTenantAssertion,
  verifyMcpTenantAssertion,
} from "@kido/tenant-guard/mcp-assertion";

const replayGuard = new BoundedNonceReplayGuard({ maxEntries: 10_000, ttlMs: 300_000 });
const hmacSecret = process.env.MCP_INTERNAL_HMAC_SECRET!;

// Edge api-server signs short-lived assertion for internal VPC FastMCP hop
const assertionHeader = signMcpTenantAssertion(
  {
    tenantId: "unit-042",
    actorId: "officer-88",
    scopeTier: "unit",
    mode: "propose", // Rejects 'execute' at both sign & verify time (6-Gate HITL)
    issuedAtMs: Date.now(),
    expiresAtMs: Date.now() + 60_000,
    nonce: crypto.randomUUID(),
    toolName: "workflow_propose_action",
    lineage: { provinceId: "prov-07", unitId: "unit-042" },
  },
  hmacSecret
);

// Internal mcp-server verifies signature via timingSafeEqual + replay cache
const verified = verifyMcpTenantAssertion(assertionHeader, hmacSecret, {
  expectedToolName: "workflow_propose_action",
  replayGuard,
});

// Per-tenant isolated SHA-256 chain + 3-tier RAG scope ranking (1.25x > 1.12x > 1.0x)
const genesis = computeTenantGenesisHash("unit-042");
const block = appendTenantAuditBlock(genesis, {
  sequence: 1,
  action: "DRAFT_PROPOSED",
  actorId: "officer-88",
  timestampIso: new Date().toISOString(),
  payload: { draftId: "draft-101", hitlPrefillOnly: true },
}, "unit-042");

const topChunks = rankHierarchicalScopeCandidates(
  [
    { id: "doc-central", scope: "national", baseScore: 0.85 },
    { id: "doc-prov", scope: "province", provinceId: "prov-07", baseScore: 0.8 },
    { id: "doc-foreign", scope: "unit", tenantId: "unit-999", baseScore: 0.99 },
    { id: "doc-unit", scope: "unit", tenantId: "unit-042", baseScore: 0.78 },
  ],
  "unit-042",
  undefined,
  "prov-07"
);
// Drops 'doc-foreign' completely and orders: doc-unit (0.975) > doc-prov (0.896) > doc-central (0.85)

All inference remains inside the private VPC using vLLM (--enable-prefix-caching for shared system rubrics and xgrammar for schema-guaranteed Pydantic JSON) paired with TEI hosting BAAI/bge-m3 dense embeddings and BAAI/bge-reranker-v2-m3. This delivers 45–90 tok/s per stream at a predictable 1.20M–1.87M VND/unit/month across 100 units, cutting unit economics by over 95% versus external per-seat SaaS pricing.

3.3 Clean MP4 Remuxing and Single-Host bun:sqlite WAL Retention

Eliminating the 4K playback stall requires zero transcoding: strip embedded mov_text and metadata streams (-sn -dn), retain original HEVC bits (-c:v copy), extract .srt sidecars for the player overlay, and stage hot files on native NVMe ext4 (>2,500 MB/s):

# Clean MP4 muxing eliminating +245MB mov_text byte-range seek storms at $0 compute overhead
ffmpeg -hide_banner -y -i "master_4k_remux.mkv" \
  -map 0:v:0 -map 0:a:0 \
  -c:v copy -c:a eac3 -ac 6 -b:a 640k \
  -sn -dn -movflags +faststart \
  "clean_directplay.mp4"

Production Verification & Measured Benchmarks

Automated verification (75/75 passing unit tests in @kido/tenant-guard) and direct telemetry benchmarks confirm the production envelope across all three subsystems:

Measured Metric Baseline / Mis-Sized Setup Tier-1 Production Architecture Measured Delta
Multi-Tenant DB & Audit Isolation SQLITE_BUSY + 10 missing tenant_id tables + open IDOR 15 PG17 FORCE RLS tables + per-tenant SHA-256 chains 0.0% cross-tenant leak; <0.3ms RLS overhead
3-Tier Hybrid RAG Latency 15–120ms single-process BM25, zero semantic recall <5ms Valkey / <35ms Semantic / 60–110ms Qdrant RRF Enforces unit 1.25x > province 1.12x > central 1.0x
City-Scale AI Infrastructure Cost Uncapped external token egress failing data residency Private VPC GPU (vLLM + TEI + int8 Qdrant) 1.20M–1.87M VND/unit/mo (>95% cheaper than SaaS)
Single-Host Daemon (0.03 TPS) Rewrite risk across 120+ sync sites + 0.5–1.2ms TCP bun:sqlite WAL (busy_timeout=5000, 0.03ms FFI) Zero migration churn; zero extra Postgres RAM
4K Remux Streaming (104.5 Mbps) 86 range-abort jumps (±245MB), 17-second deadlocks Clean MP4 (-sn -dn) + NVMe ext4 (>2,500 MB/s) 1 sequential HTTP 206 stream; zero buffering stalls

Sovereign multi-tenant security relies on kernel-enforced database boundaries and cryptographically signed VPC tool assertions, while storage-engine and media-muxing choices must obey empirical throughput and byte-offset measurements rather than architectural fashion.

🎭
Kido Chronicles Flywheel

Read the Companion Manga & Dev War-Story Edition on Kido Chronicles

Looking for the real-world production incidents, late-night debugging war stories, and illustrated manga episodes behind this architecture? Explore the companion chapters below:

Explore all 164+ chapters at truyen.khanhdp.comExplore Manga Universe ↗
🔬

Related Architecture Monographs

More in Autonomous AI Agents & Solopreneur OS ↗
All-Weather AI Global Launch Architecture: Defeating Model Drift, 120s Outage Fallback Mesh, and Multi-Tenant Vector Isolation (0.9408¢)
Autonomous AI Agents & Solopreneur OS
Nov 20, 2026•15 min read

All-Weather AI Global Launch Architecture: Defeating Model Drift, 120s Outage Fallback Mesh, and Multi-Tenant Vector Isolation (0.9408¢)

Root-cause architecture for three critical failure modes during enterprise AI global launch days: silent upstream checkpoint updates at second 30 (Model Drift), catastrophic 120-second primary provider blackouts (Provider Outage), and cross-company document leaks across 200 tenants sharing a vector database. Solved via Immutable Checkpoint Pinning, Dual-Provider Active-Passive Mesh with Exponential Backoff, and pgvector Tenant Isolation holding data leaks to 0.0% at a record 0.9408¢/task.

🎭Chronicles:GC Ep 23
Production Stateful AI Architecture: Multi-Tenant RAG Isolation (RLS vs. HNSW Partitioning), Full-Duplex Voice Streaming, and O(1) Rolling Memory
Autonomous AI Agents & Solopreneur OS
Nov 19, 2026•15 min read

Production Stateful AI Architecture: Multi-Tenant RAG Isolation (RLS vs. HNSW Partitioning), Full-Duplex Voice Streaming, and O(1) Rolling Memory

Root-cause engineering for three stateful AI production failures: cross-tenant data leaks and HNSW recall starvation under PostgreSQL RLS (0.9414¢/task), the 0.60¢/turn TTS unit-cost trap solved by small-model full-duplex sentence chunking (< 1.2s TTFA, 0.6633¢/turn), and O(1) rolling-summary conversation memory with NFC back-reference safety (0.0403¢/turn).

🎭Chronicles:GC Ep 22
Three-Layer AI Gateway Defense: Per-User EDoS Quotas, Entity-Aware Strict Semantic Caching, and Sub-1ms FrugalGPT Routing
Autonomous AI Agents & Solopreneur OS
Nov 18, 2026•16 min read

Three-Layer AI Gateway Defense: Per-User EDoS Quotas, Entity-Aware Strict Semantic Caching, and Sub-1ms FrugalGPT Routing

Production architecture for high-concurrency AI gateways: stopping 50k-token EDoS floods with Valkey Lua quotas and prompt clamping (0.0273¢/task), eliminating the e-commerce cosine > 0.95 Size M vs. Size L collision via NER entity partitioning and O(k) SKU invalidation (0.3559¢/task), and shedding 80% of strong-model load via sub-1ms FrugalGPT routing (0.6599¢/task).

🎭Chronicles:GC Ep 21
Author & Systems ArchitectDa Nang, Vietnam

(Dương Phúc Khánh · Kido)

Senior Software Engineer & Systems Architect with 9+ years of experience in high-concurrency distributed architectures, Google Core Web Vitals optimization (0ms TBT, CLS 0.000), and author of the 164+ episode engineering war-story series Kido Chronicles.

⚡ Enterprise Architecture & Turnkey B2B Systems

Need High-Concurrency System Architecture Consulting, AI Automation, or Turnkey B2B Software?

Explore 41 production infrastructure packages (kido-packages (@kido/*)) and 18 turnkey B2B Web App/ERP systems with 100% source code ownership architected by (Dương Phúc Khánh · Kido).

Tags:#Multi-Tenant RLS#Model Context Protocol#Qdrant Hybrid RAG#Private GPU vLLM#SQLite WAL#MP4 Demuxing