All articles

AI Agents8 min readBy Petrică RădanReference guide

Multi-Tenant RAG Isolation and Quotas on Cloud Run and AlloyDB

Deterministic tenant boundaries in AI SaaS require pairing database row-level security and inline vector filtering with transaction-scoped pooling and atomic token reservations

  • AlloyDB
  • Cloud Run
  • Row-Level Security
  • ScaNN
  • Multi-Tenant RAG
  • Connection Pooling
  • Token Quotas

Every enterprise security review reaches the same uncomfortable question. What stops a prompt injection, or a developer's forgotten WHERE clause, from pulling a competitor's documents into your RAG prompt? Mumble about filtering in Python before calling Gemini and the meeting is over. As the engineering team at Truto points out, you need a deterministic boundary inside the database itself.

A multi-tenant RAG stack on Cloud Run and AlloyDB survives that scrutiny only when three mechanisms lock together without gaps. You have to pair PostgreSQL Row-Level Security (RLS) with AlloyDB's ScaNN inline filtering so small tenants don't get empty search results. You have to scope session variables strictly to transactions so pooled connections never bleed data across customers. And you have to replace naive HTTP rate limiters with atomic token reservations that survive broken streams.

Standard pgvector starves small tenants

In a shared-schema database, every customer's embeddings sit in one table, separated by a tenant_id column. Turn on PostgreSQL Row-Level Security, and the database appends your tenant policy to every query, vector similarity searches included. One developer write-up on DEV Community reported no measurable overhead from properly indexed RLS up to 500 concurrent connections; it's a single self-reported test rather than a formal benchmark, though it matches how PostgreSQL evaluates indexed equality predicates. On paper, shared-schema isolation looks effortless.

Then you put an HNSW index on the embedding column and onboard a small customer. Approximate nearest neighbour (ANN) indexes like HNSW walk a graph to find the closest vectors across the entire table first, applying metadata filters afterward. Suppose Tenant A owns 600 rows out of two million. The top 40 vector matches across the whole table might belong entirely to Tenant B, so your query returns zero rows even though Tenant A has plenty of matching documents.

A separate post on DEV Community demonstrated how fast this breaks by running 400 multi-tenant queries against default pgvector HNSW settings (ef_search=40): post-filter starvation caused 147 queries to return fewer rows than the requested LIMIT, and 52 returned nothing at all. Take a solo community post for what it is rather than peer-reviewed research, yet the arithmetic behind that starvation is easy to reproduce on any skewed table. Recent pgvector releases soften the blow with iterative scans (hnsw.iterative_scan = relaxed_order) or exact B-tree fallbacks for tiny tenants, but you're still fighting an index that wasn't built to check metadata while walking the graph.

ScaNN filters while it walks the tree

AlloyDB replaces HNSW with Google's ScaNN index (alloydb_scann). Google Cloud claims it delivers up to 10x faster filtered vector queries and 10x faster index creation than standard PostgreSQL HNSW. Treat vendor ceilings with healthy scepticism, of course, but the mechanism underneath solves multi-tenant starvation cleanly.

Instead of choosing blindly between pre-filtering and post-filtering, AlloyDB's query planner adapts to how much of the table a tenant owns.

Tenant Data ShareExecution StrategyHow AlloyDB Executes It
Tiny (e.g., 0.2% of rows)Pre-filteringUses the B-tree index on tenant_id to pull exact candidates first, then computes exact vector distances.
Medium (0.5% to 10% of rows)Inline filteringBuilds an in-memory bitmap from the B-tree index and evaluates ScaNN vector partitions only against matching rows.
Dominant (>10% of rows)Post-filteringScans the ScaNN vector index first and drops non-matching tenants afterward while maintaining high recall.

Most B2B SaaS platforms live in that middle tier. As Google Cloud's Vinay Sharma and Kumar Ramamurthy explain on Medium, neither pure pre-filtering nor pure post-filtering handles predicates matching 0.5% to 10% of a dataset well. AlloyDB bridges the gap with a bitmap-assisted vector scan. It reads your standard B-tree index on tenant_id, builds an in-memory bitmap of valid rows, and skips distance math for every vector outside that bitmap while walking the ScaNN tree.

One catch trips teams up early: inline filtering is off by default, and it only works on ScaNN indexes. Google Cloud's documentation shows you must explicitly pair your vector index with a B-tree on the tenant column and turn the flag on in your database or session settings.

sql
1-- 1. Enforce strict row-level isolation (even for table owners)
2ALTER TABLE document_chunks ENABLE ROW LEVEL SECURITY;
3ALTER TABLE document_chunks FORCE ROW LEVEL SECURITY;
4
5CREATE POLICY tenant_isolation_policy ON document_chunks
6    USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);
7
8-- 2. Pair a standard B-tree with AlloyDB ScaNN
9CREATE INDEX idx_chunks_tenant ON document_chunks (tenant_id);
10CREATE INDEX idx_chunks_embedding ON document_chunks 
11    USING alloydb_scann (embedding cosine)
12    WITH (mode = 'AUTO');

