Multi-Tenancy and Isolation Questions
Serving many tenants from shared infrastructure: tenancy models (silo, pool, bridge), data isolation, per-tenant data residency, noisy-neighbor mitigation, per-tenant limits, and security boundaries between tenants. Covers the cost, isolation, and blast-radius tradeoffs of shared versus dedicated resources, and business continuity: per-tenant backup, disaster recovery, and compliant tenant offboarding and deletion. The architecture layer specific to SaaS and platform products.
Design a per-tenant rate limiter for API ingestion supporting 100k tenants where each tenant has a base quota plus burst credits. Describe data structures, storage (in-memory vs Redis), how to scale, and strategies to avoid cross-tenant interference and race conditions in a distributed environment.
Sample Answer
Direct answer
I would give each tenant a token bucket stored in Redis: the bucket refills at the tenant's base rate, and its capacity is the base rate plus the tenant's burst credits, so a quiet tenant accumulates the right to burst and a busy tenant is held to its base rate. The refill-and-take step runs as one atomic Lua script inside Redis (Redis executes a script start to finish without interleaving any other command), which removes the race where two API servers both spend the last token. Enforcement sits at the API gateway, keys are sharded (split across multiple Redis nodes by key, so no single node holds every tenant) by tenant across a Redis cluster, and a small in-process cache in each gateway handles the very largest tenants so one hot key (a single Redis key that gets so much traffic it becomes a bottleneck on its own, even though the rest of the cluster is fine) cannot slow the others.
Algorithm choice: token bucket versus leaky bucket
- Token bucket: tokens drip into a bucket at a fixed rate up to a maximum. Each request spends one token; no token, the request is rejected. It allows bursts up to the bucket size, then settles at the refill rate. That matches "base quota plus burst credits" exactly: refill rate = base quota, capacity = one second of base quota plus burst credits.
- Leaky bucket: requests enter a queue that drains at a fixed rate. Output is perfectly smooth, but bursts are delayed rather than served. Good in front of a fragile downstream system; wrong here, because ingestion clients want a burst to succeed now.
- Fixed window counters ("100 per minute", reset on the minute) are simpler but allow double the rate across a window boundary.
Data structure and storage
One small hash (a Redis data type that stores field-value pairs under one key, like a tiny dictionary) per tenant: tokens (a float) and ts (last refill time in milliseconds). No per-request records are stored, so memory depends on tenant count, not traffic.
In-memory only versus Redis:
| Option | Pros | Cons |
|---|---|---|
| In-memory per gateway node | No network hop; simplest | With 20 gateway nodes, each enforces its own bucket, so a tenant gets up to 20 times its quota unless you divide the quota by node count, which is wrong whenever load is uneven |
| Central Redis | One accurate bucket per tenant across all nodes | One network round trip per request; Redis becomes a dependency to scale and to fail around |
| Hybrid | Redis for accuracy, plus local pre-allocation of small token batches for the few highest-volume tenants | More code; a node that dies loses its unspent batch (bounded, small over-admission: the tenant can be let through slightly more requests than its exact quota for a short time) |
I choose Redis with the hybrid path for the top tenants.
Where to enforce
Enforce at the edge (API gateway) for the ingestion quota, so rejected traffic never reaches the ingestion service or its queue. Keep a second, coarser limit inside the ingestion service on expensive work (bytes written, records per batch), because the gateway only sees request counts.
Worked example (executed)
The Lua script below is the whole limiter. Time is passed in by the caller so the demo is deterministic; in production you would pass the gateway's clock (or read Redis TIME inside the script) and accept small clock skew between gateways.
# pip install redis ; docker run -d --name redis-demo -p 6379:6379 redis:7-alpine
import sys
from concurrent.futures import ThreadPoolExecutor
import redis
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 6379
r = redis.Redis(port=PORT, decode_responses=True)
r.flushdb() # demo only: empties the selected Redis database
# One atomic refill-and-take per request. Keys: the tenant's bucket.
# ARGV: rate (tokens/sec), capacity, now (ms), cost
TAKE = r.register_script("""
local rate, cap, now, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3]), tonumber(ARGV[4])
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens, ts = tonumber(b[1]), tonumber(b[2])
if tokens == nil then tokens, ts = cap, now end
local elapsed = math.max(0, now - ts)
tokens = math.min(cap, tokens + elapsed * rate / 1000)
local allowed = 0
if tokens >= cost then tokens = tokens - cost; allowed = 1 end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', math.max(ts, now))
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate * 1000) * 2)
return {allowed, tostring(tokens)}
""")
PLAN = {"rate": 100, "capacity": 500} # base 100 req/s + 400 burst credits
def take(tenant, now_ms, cost=1):
# f"rl:{{{tenant}}}" is an f-string: the outer {{ }} are literal braces
# in the output (Redis Cluster hash-tag syntax), and the inner {tenant}
# substitutes the tenant id, producing e.g. "rl:{A}".
return TAKE(keys=[f"rl:{{{tenant}}}"],
args=[PLAN["rate"], PLAN["capacity"], now_ms, cost])
def burst(tenant, n, now_ms):
with ThreadPoolExecutor(max_workers=20) as pool:
results = list(pool.map(lambda _: take(tenant, now_ms), range(n)))
return sum(int(a) for a, _ in results)
print("t=0ms tenant A sends 600 concurrently, admitted:", burst("A", 600, 0))
print("t=0ms tenant B sends 10 concurrently, admitted:", burst("B", 10, 0))
print("t=1000ms tenant A sends 150 concurrently, admitted:", burst("A", 150, 1000))
print("t=6000ms tenant A sends 600 concurrently, admitted:", burst("A", 600, 6000))
print("bytes for one tenant bucket:", r.memory_usage("rl:{A}"))
# The race the Lua script prevents: read-then-write from two app servers.
r.hset("naive:{C}", mapping={"tokens": 1})
seen_1 = float(r.hget("naive:{C}", "tokens")) # server 1 reads 1
seen_2 = float(r.hget("naive:{C}", "tokens")) # server 2 reads 1 before server 1 writes
admitted = 0
for seen in (seen_1, seen_2):
if seen >= 1:
admitted += 1
r.hset("naive:{C}", "tokens", seen - 1)
print("naive read-then-write with 1 token left, admitted:", admitted)
How the script works, line by line:
HMGET KEYS[1] tokens ts(HMGET: read multiple fields from a Redis hash in one call) reads the tenant's current token count and the timestamp of its last refill. If the key does not exist yet (tokens == nil), the bucket starts full:tokens, ts = cap, now.elapsed = max(0, now - ts)is the number of milliseconds since the last refill.tokens = min(cap, tokens + elapsed * rate / 1000)adds backelapsedmilliseconds' worth of tokens at the tenant's rate (tokens per second, so divide by 1000 to convert milliseconds to seconds), capped at the bucket's capacity so a long-idle tenant does not accumulate unlimited credit.- If there are enough tokens for this request's
cost, the request is admitted and the cost is subtracted; otherwisetokensis left unchanged and the request is rejected. HSET KEYS[1] tokens ... ts ...(HSET: write fields back to a Redis hash) saves the new token count and refill time, so the next call sees the updated state.PEXPIRE KEYS[1] (cap / rate * 1000) * 2(PEXPIRE: set a millisecond time-to-live on the key) expires the bucket after twice the time it would take to refill from empty, so a tenant that stops sending traffic does not leave its key in Redis forever; by the time it would expire, an empty bucket and a missing key behave the same way (both start the next request from a full or freshly-refilled bucket).
Output against redis:7-alpine (Redis 7.4.11), run twice with identical results:
t=0ms tenant A sends 600 concurrently, admitted: 500
t=0ms tenant B sends 10 concurrently, admitted: 10
t=1000ms tenant A sends 150 concurrently, admitted: 100
t=6000ms tenant A sends 600 concurrently, admitted: 500
bytes for one tenant bucket: 80
naive read-then-write with 1 token left, admitted: 2
Reading it:
- Tenant A's first burst of 600 gets exactly 500 (the full bucket: 100 base plus 400 burst credits), despite 20 threads racing, because each Lua call is atomic.
- Tenant B is untouched by A's flood: separate key, separate bucket.
- One second later A has refilled 1,000 ms x 100 / 1,000 = 100 tokens, so 100 of 150 pass.
- After 5 quiet seconds A has 5 x 100 = 500 tokens again, capped at 500: burst credits rebuild while the tenant is idle.
- The naive version admits 2 requests on 1 token: both servers read the same stale value before either writes back, an overshoot of 1. The same race generalizes to N nodes: if all N happen to read the stale value before any of them writes back, all N admit, which is an overshoot of N-1, not N. Scale that to 20 gateway nodes racing on the same contended token and, in the worst case, all 20 admit when only 1 token remained, an overshoot of 19.
Sizing for 100,000 tenants: Redis reported 80 bytes for one bucket (MEMORY USAGE, which does not count every piece of per-key overhead such as the expiry entry), so 100,000 x 80 bytes = 8,000,000 bytes, about 8 MB. Even at several times that, memory is not the constraint. Throughput is: every admitted or rejected request is one Redis call. Measure your Redis node's throughput for this script under load and divide peak request rate by it to get the shard count, rather than trusting a published benchmark.
Scaling and avoiding cross-tenant interference
- Shard by tenant. The
{A}inrl:{A}is a Redis Cluster hash tag: everything inside the braces decides the shard, so any future per-tenant keys land on the same node as the bucket and can be used in the same script. - Hot tenants. One tenant at 50,000 requests per second would make its shard hot and slow every other tenant on that shard. For the top few tenants, each gateway takes tokens in batches (for example 100 at a time) and spends them locally, cutting Redis calls for that tenant by 100 times at the cost of a small over-admission if a node dies holding tokens.
- Fail open or fail closed. If Redis is unreachable, I fail open with a local, conservative in-memory limit per node (so ingestion keeps working) and alert. Failing closed would turn a Redis outage into an outage for every tenant.
- Config per tenant. Rate and capacity come from the tenant's plan, cached in the gateway and refreshed on change, so an upgrade takes effect without a deploy.
- Clear rejection. Return HTTP 429 with a
Retry-Afterheader computed from the token deficit, so well-behaved clients back off instead of retrying immediately.
Trade-offs and pitfalls
- Count what costs you money. Requests are a proxy; if one request can carry 10 MB, charge tokens by size (the script's
costargument) on the ingestion path. - Clock skew between gateways can refill slightly early or late. Passing Redis's own time inside the script removes skew and is safe because Redis 7 replicates a script's effects (the writes it made) rather than re-running the script on replicas.
- Do not store per-request timestamps (a sliding-window log) at this scale: memory grows with traffic, not tenants.
Design a multi-tenant API gateway and extensibility model for a SaaS platform that must support tenant-specific rate limits, custom authentication, and plugin-based request transformations. Describe the components, a tenant-config data model, your scaling strategy, and how you'd evolve shared API contracts safely without breaking individual tenants.
Sample Answer
Direct answer
I would build a gateway data plane of stateless nodes that serves every tenant, driven by a control plane that stores each tenant's configuration and pushes versioned snapshots to the nodes. Each request is resolved to a tenant first, then passes a fixed pipeline: tenant-specific authentication, rate limiting, then the tenant's ordered list of transformation plugins, then the backend. Custom authentication is configuration wherever possible (which identity provider, which key format), and custom transformations run as sandboxed WebAssembly plugins with strict CPU, memory and time budgets. Shared API contracts evolve by additive changes, explicit versions tenants can pin, and a pre-release check that replays every tenant's plugins against the new contract.
Terms used below
- API gateway: the front door that every API request passes through; it handles cross-cutting concerns (auth, limits, routing) so backends do not.
- Data plane / control plane: the data plane handles live traffic; the control plane manages configuration and is off the request path.
- Rate limit / token bucket: a limit like "100 requests per second, bursts up to 200". A token bucket refills at the rate and each request spends a token.
- Plugin: tenant-supplied logic that modifies a request or response (rename a field, add a header, map a legacy format).
- WebAssembly (Wasm): a portable bytecode that runs in a sandbox with no access to the host unless explicitly granted, which makes it suitable for running untrusted code.
- OIDC (OpenID Connect) and JWT (JSON Web Token): a standard login protocol and the signed token it issues; the gateway verifies the signature with the issuer's public keys (a JWKS, JSON Web Key Set).
- Feature flag: a runtime switch turning behaviour on for specific tenants without a deploy.
Components
flowchart LR
REQ[Request] --> TR[Tenant resolver]
TR --> AU[Auth stage]
AU --> RL[Rate limiter]
RL --> PL[Plugin chain<br/>Wasm sandbox]
PL --> BE[Backend services]
CP[Control plane<br/>config store + validator] -->|versioned snapshots| TR
RL <--> RC[(Shared counters)]
- Tenant resolver: maps hostname (
acme.api.example.com), API key prefix, or token claim (a field inside a verified token, such as a JWT'stenant_idfield, set by the issuer and not editable by the caller) to a tenant ID. Unknown tenant: reject before any other work. - Auth stage: per-tenant method from config: OIDC with the tenant's issuer, API keys (stored hashed), or mutual TLS (both sides present certificates). The verified identity, not a header, becomes the tenant context passed downstream.
- Rate limiter: per-tenant, per-key and per-route limits. Each node keeps a local token bucket and synchronises with a shared counter store every short interval, so the global limit is approximately enforced without a remote call per request. Concretely, for a tenant limited to 500 rps / burst 1000 behind, say, 10 gateway nodes, each node's local bucket gets an even static share: 50 rps and a burst of 100. A node enforces only its own share regardless of what other nodes see, so the platform-wide total can never exceed the configured 500 rps / 1000 burst: the "approximate" part is fairness, not the ceiling. If the tenant's traffic happens to land unevenly (all of it hitting 2 of the 10 nodes instead of spreading out), those 2 nodes throttle it well before 500 rps platform-wide while the other 8 nodes' shares sit unused; the periodic sync is what lets the counter store notice that skew and rebalance the local shares at the next interval, not what caps the total.
- Plugin chain: ordered list of Wasm modules for this tenant, each with a budget (for example 5 ms CPU and 16 MB memory), no network access, and a declared failure mode (fail closed: reject the request; fail open: skip the plugin).
- Control plane: API and UI for tenants to edit config, a validator (schema checks, plugin compilation, limit sanity), and a publisher that distributes signed, versioned snapshots.
Tenant-config data model
{
"tenant_id": "t-4812",
"version": 57,
"hosts": ["acme.api.example.com"],
"auth": {
"type": "oidc",
"issuer": "https://login.acme.com",
"audience": "acme-api",
"required_scopes": ["orders:read"]
},
"rate_limits": [
{"scope": "tenant", "rps": 500, "burst": 1000},
{"scope": "api_key", "rps": 50, "burst": 100},
{"scope": "route", "route": "POST /orders", "rps": 100, "burst": 100}
],
"plugins": [
{"id": "legacy-date-format", "module_sha256": "<hash of reviewed module>", "stage": "response",
"cpu_ms": 5, "memory_mb": 16, "on_error": "fail_open"}
],
"api_version_pin": "2025-11-01",
"flags": {"orders_v2_fields": true},
"schema_extensions": {"order": {"x_acme_cost_center": "string"}}
}
Key design choices: the whole document is versioned, so a bad change rolls back to version 56 in one step; plugins are referenced by content hash so the running code is exactly the reviewed code; custom schema extensions live in a tenant namespace (x_acme_...) so they can never collide with future platform fields.
Scaling strategy
- Stateless nodes, config in memory. Illustrative sizing: 20,000 tenants x about 4 KB of config each = 80 MB, which every node can hold. Nodes pull whole snapshots or, to save bandwidth, deltas (only the tenants whose config changed since the last version, not the whole 80 MB document), and swap atomically (the node switches every lookup to the new version in one step, so no request is ever served against half-old, half-new config); a node that cannot fetch config keeps serving the last good version.
- Horizontal scale behind a load balancer; the rate-limit counter store is sharded by tenant ID (its data is split across multiple physical stores by tenant ID, so a given tenant's counters always live on the same one store and no single store has to hold everyone's counters) so one tenant's counters live on one shard.
- Hot tenants: a tenant large enough to dominate a node pool gets its own pool (routing by hostname), which is a config change, not a code change.
- Plugin cost control: modules are compiled once and cached per node; the per-plugin CPU budget bounds the worst case. With a 5 ms budget and 3 plugins, a tenant can add at most 15 ms to its own request's processing time. That bound caps the delay added to the request that triggered it, but the CPU still runs on a node shared by other tenants, so it is not free for them: enough concurrent requests from one tenant still compete for the same node's CPU as everyone else's requests. What actually bounds a tenant's total draw on a node is the rate limiter above (it caps how many of that tenant's requests can be in flight at once); the plugin budget alone only bounds the worst case per request, not the aggregate load one tenant can put on a shared node.
Evolving shared contracts without breaking tenants
- Additive by default: new optional fields and new endpoints are safe; removing or renaming fields, tightening validation, or changing a field's meaning are breaking.
- Explicit versions with pins: breaking changes ship as a new dated version; each tenant's
api_version_pinkeeps them on the old behaviour until they opt in. The gateway translates between versions for as long as the old one is supported. - Tolerant readers: clients and plugins are required to ignore unknown fields rather than error on them. Document it, and test it.
- Replay tenant plugins before release: for every tenant plugin, run its recorded sample traffic through the new contract in a staging gateway and diff the outputs. A plugin that relied on a field that moved fails here, not in production.
- Feature flags for rollout: new behaviour turns on per tenant (internal tenants, then a small cohort, then everyone), with instant rollback.
- Deprecation with telemetry: the gateway counts calls per tenant per deprecated field; you only remove a version when that count is zero or the announced deadline (for example 12 months) has passed.
Trade-offs and pitfalls
- Wasm plugins vs declarative transforms: declarative mapping rules (for example JSON path renames: move or rename a field at a given address inside the JSON document, such as
$.customer.email, plus header rules) cover most needs, are easier to validate, and cannot loop. Offer them first and allow Wasm only when rules cannot express the need. - Global vs local rate limiting: exact global counting needs a remote call per request; local buckets with periodic sync allow brief overshoot of the limit. For fairness between tenants the overshoot is acceptable; for billing-grade quotas, reconcile from logs.
- Pitfall: letting custom auth plugins decide the tenant. The tenant must be established by the platform's resolver and auth stage, not by tenant code that could claim to be anyone.
- Pitfall: config pushes as an outage source. Validate, canary (send the new config to a small subset of nodes first and watch for errors before the rest of the fleet gets it) to a few nodes, and keep the last-good snapshot, because one malformed tenant config must not take down the fleet.
Explain how PostgreSQL Row Level Security (RLS) can be used to implement tenant isolation for a shared-schema database. Describe how the policies are defined, the performance implications, and the gotchas that catch teams out in production. Give examples of when RLS is the right choice and when it isn't.
Sample Answer
Direct answer
PostgreSQL Row Level Security (RLS) lets you attach a policy to a table, a boolean condition such as tenant_id = <current tenant>, that the database silently adds to every query from ordinary roles. In a shared-schema design (all tenants in the same tables, each row tagged with tenant_id), that turns "every developer must remember the WHERE tenant_id = ? clause" into "the database refuses to show or write other tenants' rows". The application sets the current tenant per transaction, and the policy reads it. RLS is a strong safety net, not a complete isolation strategy: superusers, table owners and some views bypass it, and connection pooling can leak the tenant setting unless it is scoped correctly.
How the policy is defined
Three pieces:
- Turn it on for the table:
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;With RLS enabled and no policy, ordinary roles see zero rows (default deny). - Write the policy.
USINGfilters which existing rows a query can see, update or delete.WITH CHECKvalidates rows being inserted or updated, so a tenant cannot write a row stamped with another tenant's ID. - Tell the database who the tenant is. The usual pattern is a custom setting: the application runs
SET LOCAL app.tenant_id = '42'at the start of each transaction, and the policy reads it withcurrent_setting('app.tenant_id', true). Thetruemeans "return NULL instead of erroring if the setting does not exist".
Worked example (executed)
Run against postgres:16-alpine with docker run -d --name pg-demo -e POSTGRES_PASSWORD=pw postgres:16-alpine, then docker exec -i pg-demo psql -U postgres -q < rls.sql:
-- run as the superuser "postgres" (the table owner in this demo)
CREATE TABLE invoices (
tenant_id int NOT NULL,
id int NOT NULL,
amount numeric NOT NULL,
PRIMARY KEY (tenant_id, id)
);
INSERT INTO invoices VALUES (1,1,100),(1,2,250),(2,1,999);
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::int)
WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::int);
CREATE ROLE app_user LOGIN;
GRANT SELECT, INSERT, UPDATE, DELETE ON invoices TO app_user;
CREATE VIEW invoice_totals AS SELECT tenant_id, sum(amount) AS total FROM invoices GROUP BY tenant_id;
GRANT SELECT ON invoice_totals TO app_user;
\echo '--- 1. superuser/owner, no tenant set: policy does not apply'
SELECT count(*) FROM invoices;
SET ROLE app_user;
\echo '--- 2. app_user, no tenant set: fails closed (NULL matches nothing)'
SELECT count(*) FROM invoices;
\echo '--- 3. app_user as tenant 1'
BEGIN;
SET LOCAL app.tenant_id = '1';
SELECT tenant_id, id, amount FROM invoices ORDER BY id;
\echo '--- 4. tenant 1 tries to write a tenant 2 row'
-- SAVEPOINT marks a point to roll back to. Without it, the failed INSERT below
-- would abort this whole transaction and every later statement in it would also
-- error with "current transaction is aborted"; rolling back to the savepoint
-- undoes just the failed insert so the script can keep running and COMMIT.
SAVEPOINT s;
INSERT INTO invoices VALUES (2, 50, 1);
ROLLBACK TO SAVEPOINT s;
COMMIT;
\echo '--- 5. SET LOCAL ended with the transaction: next request on this pooled connection sees'
SELECT count(*) FROM invoices;
\echo '--- 6. plain SET (session scope) leaks into the next request on the same connection'
SET app.tenant_id = '2';
SELECT 'request A (tenant 2)' AS who, count(*) FROM invoices;
SELECT 'request B (forgot to set tenant)' AS who, tenant_id, amount FROM invoices;
RESET app.tenant_id;
\echo '--- 7. a view owned by the superuser bypasses the policy'
SET app.tenant_id = '1';
SELECT * FROM invoice_totals ORDER BY tenant_id;
RESET ROLE;
ALTER VIEW invoice_totals SET (security_invoker = true);
SET ROLE app_user;
\echo '--- 8. same view with security_invoker = true'
SELECT * FROM invoice_totals ORDER BY tenant_id;
RESET ROLE;
Output:
--- 1. superuser/owner, no tenant set: policy does not apply
count
-------
3
(1 row)
--- 2. app_user, no tenant set: fails closed (NULL matches nothing)
count
-------
0
(1 row)
--- 3. app_user as tenant 1
tenant_id | id | amount
-----------+----+--------
1 | 1 | 100
1 | 2 | 250
(2 rows)
--- 4. tenant 1 tries to write a tenant 2 row
ERROR: new row violates row-level security policy for table "invoices"
--- 5. SET LOCAL ended with the transaction: next request on this pooled connection sees
count
-------
0
(1 row)
--- 6. plain SET (session scope) leaks into the next request on the same connection
who | count
----------------------+-------
request A (tenant 2) | 1
(1 row)
who | tenant_id | amount
----------------------------------+-----------+--------
request B (forgot to set tenant) | 2 | 999
(1 row)
--- 7. a view owned by the superuser bypasses the policy
tenant_id | total
-----------+-------
1 | 350
2 | 999
(2 rows)
--- 8. same view with security_invoker = true
tenant_id | total
-----------+-------
1 | 350
(1 row)
What each step shows:
- Steps 1 and 2: the superuser sees all 3 rows; the application role with no tenant set sees 0. Failing closed (showing nothing) is the behaviour you want when context is missing.
- Step 3: tenant 1 sees only its own 2 rows, with no
WHEREclause in the query. - Step 4:
WITH CHECKblocks tenant 1 from inserting a row labelled tenant 2. TheSAVEPOINTaround it is not part of the isolation mechanism; it only lets this script recover from the expected error and keep running the remaining steps in one transaction. - Step 5:
SET LOCALvanished atCOMMIT, so the next request on the same pooled connection starts with no tenant and sees nothing. - Step 6: a plain
SETlasts for the whole session, so request B, which forgot to set a tenant, silently read tenant 2's 999 invoice. - Steps 7 and 8: a view runs with its owner's rights by default, and the owner here bypasses RLS, so the view leaked tenant 2's total. PostgreSQL 15 added
security_invoker = truefor views, which applies the caller's policies.
The NULLIF(..., '') in the policy is there for a reason found while running this: once a transaction has used SET LOCAL app.tenant_id, later reads of the setting in that session return an empty string rather than NULL, and without NULLIF the cast ''::int raises invalid input syntax for type integer on the next request. That fails closed, but as an error on every pooled connection's next query rather than an empty result.
Performance implications
- The policy predicate is added to the query like an ordinary
WHEREclause, so the cost is whatever that filter costs. With an index that leads withtenant_id, it is usually an index lookup. The follow-on script below (run in the same container afterrls.sql, withdocker exec -i pg-demo psql -U postgres -q < rls2.sql) loads 200 tenants with 501 invoices each and checks the plan, and also checks the table-owner bypass covered under gotchas:
CREATE ROLE app_owner LOGIN;
CREATE TABLE notes (tenant_id int NOT NULL, body text);
ALTER TABLE notes OWNER TO app_owner;
INSERT INTO notes VALUES (1,'a'),(2,'b');
ALTER TABLE notes ENABLE ROW LEVEL SECURITY;
CREATE POLICY p ON notes USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::int);
SET ROLE app_owner;
SET app.tenant_id = '1';
\echo 'owner, ENABLE only'
SELECT count(*) FROM notes;
RESET ROLE;
ALTER TABLE notes FORCE ROW LEVEL SECURITY;
SET ROLE app_owner;
\echo 'owner, FORCE'
SELECT count(*) FROM notes;
RESET ROLE;
-- index use (loads 200 tenants x 501 invoices)
INSERT INTO invoices SELECT t, g, 1 FROM generate_series(1,200) t, generate_series(1000,1500) g;
ANALYZE invoices;
SET ROLE app_user;
SET app.tenant_id = '7';
EXPLAIN (COSTS OFF) SELECT sum(amount) FROM invoices;
EXPLAIN (COSTS OFF) SELECT * FROM invoices WHERE id = 1200;
owner, ENABLE only
count
-------
2
(1 row)
owner, FORCE
count
-------
1
(1 row)
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------
Aggregate
-> Bitmap Heap Scan on invoices
Recheck Cond: (tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
-> Bitmap Index Scan on invoices_pkey
Index Cond: (tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer)
(5 rows)
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------
Index Scan using invoices_pkey on invoices
Index Cond: ((tenant_id = (NULLIF(current_setting('app.tenant_id'::text, true), ''::text))::integer) AND (id = 1200))
(2 rows)
Reading the two shapes: the first query (sum(amount), no row filter beyond tenant) matches many rows, tenant 7's whole slice of the table, so the planner picks a Bitmap Index Scan: walk the index once and build an in-memory list ("bitmap") of the matching rows' physical locations, without fetching them yet. That feeds a Bitmap Heap Scan, which fetches exactly those locations from the table in one pass ordered by physical position, cheaper than jumping to each row individually. Index Cond under the bitmap index scan is the condition used to build that list; Recheck Cond on the heap scan is PostgreSQL re-checking that same condition against each fetched row, something bitmap scans always do because the in-memory bitmap can be a lossy approximation when a great many rows match. The second query adds id = 1200. Combined with the policy's tenant condition, that pins down both columns of the (tenant_id, id) primary key, so at most one row can match, and the planner instead uses a plain Index Scan: walk the index and fetch that one matching row immediately, which beats building a whole bitmap when only a single row is expected. Either way, the policy's tenant condition becomes part of the Index Cond on the (tenant_id, id) primary key, so the database reads only tenant 7's slice of the index.
- Without a
tenant_id-leading index, every query scans all tenants' rows and then filters, which gets worse as tenants grow. - Policies that call subqueries or functions (for example "tenant is in the user's membership table") run that logic for queries on every protected table; keep the policy a simple comparison against a setting.
- The query planner (the part of PostgreSQL that chooses the plan, the kind of plan shown by
EXPLAINabove) will not push (reorder to run earlier than) user-supplied conditions that use non-leakproof functions ahead of the policy check. A function is leakproof if PostgreSQL can prove it never reveals anything about its input, not through its result, an error message, a log line, or even how long it takes to run; plain comparisons like=are leakproof, but an arbitrary user-defined function might, for example, raise an error that quotes the value it was checking, revealing a row's content even though the row was never returned. PostgreSQL cannot verify this for every function, so a non-leakproof user condition is never allowed to run before the tenant policy check, only after it. That ordering (policy check first, always) can occasionally produce a worse plan than letting a cheap-looking user condition run first. CheckEXPLAINon hot queries after enabling RLS.
Production gotchas
| Gotcha | What happens | Fix |
|---|---|---|
Superuser and BYPASSRLS roles | Always bypass policies | The application must never connect as a superuser or a role with BYPASSRLS |
| Table owner | The owner bypasses RLS unless the table is set to FORCE ROW LEVEL SECURITY (in the script above, the non-superuser owner app_owner saw 2 rows before FORCE and 1 after) | Have migrations run as the owner, the application as a separate role, and use FORCE as a backstop |
| Connection pooling | SET persists on the pooled connection into the next request (step 6); PgBouncer (a widely used PostgreSQL connection pooler) in transaction mode hands the same physical connection to a different client at each transaction boundary, so a plain session SET left behind by one client can still be active on that connection when a completely different client's next transaction begins, silently applying the wrong tenant to their queries | Use SET LOCAL (or set_config(..., true)) inside the transaction, never session SET |
| Views | Run as the view owner, bypassing the caller's policies (step 7) | security_invoker = true on PostgreSQL 15+, or have views owned by a non-bypassing role |
| Tenant ID from untrusted input | If the tenant value comes from a request header or, worse, is built into SQL by string concatenation, an attacker can switch tenant or inject SQL | Take the tenant from the authenticated token, pass it as a bound parameter to set_config('app.tenant_id', $1, true) |
| Unique constraints and foreign keys | These are checked across all rows regardless of RLS, so "email already exists" can reveal another tenant's data | Make uniqueness per tenant: UNIQUE (tenant_id, email) |
| Missing context | A policy that errors or matches everything when the setting is absent | Fail closed, as with the NULLIF form above |
When RLS is the right choice, and when it is not
Right choice: a shared-schema SaaS (software as a service) product with many small tenants on PostgreSQL, where the risk you most want to remove is a developer forgetting a tenant filter; internal analytics databases where many teams share tables but must see only their own rows.
Not the right choice (or not enough on its own):
- Tenants that need a separate encryption key, separate backup and restore, or proof of physical separation: use a database or infrastructure per tenant.
- Workloads where one tenant's queries overload the database: RLS isolates data, not performance.
- Heavy reporting through views, materialized views or ETL (extract, transform, load) jobs that run as privileged roles: those paths bypass RLS and need their own tenant filtering.
- Very complex policies (hierarchical sharing across tenants): the per-query cost and the difficulty of reasoning about them usually argue for authorization in the application plus a simple RLS tenant check underneath.
Design a tenant-aware backpressure and queueing system for a multi-tenant SaaS product with bursty workloads. Explain fair-share algorithms, per-tenant quotas, circuit-breakers per tenant, and how to avoid noisy-neighbor problems without over-provisioning.
Sample Answer
Direct answer
The core change is to stop putting all tenants' work in one first-in first-out (FIFO) queue. I would give each tenant its own bounded queue, have workers pull from those queues with a weighted fair-share scheduler (deficit round robin), cap each tenant's in-flight work with a quota, and push back on a tenant whose queue is full with a retryable rejection instead of letting its backlog grow. Per-tenant circuit breakers stop one tenant's failing dependency from tying up shared workers. Together these let one tenant's burst use idle capacity, while making it impossible for that burst to delay everyone else, so you do not need to provision for every tenant's peak at once.
Why a shared FIFO queue fails
With one queue, a tenant that drops 500 jobs at once puts every other tenant's next job behind all 500. Nobody did anything wrong; the queue discipline simply gives the earliest arrivals all the capacity. Adding workers only shortens the delay in proportion to the extra spend, which is the over-provisioning we want to avoid.
Backpressure is the general answer: when a system is full, it signals producers to slow down instead of accepting unbounded work. In a multi-tenant system, the signal must be per tenant, so that only the tenant causing the pressure is slowed.
Architecture
flowchart LR
C[Tenant clients] --> A[Admission: auth, tenant ID, quota check]
A -->|queue full| R[429 + Retry-After]
A --> Q1[Queue tenant A]
A --> Q2[Queue tenant B]
A --> Q3[Queue tenant C]
Q1 --> S[Fair-share scheduler]
Q2 --> S
Q3 --> S
S --> W[Shared worker pool]
W --> CB[Per-tenant circuit breakers]
CB --> D[Downstream dependencies]
1. Admission. Identify the tenant from its credentials (never from a client-supplied field), check its rate quota (for example a token bucket: a per-tenant allowance that refills at a fixed rate), and check its queue depth. If the queue is at its bound, reject with HTTP 429 and a Retry-After header. This is where backpressure becomes visible to the producer.
2. Per-tenant bounded queues. Physically these can be one table or stream partitioned by tenant, or a set of logical queues in the scheduler. The bound per tenant is set by tier (e.g. 200 queued jobs for a standard tenant, 2,000 for enterprise), which is what caps any one tenant's claim on memory and latency.
3. Fair-share scheduler. Deficit round robin (DRR) visits each non-empty tenant queue in turn and gives it a "quantum" of work credit per round (its weight); a tenant spends credit to dispatch jobs, and unspent credit carries over only while it has jobs waiting. With equal weights it is plain round robin; with weights 1:2:4 for free, standard and enterprise tiers, capacity divides in that ratio when everyone is busy. Crucially, it is work-conserving: if only one tenant has work, that tenant gets all the workers. That is how one tenant's burst uses idle capacity without taking capacity other tenants need. If job costs vary a lot, charge the quantum in estimated cost units (seconds of work) rather than job count.
4. Per-tenant concurrency quota. Independently of the scheduler, cap how many jobs a tenant can have running at once (e.g. 20% of workers for a standard tenant). This protects against a tenant whose jobs are individually slow, which fair ordering alone does not.
5. Per-tenant circuit breakers. A circuit breaker watches calls to a dependency and, once the failure rate crosses a threshold, fails further calls immediately for a cool-down period instead of letting them hang. Keyed per tenant (and per dependency), it handles the case where one tenant's jobs call something tenant-specific that is broken (its webhook endpoint, its connected database, its bad configuration). Without it, that tenant's jobs sit on shared workers waiting on timeouts. With it, the tenant's jobs fail fast (and are retried later or dead-lettered, i.e. moved to a DLQ, a dead-letter queue for jobs that keep failing) and the workers go back to everyone else.
6. Load shedding under global overload. If the whole system is saturated, shed in order: free-tier background work first, then retries, then new standard work; never an enterprise tenant's in-flight job.
Worked example (executed)
A pool completes 10 jobs per tick. Tenant a submits a burst of 500 jobs at tick 0; tenants b, c, d, e each submit 2 jobs per tick, steadily. Compare one FIFO queue with per-tenant queues (bound 200) served round robin.
from collections import deque
CAPACITY = 10 # jobs the worker pool finishes per tick
TICKS = 100
SMALL = ["b", "c", "d", "e"] # steady tenants: 2 jobs per tick each
BURST = 500 # tenant "a" dumps 500 jobs at tick 0
QUEUE_CAP = 200 # per-tenant queue bound (used by fair mode only)
def arrivals(t):
jobs = [("a", t)] * BURST if t == 0 else []
for s in SMALL:
jobs += [(s, t)] * 2
return jobs
def pct(values, p):
v = sorted(values)
return v[min(len(v) - 1, int(p / 100 * len(v)))]
def run_fifo():
q, waits, rejected = deque(), {}, 0
for t in range(TICKS):
q.extend(arrivals(t))
for _ in range(min(CAPACITY, len(q))):
tenant, arrived = q.popleft()
waits.setdefault(tenant, []).append(t - arrived)
return waits, rejected, len(q)
def run_fair():
queues = {x: deque() for x in ["a"] + SMALL}
waits, rejected = {}, 0
for t in range(TICKS):
for tenant, arrived in arrivals(t):
if len(queues[tenant]) >= QUEUE_CAP:
rejected += 1 # backpressure: caller gets 429 + Retry-After
else:
queues[tenant].append((tenant, arrived))
served = 0
while served < CAPACITY and any(queues.values()):
for tenant in queues: # round-robin, quantum = 1 job per visit
if served < CAPACITY and queues[tenant]:
_, arrived = queues[tenant].popleft()
waits.setdefault(tenant, []).append(t - arrived)
served += 1
return waits, rejected, sum(len(q) for q in queues.values())
for name, fn in [("FIFO", run_fifo), ("fair-share", run_fair)]:
waits, rejected, backlog = fn()
small = [w for s in SMALL for w in waits.get(s, [])]
print(f"{name:10s} small-tenant p99 wait={pct(small, 99)} ticks, "
f"small jobs done={len(small)}, burst jobs done={len(waits.get('a', []))}, "
f"rejected={rejected}, backlog={backlog}")
Output (Python 3):
FIFO small-tenant p99 wait=50 ticks, small jobs done=500, burst jobs done=500, rejected=0, backlog=300
fair-share small-tenant p99 wait=0 ticks, small jobs done=800, burst jobs done=200, rejected=300, backlog=0
Reading it: under FIFO the four well-behaved tenants waited up to 50 ticks at the 99th percentile (p99) and had 300 jobs still stuck at the end, because the burst went first. Under fair share their p99 wait was 0 ticks and all 800 of their jobs finished. Tenant a still got the 2 spare slots per tick (10 capacity minus 8 from the steady tenants), finishing 200 jobs, and its other 300 were rejected at admission and must be retried later. Same worker count, no extra capacity: the only thing that changed is who absorbs the burst. Tenant a does.
Avoiding over-provisioning
Provision for the sum of guaranteed shares plus a modest burst buffer, not the sum of peaks. Because DRR is work-conserving, idle capacity is still lent to whoever is bursting, so utilisation stays high. Scale out the worker pool on the metric that means "tenants inside their quota are waiting" (queue age of in-quota work), not on total queue length, which a single bursting tenant can inflate on its own and which would make you buy capacity for that tenant's backlog.
Trade-offs and pitfalls
- Rejecting work moves the problem to the client. Clients must honour
Retry-Afterwith backoff and jitter (random spread), or the rejections come straight back as a retry storm. Offer an asynchronous submit-and-poll path for tenants who legitimately send large batches. - Thousands of tenants and a naive round robin scans many empty queues; keep an "active tenants" list containing only non-empty queues.
- Fairness by job count is unfair when job sizes differ. Charge cost units, or one tenant with 10-minute jobs still dominates.
- Circuit breakers keyed globally punish every tenant for one tenant's broken webhook; key them by tenant and dependency.
- Priority tiers without a floor starve the free tier. Give every tier a minimum weight so low-tier work always progresses.
You're designing microservices for a multi-tenant SaaS. Describe a robust approach to enforce per-tenant authorization across services. Discuss token design (what claims to include), tenant_id propagation, sidecar vs in-process checks, and how you prevent spoofing of tenant identifiers at service boundaries.
Sample Answer
Direct answer
The rule that makes everything else work: a service never believes a tenant ID it did not get from a verified source. The tenant is derived at login and carried in a signed token (a JWT, JSON Web Token: a small JSON document signed by the identity provider so any service can check it was not altered). The API gateway strips any client-supplied tenant header, every service validates the token itself rather than trusting its caller, a sidecar can do the generic checks, and the service's own code does the resource-level check ("does this invoice belong to this token's tenant?"), with row-level security (RLS: a database policy that automatically filters query results down to the session's own tenant) in the database as the last net.
Token design: which claims to include
A token issued after login looks like this:
{
"iss": "https://auth.example.com",
"aud": "api.example.com",
"sub": "user_8812",
"tenant_id": "t_acme",
"roles": ["billing_admin"],
"scope": "invoices:read invoices:write",
"iat": 1790000000,
"exp": 1790000900
}
| Claim | Purpose |
|---|---|
iss (issuer) | Which identity provider signed it; reject anything else |
aud (audience) | Which API it is meant for; stops a token for one system being replayed against another |
sub (subject) | The user |
tenant_id | The tenant the user is acting in, set by the identity provider from the user's membership, never from a request parameter |
roles / scope | What they may do within that tenant |
iat, exp | Issued-at and expiry; keep lifetime short (here 15 minutes, 1790000900 minus 1790000000 = 900 s) so a stolen token is useful briefly |
Keep tokens small: no lists of every resource the user can touch, no personal data.
Propagating tenant_id between services
- The gateway validates the token (signature, issuer, audience, expiry), and removes any incoming
X-Tenant-Idheader from the client. - Internal calls forward the original token (or a token exchanged for a narrower audience per downstream service, so a token stolen from one service cannot be used against another).
- Asynchronous work carries the tenant ID in the message envelope and is re-checked by the consumer against what it loads; background jobs are a common place for tenant context to be lost.
- Logs and traces include
tenant_idfrom the validated token, so you can audit which tenant each call acted for.
Sidecar vs in-process checks
A sidecar is a proxy running next to each service instance (for example Envoy in a service mesh, a layer that handles traffic between services) that can validate tokens before the request reaches the application.
| Sidecar | In-process (library in the service) | |
|---|---|---|
| Good at | Signature and expiry validation, mTLS (mutual TLS: both sides present certificates), coarse rules like "caller must be the billing service" | Checks that need business data: "invoice 42 belongs to t_acme" |
| Consistency | Same behaviour for every service, any language | Depends on each team using the shared library |
| Blind spot | Does not know which tenant owns a database row | Easy to forget in a new endpoint |
Recommendation: both. The sidecar handles authentication and coarse authorization uniformly; a shared in-process library does the tenant-ownership check against the data being loaded. Neither alone is enough.
Preventing tenant spoofing at service boundaries
- Derive, never accept. The tenant comes from the verified token. If a URL also contains a tenant (
/tenants/t_acme/invoices), the service checks it equals the token's tenant and returns 404 if not. - Validate at every hop, not just the gateway. A compromised internal service must not be able to call another with a made-up tenant.
- Authenticate services to each other with mTLS, so only known services can call a given endpoint at all.
- Scope data access: every query includes the tenant from the token, and the database enforces RLS (row-level security, a policy that filters rows by the session's tenant) as a backstop.
Worked example: a spoofing attempt
A user of tenant t_acme calls GET /tenants/t_globex/invoices/42 with a valid t_acme token and adds the header X-Tenant-Id: t_globex.
- Gateway: token valid; the
X-Tenant-Idheader is stripped. - Invoice service: path tenant
t_globexdoes not equal token tenantt_acme, so it returns 404. - Even if a bug skipped step 2, the query runs with the session tenant set to
t_acme, and RLS returns no rows for invoice 42 owned byt_globex.
Three independent layers; the attacker needs all three to fail.
Pitfalls
- Trusting internal traffic. "It came from inside the network" is not authentication.
- Long-lived tokens for convenience; tenant membership changes (a user removed from a tenant) then take hours to apply.
- Returning 403 instead of 404 for other tenants' resources reveals that the resource exists.
- Users in several tenants: the token must name the currently selected tenant, and switching tenants issues a new token.
Unlock Full Question Bank
Get access to all 8 Multi-Tenancy and Isolation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.