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.
For a multi-tenant API platform where one noisy tenant's traffic can degrade performance for every other tenant, design a fault-isolation strategy grounded in the bulkhead pattern. Cover resource controls, container or VM-level isolation, and protections you would apply at the request layer, and explain how each layer contains a single tenant's failure without cutting off healthy tenants.
Sample Answer
Direct answer
A bulkhead splits shared capacity into compartments so a flood in one compartment cannot sink the ship. For a multi-tenant API, I would build bulkheads at three layers: at the request layer, per-tenant rate limits, concurrency caps, fair queues, and circuit breakers so a noisy tenant is throttled before it consumes shared capacity; at the resource layer, per-tenant slices of connection pools, worker threads and CPU/memory quotas; at the container/VM layer, cells and shuffle-sharded worker assignment so that even an unbounded failure (a crash loop: a process that crashes, gets restarted, and crashes again immediately, over and over; a memory leak; a poison request: a single malformed or pathological request that reliably crashes whatever worker handles it, so simply retrying it just crashes the next worker too) only reaches a small, known group of tenants. Each layer contains the tenant by limiting what it can take, not by blocking everyone, so healthy tenants keep their share.
Terms used below
- Bulkhead pattern: partitioning resources so that failure or overload in one partition is contained there. Named after the watertight compartments of a ship.
- Noisy neighbour: a tenant whose load degrades others sharing the same resources.
- Concurrency limit: a cap on how many requests from one tenant can be in progress at once.
- Circuit breaker: a switch that stops calling a failing dependency for a while, returning errors fast instead of piling up waiting requests.
- Load shedding: deliberately rejecting some requests (with HTTP 429 or 503) to protect the rest.
- cgroups: the Linux kernel feature that limits CPU and memory per process group; container limits in Kubernetes use it.
- Cell: an independent copy of the service stack serving a subset of tenants.
- Round-robin: serving one item from each of several queues in turn, cycling through them, instead of fully draining one queue before touching the next.
- Shuffle sharding: each tenant is assigned a small random combination of workers, so two tenants rarely share all of them.
- Little's law: in-flight requests = arrival rate x time each request spends in the system.
Layer 1: request layer (first line, cheapest to act)
- Per-tenant rate limit (token bucket) at the gateway, sized to the tenant's plan.
- Per-tenant concurrency cap. Rate limits alone miss slow requests: a tenant sending modest traffic to an endpoint that has become slow can still hold many connections. Capping in-flight requests per tenant bounds its share directly.
- Fair queueing: when the service is busy, requests wait in per-tenant queues served round-robin (see "Terms used below"), so a tenant with 10,000 queued requests does not delay a tenant with 3.
- Per-tenant circuit breakers and timeouts on downstream calls: if tenant X's requests to its custom webhook or its large report query keep failing, trip the breaker for X only.
- Load shedding with priority: under overload, shed the tenant furthest over its fair share first, not requests at random.
How this contains without cutting others off: the noisy tenant gets HTTP 429 once over its limits; everyone else's requests still pass.
Layer 2: resource layer
- Partitioned pools: a database connection pool of 100 split into a shared reserve plus a per-tenant cap (for example no tenant may hold more than 10). A thread pool for expensive operations, with the same per-tenant cap.
- Separate pools for separate work: interactive API calls and bulk exports never share a pool, so one tenant's export does not starve another's login.
- Container quotas: Kubernetes CPU and memory limits per pod (a pod is the smallest deployable unit in Kubernetes, usually one running copy of the service, containing one or more containers; the limits are enforced through cgroups), and namespace resource quotas (a namespace resource quota is a Kubernetes-enforced ceiling on total CPU, memory and object count for everything in one namespace, a way to group a tenant's own set of pods and cap them as a whole) where a tenant has dedicated workloads.
- Database-side limits: statement timeouts (the database automatically cancels a single query if it runs longer than a configured limit) and per-role connection limits, so a runaway query from one tenant is killed rather than holding locks.
Layer 3: container/VM and placement
- Cells: tenants are split across cells, each a full stack. A cell-level failure affects only that cell's tenants.
- Shuffle sharding within a cell: each tenant is served by 2 of 16 worker groups.
- Dedicated node pools or VMs for the few largest tenants, and microVM sandboxes (lightweight VMs such as Firecracker) for any tenant-supplied code, because a container shares the host kernel and a VM does not. A container is really just a restricted, walled-off process (or group of processes) running under the one operating-system kernel (the core of the OS that manages memory, CPU scheduling and hardware) the host is running; every other container on that host, from every tenant, shares that same kernel, so a kernel-level bug or exploit reachable from one tenant's code has a path to the host and to other tenants' containers. A VM boots its own separate kernel on top of virtualised hardware, so the same bug stays contained inside that one VM.
Worked example
Concurrency bulkhead, using Little's law. A noisy tenant sends 2,000 requests per second and each takes 50 ms:
in-flight=2000 req/s×0.05 s=100That would take all 100 database connections. With a per-tenant cap of 10 in-flight requests, the most the tenant can complete is:
0.05 s10=200 req/sThe other 1,800 requests per second get 429s, and 90 connections remain for everyone else.
Shuffle sharding. With 16 worker groups and 2 per tenant, the number of distinct pairs is:
(216)=216×15=120If a poison request from one tenant crashes both of its worker groups, another tenant is fully cut off only if it has the identical pair: a 1 in 120 chance (about 0.8%). Every other tenant keeps at least one healthy group. Compare plain sharding into 8 fixed pairs, where every tenant on the noisy tenant's pair (1 in 8, 12.5%) is fully down.
flowchart TB
R[Requests] --> L1[Request layer<br/>rate limit, concurrency cap, fair queue]
L1 --> L2[Resource layer<br/>pool slices, cgroup limits]
L2 --> C1[Cell A<br/>shuffle-sharded workers]
L2 --> C2[Cell B<br/>shuffle-sharded workers]
C1 --> D1[(Cell A data)]
C2 --> D2[(Cell B data)]
Trade-offs and pitfalls
- Static partitions waste capacity. If each of 50 tenants gets a hard 2% of a pool, idle slices sit unused. Use a cap plus a shared reserve (work-conserving): tenants may borrow idle capacity but can never exceed their cap.
- Caps set too low throttle legitimate growth. Make them per plan, observable (tenants can see their usage), and adjustable without a deploy.
- Retries defeat bulkheads. A throttled tenant's clients retrying instantly multiply load. Return the
Retry-AfterHTTP header (it tells the client exactly how long to wait before trying again), and have your SDKs use exponential backoff with jitter (each retry waits roughly twice as long as the previous one, with a bit of randomness mixed in so retries from many clients spread out instead of all landing at the same instant). - Pitfall: bulkheads only at the edge. A gateway rate limit does not stop one expensive request from locking a shared table. The inner layers exist because some overload is shaped by cost, not count.
- What would change the design: very large or regulated tenants justify moving from shared cells to a dedicated cell, which is the strongest bulkhead but the most expensive.
Design a multi-tenant SaaS architecture that supports per-tenant configuration and data isolation while minimizing infrastructure cost. Requirements: up to 10,000 tenants, mixed sizes (90% small, 10% enterprise), ability to offer enterprise-only custom features, and an upgrade path from single-tenant to multi-tenant. Describe tenancy models, schema strategies, deployment options, and migration approach.
Sample Answer
Direct answer
I would run two tiers on one codebase: the 9,000 small tenants in a pooled tier (shared database, every row tagged with tenant_id, enforced by row-level security), and the 1,000 enterprise tenants in a bridge tier by default (shared application fleet, but a schema or database of their own on shared database clusters), with a silo option (fully dedicated stack) carved out of that same 1,000 and sold only to the handful of enterprises that need it for regulation, about 990 remaining in bridge day to day; the table below gives that split. A tenant registry decides where each tenant lives and which features it has, so enterprise-only features are entitlements, not forks. The move from single-tenant to multi-tenant is done tenant by tenant: make the code tenant-aware first, then migrate data with copy plus change capture, verify, and cut over with a rollback path.
Terms used below
- Tenant: one customer organisation. Multi-tenant means many tenants share infrastructure; single-tenant means each customer has its own deployment.
- Pool / bridge / silo: pool shares everything; silo dedicates everything; bridge shares some layers (usually compute) and dedicates others (usually data).
- Row-level security (RLS): a database feature that automatically adds a filter such as
tenant_id = current tenantto every query, so application code cannot forget it. - Schema: a namespace of tables inside one database. Schema-per-tenant gives each tenant its own copy of the tables.
- CDC (change-data-capture): streaming every insert, update and delete from a database's log so a copy can be kept in sync.
- Noisy neighbour: a tenant whose load slows others sharing the same resources.
1. Tenancy models per segment
| Segment | Count | Model | Why |
|---|---|---|---|
| Small | 9,000 | Pool: shared schema, tenant_id column, RLS | Per-tenant cost must be near zero; a dedicated anything per tenant would dominate the bill |
| Enterprise | ~990 | Bridge: shared app tier, schema-per-tenant (or database-per-tenant) on shared clusters | Clean per-tenant backup/restore, per-tenant encryption keys, easy export, noisy-neighbour control at the database level |
| Regulated enterprise | handful | Silo: dedicated account, network, database | Contractual or regulatory need (customer-managed keys, data residency, own change windows) |
I would not use schema-per-tenant for all 10,000. Every schema change must run once per schema: at an assumed 2 seconds per schema, that is 10,000 x 2 s = 20,000 s, about 5.6 hours per release, versus (rounding the ~990 bridge schemas up to an even 1,000 for the estimate) 1,000 x 2 s = 2,000 s, about 33 minutes, for the enterprise tier alone; the ~10 silo tenants run their own dedicated databases outside this per-release schema sweep entirely, which is exactly why they are excluded from the count. Very large numbers of schemas also bloat the database catalog (the internal tables describing all tables), slowing planning and backups.
2. Schema strategy and per-tenant configuration
Pooled tables: every table has tenant_id as the first column of its primary key, e.g. (tenant_id, order_id). This keeps a tenant's rows together in indexes and makes future sharding (splitting one logical dataset across several physical databases, each holding a share of it) by tenant a simple range split (cutting the space of tenant_id values into contiguous chunks and giving each chunk its own shard, rather than a more disruptive reshuffle).
Tenant registry (the single source of truth, cached in every service):
| Field | Example |
|---|---|
tenant_id | t-08812 |
tier | pool / bridge / silo |
placement | pg-cluster-3/schema_t08812 |
entitlements | ["sso","audit_export","custom_workflows"] |
config | JSON: branding, limits, locale, retention |
schema_version | 2026.09.1 |
status | active / migrating / suspended |
Enterprise-only custom features: implemented once, switched on through entitlements checked by a feature-flag service (a service that answers "is feature X on for tenant Y"). Custom fields go in a typed extension table (tenant_id, entity_id, field_key, value) or a validated JSON column, with per-tenant field definitions in the registry. What is never allowed: a per-customer code branch. That is the path back to 1,000 single-tenant products.
3. Deployment options
- One application fleet for pool and bridge tenants, deployed by one pipeline. A request's tenant is resolved from the login token, the registry supplies placement, and the data layer connects to the right cluster and sets the tenant context (for RLS) or the schema.
- Cells: split the pool into cells of about 2,000 tenants each (a cell is a full copy of the stack serving a subset of tenants), so a bad deploy or overloaded database hits at most 2,000 / 10,000 = 20% of tenants. Deploy to one cell first.
- Silo tenants get the same artifacts through the same pipeline, deployed later in the rollout order, so they are never on a different code version for long.
flowchart TB
U[Request with token] --> GW[Gateway: resolve tenant]
GW --> REG[(Tenant registry)]
GW --> APP[Shared app fleet]
APP -->|pool| PDB[(Pooled DB + RLS)]
APP -->|bridge| BDB[(Schema per tenant<br/>on shared clusters)]
GW -->|silo| SILO[Dedicated stack]
4. Data partitioning and virtualization for the data pipeline
The analytics pipeline needs the same boundaries as the application:
- Partitioning: lake tables (tables in the analytics data lake, the large repository of raw and processed data used for analytics rather than live application queries) partitioned by
tenant_bucket(a hash oftenant_idinto, say, 64 buckets) and date, withtenant_ida column in every row. Partitioning by rawtenant_idwould create 10,000 x 365 small partitions a year, which slows query planning (the step where the query engine decides which partitions and indexes it actually needs to read before running the query); buckets keep partition counts bounded while still pruning (letting the engine skip whole partitions that cannot match the query's filter, instead of scanning them). - Virtualization: tenants never see shared tables directly. Each tenant gets views (virtual tables defined as a query) filtered on its
tenant_id, or the query engine applies a row filter from the caller's identity. To the tenant it looks like a private dataset; physically it is one table. - Enterprise exports: bridge tenants can get physically separate output (their own prefix in object storage, their own encryption key) because the pipeline writes partitioned by tenant anyway.
5. Migration approach: single-tenant to multi-tenant
Worked example: 100 existing single-tenant deployments (each customer has its own app and database) moving into the pool.
- Make the code tenant-aware while still single-tenant. Add
tenant_idto every table and every query, set it to a constant in each old deployment, turn RLS on. Behaviour is unchanged, so this ships safely. - Resolve identifier collisions. Each old database has its own order 1, order 2, and so on. Composite keys
(tenant_id, order_id)avoid rewriting IDs; anything exposed externally (URLs, webhooks) keeps working because the tenant is part of the lookup. - Bulk copy plus CDC catch-up. Copy the tenant's data into the pool with its
tenant_id, then stream changes via CDC until the lag is seconds. - Verify before cutover. Per table: row counts and checksums between source and target; a replay of a sample of real read requests against both, comparing responses; and a cross-tenant leak test: log in as the migrated tenant and assert that queries return zero rows belonging to any other tenant, and vice versa.
- Cut over: a brief write freeze (the tenant's writes are paused, seconds to minutes, while reads keep working), a final CDC drain (let the change-data-capture stream fully catch up so no write is left unsynced), flip the registry's placement, unfreeze. Keep the old deployment read-only for a rollback window (for example 14 days).
- Waves: internal and test tenants first (not counted in the 100 below), then 5, then 20, then the rest, all cut over at the same steady 5 tenants a night: the 5-tenant wave takes 5 / 5 = 1 night, the 20-tenant wave takes 20 / 5 = 4 nights, and the remaining 100 - 5 - 20 = 75 tenants take 75 / 5 = 15 nights, for 1 + 4 + 15 = 20 nights total, matching 100 / 5 = 20. The wave sizes only control the order tenants move in and how much blast radius one bad night can reach; the nightly rate is what sets the calendar.
The same move runs in reverse for tier changes: a small tenant upgrading to enterprise is copied from the pool into its own schema with the same copy, CDC, verify, flip sequence, so the upgrade path is a tested procedure rather than a one-off.
Trade-offs and pitfalls
- Pool's weakness is blast radius: one missing filter exposes many tenants. RLS plus automated leak tests on every release are non-negotiable.
- Bridge's weakness is operational fan-out: ~990 schemas means migrations, connection pools (the set of already-open database connections a service reuses instead of opening a new one per request) and monitoring per schema. Automate or it collapses.
- What would flip the split: if most revenue came from a few hundred very large tenants with strict isolation needs, I would push more of them to database-per-tenant and accept the cost; if enterprise tenants were small in data, I would keep them pooled and sell isolation through dedicated keys and cells instead.
- Pitfall: letting "enterprise custom features" become per-customer code. Every exception must be expressible as registry configuration.
Describe an incremental migration strategy to move a tenant from a shared schema to a dedicated database with minimal downtime, for example when onboarding an enterprise customer who requires stronger isolation than the shared tier provides. Cover the data-sync approach (full copy plus change-data-capture for deltas), the cutover process including dual-writes, validation checks, the rollback plan, and how you handle referential integrity, secondary indexes, and any schema changes that land during the migration window.
Sample Answer
Direct answer
Copy the tenant's rows from the shared schema into a new dedicated database, keep the copy current with change-data-capture (CDC: reading the database's change log and replaying inserts, updates and deletes), prove the two sides match, then cut over with a short per-tenant write freeze and a routing flip. Keep CDC running in reverse after cutover so rollback is a routing flip too. I prefer CDC plus a brief freeze over application dual-writes, and I use dual-writes only in a narrow, verified form if the tenant cannot tolerate even a few seconds of paused writes.
The usual trigger: an enterprise customer is onboarding and their security review requires stronger isolation than a shared table filtered by tenant_id gives them, for example their own database with its own encryption key.
The plan
flowchart LR
A[Provision dedicated DB] --> B[Snapshot copy at log position L0]
B --> C[CDC replays changes after L0]
C --> D[Validate counts and checksums]
D --> E[Freeze tenant writes]
E --> F[Drain CDC, final check]
F --> G[Flip routing]
G --> H[Reverse CDC for rollback]
1. Provision
Create the dedicated database with the same schema version as the shared one, its own credentials and its own encryption key. Create tables and primary keys, but defer secondary indexes and foreign keys (constraints that say "this order's customer_id must exist in customers") until after the bulk copy; loading into a table that has to maintain five indexes row by row is several times slower than building them once at the end.
2. Full copy plus CDC
- Take a consistent snapshot of the tenant's rows, recording the log position
L0the snapshot corresponds to. In Postgres, creating a logical replication slot (a named, durable bookmark the server keeps, guaranteeing it retains every change made after a given point until you have streamed it, even if your consumer disconnects for a while) gives you both a snapshot and the position to stream from. - Copy
WHERE tenant_id = Xfor each table from that snapshot. - Start a CDC stream from
L0, filtered to this tenant's rows, and apply it to the new database. Apply is idempotent (an upsert, a write that inserts the row if it is new or updates it in place if it already exists, keyed on primary key), so replaying the same change twice is harmless.
3. Referential integrity and indexes
- Copy parent tables before child tables, or load everything and add foreign keys afterwards with a validation pass. In Postgres,
ADD CONSTRAINT ... NOT VALIDfollowed byVALIDATE CONSTRAINTchecks existing rows without blocking writes for the whole check. - CDC applies changes in commit order across tables, so a transaction that inserts an order and its line items arrives together. Apply it as a transaction on the target, otherwise a reader of the new database can briefly see line items with no order.
- Check that no row references another tenant's data (in a shared schema this is a real bug class, for example a lookup table row shared across tenants). Shared reference data must be copied as a separate, explicit step.
- IDs: if the shared schema uses one global sequence (a single counter the database uses to generate the next id, shared across all tenants rather than per-tenant), copy IDs unchanged and set the new database's sequences (the database objects that hand out the next id) above the highest copied value. Never renumber, because IDs leak into URLs, exports and the customer's integrations.
4. Schema changes during the window
The safest rule is a DDL freeze (DDL: data definition language, meaning CREATE/ALTER/DROP) for the migration window. If the window is long, the migration tooling must apply each migration to the new database first (additive changes like a new nullable column are safe there), then to the shared schema, and CDC must be paused around the change, because most logical CDC streams carry row changes, not schema changes. A destructive change (drop or rename a column) waits until after cutover.
5. Validation
Before cutover and again during the freeze:
- Row count per table for the tenant, both sides.
- Checksum per table: hash of every row sorted by primary key, computed in chunks (for example 10,000 keys at a time) so a mismatch is located to a chunk and not rescanned whole.
- Application checks: sums of balances, counts per status.
6. Cutover
- Confirm CDC lag (how far behind the CDC stream is from the source's latest committed writes) is under one second.
- Freeze writes for this tenant only (the app returns a retryable "try again shortly" or queues writes). Other tenants are unaffected.
- Wait until CDC has applied up to the log position at the moment of the freeze. Run a final count check on the hot tables (the tables that see the most writes, and so are most likely to have changed since the last check).
- Flip routing for the tenant to the new database, with a bumped version so any app instance holding a stale route is rejected.
- Unfreeze. Start reverse CDC (new to old) so the shared copy stays current.
Expected write pause: a few seconds to tens of seconds.
If dual-writes are required (no freeze allowed), concretely: (1) the app keeps writing to the shared schema as before, the still-authoritative source, and mirrors each write to the new database asynchronously; (2) once the continuous comparison has matched for a sustained period, flip reads only, so the app reads from the new database while still writing to both, and any disagreement is now visible to users, which is why step 1's verification has to be solid first; (3) once reads have run clean through a bake period, flip the source of truth, so the app now treats the new database as authoritative and the shared-schema write becomes the safety net instead of the other way around. Dual-writes from the application are hard to make correct: if one write succeeds and the other fails, the sides diverge, and retries can reorder updates. That is why I treat them as a fallback and still verify with checksums.
7. Rollback
Before deleting anything: rollback is freeze, drain reverse CDC, flip routing back to the shared schema, unfreeze. Keep the tenant's shared-schema rows (read-only for others, untouched) for a defined period, say two weeks, then delete them and record the deletion for the customer's audit.
Worked example
Tenant: 200 GB in the shared schema, 300 writes per second. Measured copy throughput 80 MB/s; CDC apply rate 3,000 changes per second.
- Full copy: 200,000 MB / 80 MB/s = 2,500 s, about 41.7 minutes.
- Changes that pile up during the copy: 2,500 s x 300/s = 750,000.
- Catch-up: CDC closes the gap at the apply rate minus the incoming rate, 3,000 - 300 = 2,700 changes per second, so 750,000 / 2,700 = about 278 s, roughly 4.6 minutes. (Dividing by 3,000 would understate it, because new changes keep arriving while you catch up.)
- Index and foreign key build afterwards, then validation, then a cutover freeze that in practice lasts 5 to 15 s.
Trade-offs and pitfalls
- Freeze versus dual-write: a few seconds of retryable errors for one tenant is almost always cheaper than debugging divergence. Choose dual-writes only when the contract forbids any pause.
- Pitfall: validating only row counts. Counts match while values differ (an update CDC missed). Checksums are what catch it.
- Pitfall: forgetting non-database state: cache keys, search index entries, files in object storage, and scheduled jobs that still target the shared schema.
- Pitfall: tenant filter on CDC done in the application after the fact. Filter at the source and assert every applied row's
tenant_idequals the migrating tenant, so another tenant's data can never land in this customer's dedicated database.
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 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.
Unlock Full Question Bank
Get access to all 19 Multi-Tenancy and Isolation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.