Notice the NULLIF wrapper inside the RLS policy. If a bug in your Cloud Run middleware forgets to set app.tenant_id, current_setting('app.tenant_id', true) returns an empty string rather than NULL in some drivers, or throws an unguarded cast error. Returning NULL ensures the equality check fails closed and exposes zero rows.

Google Cloud's engineering posts on Medium say AlloyDB's optimizer picks between pre, inline, and post-filtering automatically from table statistics, sparing developers manual hints. I wouldn't take that on blind faith in production. Multi-tenant SaaS distributions are famously lopsided (one enterprise whale sits next to 500 free-tier signups), and stale PostgreSQL statistics fool cost optimizers all the time. If I were deploying this, I wouldn't sign off until I ran EXPLAIN ANALYZE as both a 50-row tenant and a 500,000-row tenant to verify the Bitmap Index Scan fires under RLS. I'd also watch the default SQ8 quantizer: Google's docs note a typical 1% to 2% recall drop and advise setting quantizer = 'FLAT' if legal or financial RAG demands 99%+ recall.

Connection pooling is where tenant isolation goes to die

Cloud Run scales horizontally by spinning up stateless containers on demand. If 50 instances each open a local pool of 20 connections during a traffic spike, 1,000 connections hit PostgreSQL at once. AlloyDB's Managed Connection Pooling, which recently hit general availability on port 6432 as Steef-Jan Wiggers reported at InfoQ, changes that math. Google claims up to 5x higher transactional throughput and 3x more concurrent client connections than direct connections on port 5432, and HR software company UKG uses it to pack more tenant databases onto single clusters. When you double-pool between microservices and AlloyDB, Adarsha Kuthuru and Kumar Ramamurthy write on InfoQ that 5 to 10 local connections per app instance and 15 to 20 pooler connections per database vCPU hits the right ratio.

To reach those numbers, Managed Connection Pooling runs in transaction mode, much like PgBouncer. AlloyDB lends a backend connection to your Cloud Run request for a single transaction and reclaims it the millisecond you COMMIT or ROLLBACK, without running DISCARD ALL to wipe session state.

Set the tenant context in Python or Go with a session-level SET app.tenant_id = '...', and you have built a data breach. Chris van Eijk at Now-Next tested PostgreSQL 17.10 behind PgBouncer 1.25.2 in transaction mode across two million invoice rows and 1,000 tenants. Session-level SET leaked all 267,023 rows of the largest tenant to subsequent unconfigured connections. Worse, van Eijk showed that running SET LOCAL outside an explicit BEGIN...COMMIT block (in autocommit mode) silently does nothing, leaving the connection polluted by whichever customer used it last. Wrapping every query in an explicit transaction with SET LOCAL leaked zero rows.

sql
1BEGIN;
2-- Scoped strictly to this transaction; wiped automatically on COMMIT/ROLLBACK
3SET LOCAL app.tenant_id = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
4SET LOCAL scann.enable_inline_filtering = on;
5SET LOCAL plan_cache_mode = force_custom_plan;
6
7SELECT chunk_text, (embedding <=> $1) AS distance
8FROM document_chunks
9ORDER BY embedding <=> $1
10LIMIT 10;
11COMMIT;

Look closely at the fourth line: SET LOCAL plan_cache_mode = force_custom_plan. Under PostgreSQL's plan-caching rules, repeated executions of a prepared statement can switch from custom plans to a single generic plan, and an analysis on postgr.es flagged a nasty side effect when PgBouncer shares protocol-level prepared statements in transaction mode. Tenants end up reusing each other's cached generic query plans on RLS-protected tables, slowing queries down by up to 10x. When a 500,000-row tenant warms up a prepared statement, PostgreSQL caches a post-filtering vector plan; when a 100-row tenant hits that same statement milliseconds later, the cached plan starves them. Forcing custom plans adds a fraction of a millisecond in planning time and spares you mysterious latency spikes.

Dezső Mező at consultancy DField Solutions wrote that across 12 multi-tenant SaaS projects, pairing transaction-mode pooling with transaction-wrapped SET LOCAL calls and a 40-line CI leak test caught 90% of RLS bugs before release. Write that CI test on day one. Open two concurrent pooled connections, interleave transactions for Tenant A and Tenant B, and assert that an unconfigured third connection returns zero rows.

Atomic token reservations survive broken streams

Locking down retrieval only solves half the multi-tenant problem. Once AlloyDB returns ten isolated chunks, your Cloud Run service stuffs them into a Gemini prompt and opens a Server-Sent Events (SSE) or WebSocket stream to the browser. What stops a runaway client script on a $99/month plan from burning $2,000 of Vertex AI tokens in twenty minutes?

Standard API gateways count HTTP requests, not tokens. A two-sentence chat prompt and a 40-page RAG synthesis look identical to Cloud Armor, yet differ in cost by two orders of magnitude. Streaming on Cloud Run makes it harder: you don't know the exact output token count until the stream finishes, or dies mid-sentence when the user closes their tab. If 24 users from the same tenant fire requests at once against a 5,000-token remaining balance, a naive read-call-subtract check lets all 24 slip through.

In an airport transfer booking system I built for a UK client, I stopped concurrent double-bookings by wrapping availability checks and inserts inside PostgreSQL advisory locks. Advisory locks work for SaaS token quotas too, though a single atomic UPDATE...RETURNING row lock on an AlloyDB quota table is even simpler and lives in the database you already run.

Because you can't wait until the stream ends to check the budget, use a two-phase reserve-and-reconcile loop. Before generating anything, assemble your system instructions, the user query, and the RAG chunks pulled from AlloyDB, then call the Vertex AI CountTokens API to get the exact input cost. Add those input tokens to the caller's max_output_tokens ceiling and run a single atomic UPDATE in AlloyDB that increments tokens_used only when the new total stays within monthly_token_limit; if zero rows update, return HTTP 429 before calling Gemini. Once the reservation clears, stream the Gemini response from Cloud Run while counting chunks in memory so your finally block knows roughly how much text left the server if the client disconnects. When the stream closes, read usage_metadata from Gemini's final chunk (or fall back to your in-memory count on an aborted stream) and fire a quick UPDATE to refund unused output tokens.

sql
1-- Phase 2: Atomic pre-flight token reservation in AlloyDB
2UPDATE tenant_quotas
3SET tokens_used = tokens_used + $1, -- (exact_input_tokens + max_output_tokens)
4    updated_at = NOW()
5WHERE tenant_id = $2
6  AND (tokens_used + $1) <= monthly_token_limit
7RETURNING monthly_token_limit - tokens_used AS remaining_budget;

One rule matters here: never hold a database transaction open across the Gemini stream. Commit your RAG read and your quota reservation in milliseconds, and hand the connection straight back to AlloyDB's pooler. Stream the model's answer for ten seconds with zero database connections held, then grab a fresh pooled connection for two milliseconds at the end to refund the unused tokens. Hold connections open while waiting on Vertex AI, and modest traffic will drain your AlloyDB pool.

When a shared table stops being enough

Shared-schema RLS gives you the highest tenant density and the smallest infrastructure bill, as Google Cloud's Medium posts point out, but it still hits a ceiling. AlloyDB can rebalance lopsided vector partitions automatically as one customer grows, yet every tenant on that cluster still competes for the same buffer cache, IOPS budget, and index maintenance cycles. Sooner or later, a bank or healthcare buyer will admire your RLS policies and transaction-scoped variables, then demand customer-managed encryption keys (CMEK) or physical data residency anyway. Resolve the database connection string per tenant inside your Cloud Run middleware from the start. When a seven-figure customer outgrows a row in your shared table, moving them onto a dedicated AlloyDB cluster becomes a routing change instead of a rewrite.

Frequently asked questions

Why do standard pgvector HNSW indexes fail for small tenants under Row-Level Security?

Approximate nearest neighbour indexes like HNSW walk the vector graph across the entire table first and apply metadata filters afterward. If a small tenant owns a tiny fraction of rows, the top global matches can belong entirely to larger tenants, causing queries to return fewer rows than requested or nothing at all.

How does AlloyDB ScaNN prevent multi-tenant search starvation?

AlloyDB's query planner adapts between pre-filtering, inline filtering, and post-filtering based on how much of the table a tenant owns. For mid-sized tenants, it pairs a B-tree index on the tenant column with ScaNN inline filtering to build an in-memory bitmap and evaluate vector distances only on matching rows, though inline filtering must be explicitly enabled.

How do you prevent tenant data leaks with transaction-mode connection pooling?

In transaction mode, pools like AlloyDB Managed Connection Pooling reuse backend connections across customers without wiping session-level state. You must wrap every query in an explicit BEGIN and COMMIT block using SET LOCAL for the tenant ID, and set plan_cache_mode to force_custom_plan so tenants do not reuse each other's cached query plans.

How do you enforce LLM token quotas during streaming responses on Cloud Run?

Use a two-phase reserve-and-reconcile loop instead of HTTP rate limits or open database transactions. Before calling Gemini, count input tokens with Vertex AI CountTokens, atomically reserve input plus max output tokens in AlloyDB, commit the transaction before streaming, and refund unused output tokens once the stream finishes or disconnects.

Sources

Book a discovery call

30 minutesGoogle MeetFree