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.
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.
List the most common causes of cross-tenant data leakage in multi-tenant systems (for example misconfigured ACLs, shared caches, improper log sanitization, SQL bugs). For each cause propose immediate mitigations and longer-term architectural controls you would recommend as a Solutions Architect.
Sample Answer
Direct answer
Cross-tenant leaks almost never come from a broken isolation model. They come from one code path that forgot which tenant it was working for: a query without the tenant filter, a cache key without the tenant in it, a background job that lost the tenant context, or a log line that copied customer data somewhere shared. So the short-term fix for each cause is a targeted patch, and the long-term control is always the same idea: make the tenant identity travel with every request automatically and get enforced at the layer that stores or serves the data, so a developer cannot forget it.
Where the tenant identity should come from
A tenant context is the answer to "which customer is this request for?". The rule that prevents most leaks: derive it from the authenticated identity (for example a claim inside the signed login token), never from a URL parameter, header or request body the caller controls. Then pass it down explicitly to every database call, cache call, queue message and log statement.
Causes, immediate mitigations and architectural controls
| Cause | How it leaks | Immediate mitigation | Longer-term architectural control |
|---|---|---|---|
| Misconfigured ACLs (access control lists: who may read which object) | A storage bucket, share or IAM (identity and access management) policy grants a wildcard or grants tenant B's role access to tenant A's prefix | Audit and remove wildcard grants; rotate any credentials that were over-scoped; check access logs for reads by the wrong principal (principal: the authenticated identity, a user or a service, that a permission is granted to) | Generate policies from code (infrastructure as code) with one role per tenant or per-tenant conditions; run automated policy scans in the deploy pipeline; per-tenant encryption keys so a wrong grant still yields ciphertext |
| Shared caches | Cache key is user_profile:123 instead of t42:user_profile:123, so two tenants with the same internal ID read each other's entry; or a CDN (content delivery network, a cache at the network edge) caches an authenticated response | Flush the cache; add the tenant to every key; mark authenticated responses Cache-Control: private (a header telling any shared cache or CDN along the way not to store or serve this response to anyone else) | A cache client wrapper that requires a tenant argument and builds the key itself; separate cache namespaces or clusters for high-isolation tenants |
| Improper log sanitization | Request bodies, SQL parameters or error payloads containing customer data land in a shared log index that support staff or other tenants' dashboards can query | Purge the affected log indices; turn off body logging; restrict log access | Structured logging with an allow-list of fields; redaction at the log shipper; tenant ID as a field so per-tenant log views are filters enforced by the log platform |
| SQL bugs | A query or report is missing WHERE tenant_id = ?, or a join matches on user_id alone and pulls rows from another tenant | Hotfix the query; search the codebase for queries on tenant tables without the filter | Database row-level security (RLS: the database adds the tenant filter to every query itself); a data-access layer that refuses tenant tables without a tenant context; composite keys that include tenant_id so joins cannot cross tenants |
| Insecure direct object references (IDOR) | GET /invoices/9876 returns invoice 9876 without checking it belongs to the caller's tenant | Add an ownership check on the endpoint | Look objects up by (tenant_id, id) everywhere, never by id alone; use random, non-sequential IDs as defence in depth |
| Background jobs and queues | A worker processes a message but the tenant context was not included in it, so it falls back to a default or to the previous job's tenant | Reject messages with no tenant field | Message envelope schema with a mandatory tenant field; the worker framework sets and clears tenant context per message |
| Connection-pool session state | A request sets app.tenant_id on a pooled database connection (one of a shared set of already-open connections, reused across requests instead of opening a new one each time) and the next request on that connection inherits it | Reset session state on connection check-in | Scope the setting to the transaction (for example PostgreSQL SET LOCAL, which sets the value only until the current transaction ends rather than for the whole connection), so it disappears at commit |
| Shared search indexes and derived data | Search, analytics exports or a vector index for AI features (a search index built from numeric representations of documents, used for similarity search) built from all tenants' documents return other tenants' results | Filter results by tenant at query time | Per-tenant indexes or a mandatory tenant filter enforced by the search service, never by the caller |
Worked example: the cache-key leak
A SaaS (software as a service) product caches user profiles under profile:{user_id}. User IDs are per-tenant sequences, so tenant A and tenant B both have user 17. Tenant A's user 17 logs in, the profile is cached, and ten seconds later tenant B's user 17 sees A's name and email.
- Contain: flush
profile:*, deploy the key change tot{tenant_id}:profile:{user_id}, and pull cache-hit logs for the exposure window to list affected tenants for disclosure. - Fix the class, not the instance: replace direct cache calls with
cache.get(tenant, key), which prepends the tenant itself, and add a lint rule that bans the raw client outside that wrapper. - Prove it: a test suite that creates two tenants with deliberately colliding IDs (same user ID, same invoice number) and asserts that every API read as tenant A returns nothing of tenant B's. Run it in CI (continuous integration) on every change.
Trade-offs and pitfalls
- Enforce at the lowest layer you can afford. Application-level filters depend on every developer remembering; RLS and wrapper clients do not. The cost is some performance and debugging friction, which is worth it for customer data.
- Admin and support tools are a common leak path, because they are built to see across tenants. Give them an explicit "act as tenant X" mode with audit logging rather than blanket read access.
- Do not trust tenant IDs from the client. A tenant ID in a header is an input to validate against the token, not a source of truth.
- Detection matters as much as prevention. Emit an alarm when any query returns rows whose
tenant_iddiffers from the request's tenant; this catches the bug you did not anticipate. - Stronger isolation (separate databases or keys) reduces blast radius but does not remove these bugs: a shared cache or log pipeline can still leak across dedicated databases.
Compare cloud network isolation options to enforce tenant separation: VPC per tenant, VPC peering, PrivateLink/Private Service Connect, and service-mesh-level isolation. For a data platform that serves thousands of tenants, discuss scalability, cost, operational overhead, and security.
Sample Answer
Direct answer
For a data platform with thousands of tenants I would not use a VPC per tenant or peering as the default boundary: both hit hard quota and routing limits long before a few thousand tenants, and they multiply operational work. I would run the multi-tenant data plane in a small number of shared networks, enforce tenant separation inside them with service-mesh identity and authorization (every call carries a cryptographic workload identity, and policy decides which tenant's resources it may reach), expose the platform to tenants' own networks through PrivateLink (AWS) or Private Service Connect (PSC, the Google Cloud equivalent), and reserve a dedicated VPC in a dedicated account for the few tenants whose contracts or regulators require network-level separation.
The four options, defined
- VPC per tenant. A VPC (Virtual Private Cloud) is an isolated private network in a cloud account. Giving each tenant one means their resources share no network at all with other tenants.
- VPC peering. A private, non-transitive link between two VPCs: A peered with B and B peered with C does not let A reach C. Both sides must have non-overlapping IP address ranges.
- PrivateLink / Private Service Connect. The provider publishes a service behind a load balancer; a consumer creates an endpoint (specifically an interface endpoint: a private IP in the consumer's own network) that reaches only that service. Traffic is one-directional (consumer to service), and the two networks' IP ranges may overlap because no routes are exchanged.
- Service-mesh isolation. A service mesh (e.g. Istio) puts a proxy beside every workload (a sidecar) or in the node, which enforces mTLS (mutual TLS: both sides prove their identity with certificates, issued and vouched for by a certificate authority, the trusted party whose signature both sides check) and per-request authorization policies. The boundary is identity-based, at layer 7 (the request level), rather than network-address-based.
- Networking terms used in the comparison below. A security group is a virtual firewall attached to cloud resources that allows or denies traffic by IP address and port, an address-based control, unlike the mesh's identity-based policy. An Availability Zone (AZ) is one of several physically separate data centers inside a cloud Region; spreading a resource across AZs (for example, one endpoint per AZ) protects against a single data center failing, which is why the cost example below multiplies by 3. A hub (in "hub to tenant VPCs") is a central VPC that every tenant VPC peers with individually, rather than tenants peering with each other. A mesh's control plane is the shared component that distributes identity, certificates and policy to every proxy: it is shared infrastructure, so its own capacity, not a per-network quota, is what limits how many workloads it can serve. Egress is traffic leaving a network for a destination outside it, the opposite of ingress. Kubernetes NetworkPolicy is a Kubernetes-native rule that allows or denies traffic between pods by label and namespace, enforced by the cluster's own networking rather than by a sidecar proxy.
Comparison for thousands of tenants
| VPC per tenant | VPC peering (hub to tenant VPCs) | PrivateLink / PSC | Service mesh in shared VPCs | |
|---|---|---|---|---|
| Scalability | AWS defaults to 5 VPCs per Region per account, raisable to hundreds; thousands of tenants means hundreds of accounts (at the default quota: 3,000 / 5 = 600 accounts) | AWS caps active peerings per VPC at 50 by default, 125 maximum, so one hub cannot reach thousands of tenant VPCs; every tenant needs a non-overlapping range | One endpoint service serves many consumers; overlapping tenant IP ranges are fine | Scales with the mesh control plane, not with network quotas |
| Cost | A full network stack per tenant (network address translation (NAT) gateways for outbound traffic, endpoints, load balancers) repeated thousands of times | Peering has no hourly charge (normal data-transfer charges still apply); the real cost is operational | Per endpoint, per Availability Zone, per hour, plus per GB processed (see example) | Proxy CPU and memory overhead on every workload |
| Operational overhead | Very high: thousands of networks to patch, monitor and route | High: IP address planning across thousands of ranges, route tables, non-transitivity workarounds | Moderate: endpoint lifecycle per tenant connection | Moderate to high: certificate rotation, policy management, mesh upgrades |
| Security boundary | Strongest: no shared network | Network-level, but peering exposes whole address ranges unless security groups are tight | Narrow: the consumer can reach exactly one service and nothing else | Strong if policy is default-deny; relies on correct identity and policy, not network separation |
| Tenant-facing use | Dedicated deployments | Rarely a good fit for customer networks (IP overlap, trust) | Best fit for connecting tenants' own networks to the platform privately | Internal only; tenants never see it |
The quota figures above are from AWS's documented VPC and peering quotas; Google Cloud has comparable per-network peering quotas, which is why the same conclusion holds there.
Worked example: 3,000 tenants connecting privately
Suppose 3,000 tenants each connect from their own AWS network through an interface endpoint spread over 3 Availability Zones, and each moves 50 GB a month through it. AWS lists PrivateLink data processing at $0.01 per GB for the first petabyte; the hourly rate per endpoint per Availability Zone is about $0.01 in most Regions (check the current price for yours).
endpoint hours per tenant per monthacross 3,000 tenantsdata processing=0.01×3×730=$21.90=21.90×3000=$65,700=50×0.01×3000=$1,500Two things follow. First, the endpoint is created in the tenant's account, so the tenant's bill carries most of that, which is why private connectivity is usually an enterprise-tier feature. Second, the provider side is one endpoint service, not 3,000 networks: the platform's own cost and operational work grow slowly with tenant count.
Compare VPC-per-tenant for the same 3,000 tenants: at a few hundred VPCs per account (say 300, after requesting the quota increase mentioned above), that is 3,000 / 300 = 10 or more AWS accounts purely to hold networks, each tenant network with its own NAT gateways, security groups (virtual firewalls scoped to a resource, allowing or denying traffic by IP and port), monitoring and change process. Without that increase, at the default of 5 VPCs per account, the same 3,000 tenants need the 600 accounts computed above; either way it is the operational cost, not the account count itself, that makes VPC-per-tenant the wrong default.
The recommended layered design
- Shared data-plane VPCs (a handful, per Region), sized for many tenants' workloads.
- Mesh for tenant separation inside them: default-deny authorization; every workload's identity encodes the tenant it serves (for tenant-dedicated workers) or the platform role (for shared services), and policies say which identities may call which services. Shared services must still check the tenant in the request against the caller's identity; the mesh cannot do that for data inside a shared database.
- Network policy underneath the mesh (Kubernetes NetworkPolicy or security groups) so that a workload that bypasses its proxy (for example, a misconfigured pod that opens a raw connection instead of going through its sidecar, or an attacker who gains code execution on the host directly) still cannot reach arbitrary addresses. Mesh plus network policy is defence in depth: two independent layers, so a hole in one (a missed mesh policy) is still caught by the other (the network-level rule).
- PrivateLink / PSC for ingress from tenant networks, so no tenant's network is ever routed to the platform's and IP overlap is irrelevant.
- Dedicated VPC in a dedicated account for the few tenants who need it, provisioned by the same automation so it is a configuration choice, not a fork.
What would flip the choice: a small number of very large, regulated tenants (tens, not thousands) makes VPC per tenant affordable and simplifies audits; tenants running their own code inside the platform (not just sending data) raises the bar toward separate VPCs or accounts, because a mesh policy is a weaker boundary against hostile code running inside the network than a separate network is.
Trade-offs and pitfalls
- Peering as a tenant-onboarding path fails on the first customer whose IP range overlaps yours, and peering exposes more than one service.
- Mesh-only isolation is only as strong as its policy and its certificate authority; audit policies as code and test that cross-tenant calls are denied.
- Forgetting egress: isolation is also about where tenant workloads can send data out. Restrict outbound traffic per workload identity, or a compromised tenant worker can exfiltrate through the shared NAT.
- Security-group limits: AWS defaults to 60 inbound rules per security group and 5 security groups per network interface; encoding thousands of tenants into IP-based rules breaks these quickly. Identity-based policy avoids it.
Design a metric schema and label strategy for a multi-tenant observability platform that keeps cross-tenant query cost low while making it structurally impossible for one tenant's query to see another tenant's metrics. Explain how you would partition or shard metrics by tenant, which labels are safe to leave high-cardinality versus which must stay scoped and low-cardinality, and the access controls you would enforce at query time.
Sample Answer
Direct answer
Make the tenant not a label at all but the partition key of the storage: the ingestion gateway stamps each write with the tenant taken from the authenticated credential, and every tenant's series are stored and indexed separately. A query then carries a tenant identity set by the auth layer, and the query engine only opens that tenant's data, so a crafted query cannot reach another tenant even in principle. Within a tenant, labels whose values are bounded (service, route template, status class) are fine, and each tenant gets a series budget; labels with unbounded values (user ID, request ID, full URL) are never labels. Cross-tenant queries exist only for platform operators, through a separate, explicitly enabled path.
Terms used below
- Time series: one metric name plus one exact combination of label values, for example
http_requests_total{service="cart", status="5xx"}. Each combination is a separate series stored and indexed separately. - Label: a key-value dimension on a metric. Cardinality: how many distinct series a metric produces, which is roughly the product of the distinct values of its labels.
- TSDB (time-series database): a store optimised for timestamped numeric samples (Prometheus, Grafana Mimir, Thanos, VictoriaMetrics).
- Exemplar: a sample that carries a trace ID as attached data, not as a label, linking a metric point to a trace (the recorded path of one request as it moves through several services, used to debug where its time went) without creating new series. The trace ID identifies which one of those recordings this metric point corresponds to.
- Shuffle sharding: giving each tenant a small, pseudo-random subset of the nodes, so two tenants rarely share all the same nodes.
- Ingester: the component that receives incoming samples, buffers them in memory, and periodically flushes them to long-term storage as a block.
- Querier: the component that executes a query (in this system, PromQL, Prometheus's query language) by reading the stored blocks and computing the result.
- Block: an immutable chunk of one tenant's time series data covering a fixed time range, the unit this kind of store writes and reads. A chunk is the compressed, on-disk unit of samples for one series inside a block.
Partitioning and sharding by tenant
- Physical separation per tenant. In Grafana Mimir, for example, every write and query carries an
X-Scope-OrgIDheader naming the tenant, and each tenant's data is stored in separate blocks (see "Terms used below"). Mimir does not authenticate that header itself; its docs require an authenticating proxy in front that sets it. So the proxy derives the tenant from the API key or token and overwrites any header the client sent. - Ingestion sharding: series are hashed across ingesters, and with shuffle sharding each tenant uses only a subset (in Mimir, the per-tenant
ingestion_tenant_shard_sizesetting). A tenant that floods writes saturates its own subset, not the cluster. - Query sharding: per-tenant query queues and a cap on queriers (see "Terms used below") per tenant (
max_queriers_per_tenantin Mimir) so one tenant's heavy dashboards cannot occupy every querier. A query frontend sits in front of the queriers: it is the component that holds each tenant's query queue and enforces that per-tenant cap before handing a query to a free querier.
Label strategy
Series count multiplies. For one metric with method (5 values) x status (8) x route (50) x pod (40):
5 x 8 x 50 x 40 = 80,000 series for one tenant.
If the store indexed all 10,000 tenants together with tenant as an ordinary label, the same metric is 80,000 x 10,000 = 800,000,000 series in one index, and every query's index lookup pays for the whole platform. With the tenant as the partition key, each tenant's index holds its own 80,000, and a query only searches that.
| Label type | Examples | Rule |
|---|---|---|
| Tenant identity | tenant | Not a user-controlled label; a storage partition set by the gateway |
| Bounded, tenant-scoped | service, route template (/orders/{id}), status class, region, pod | Allowed; cost falls on the tenant's own budget |
| Unbounded | user_id, request_id, session_id, raw URL, error message text | Forbidden as labels; use exemplars, logs or traces |
| Platform metrics about tenants | gateway_requests_total{tenant=...} in the provider's own monitoring | Here tenant IS a label, so keep every other label on that metric low-cardinality |
The last row is the subtle one. In the provider's own metrics, tenant really is a high-cardinality label (10,000 values). That is safe only if its companions stay small: tenant x status (8) is 80,000 series, but adding route (50) makes it 10,000 x 50 x 8 = 4,000,000. For per-tenant, per-route detail, use top-N (record only the busiest tenants per route) or logs.
Enforce budgets per tenant: a cap on active series per tenant (Mimir: max_global_series_per_user) and on labels per series. Over the cap, new series are rejected for that tenant only, and the tenant gets a clear error and a "top cardinality labels" report.
Access controls at query time
- Authenticate, then set tenant. The auth proxy maps credential to tenant and sets the tenant header; client-supplied tenant headers are discarded.
- Engine-level scoping. The query engine opens only the named tenant's blocks. This is stronger than the common alternative on a shared Prometheus: a proxy sitting in front of one shared store that rewrites every incoming query to add a
tenant="x"filter, and every incoming write to add atenant="x"label (label injection is that rewriting: the proxy, not the client, inserts the tenant filter or label). With injection, a parser bug or a missed code path returns other tenants' data; with partitioning, their data is never read because the engine never opens their blocks at all. - Per-tenant query limits: maximum series fetched and bytes fetched per query (Mimir:
max_fetched_series_per_query,max_fetched_chunk_bytes_per_query, which bounds how many chunk bytes, the compressed on-disk sample data described above, one query may read), query timeouts, and fair queueing. These keep cross-tenant query cost low: an expensive query hurts its own tenant's queue. - Cross-tenant queries for operators only. Mimir supports tenant federation (querying several tenants' data in one request) only when it is switched on (
-tenant-federation.enabled=true, with tenants separated by|in the header). Expose that only to an internal operator identity, never to tenant credentials. - Tests: on every release, run queries with tenant A's credentials using a selector such as
{__name__=~".+"}(a PromQL pattern that matches every metric name, i.e. "return all of this tenant's series") and assert zero series from tenant B: any hit would mean tenant A's credentials could read tenant B's data.
flowchart LR
AG["Tenant agent<br/>(the tenant's own metrics<br/>shipper, e.g. Prometheus<br/>remote-write)"] -->|API key| AP[Auth proxy<br/>sets tenant]
AP --> ING[Ingesters<br/>shuffle-sharded]
ING --> ST[(Blocks stored<br/>per tenant)]
Q[Tenant dashboard] -->|token| AP2[Auth proxy<br/>sets tenant]
AP2 --> QF[Query frontend<br/>per-tenant queue + limits]
QF --> ST
Trade-offs and pitfalls
- Per-tenant partitioning costs a little overhead per tenant (separate blocks, separate indexes). For thousands of tiny tenants that is acceptable; for millions, group tiny tenants into shared partitions with enforced label injection and heavier testing.
- Pitfall: using the raw URL as
route./orders/81723produces a new series per order; always use the route template. - Pitfall: trusting the client's tenant header because the storage layer "is multi-tenant". Multi-tenant storage without an authenticating front door is a shared store with a guessable key.
A security review finds that a support engineer investigating one tenant's ticket could, in principle, find another tenant's data sitting in shared application logs, backups, or a third-party monitoring pipeline. Outline the security controls you would put in place across logging, backups, and telemetry to close this off, and how you would verify none of it leaks through a vendor or pipeline you don't fully control.
Sample Answer
Direct answer
The fix is to treat logs, backups and telemetry as data stores in their own right, with the same tenant boundary as the primary database. Concretely: stop sensitive values entering them (allowlisted structured logging), tag every record with the tenant it belongs to so access can be scoped per tenant, give support engineers time-boxed, ticket-scoped access to one tenant at a time, encrypt backups per tenant and restore them only through an audited break-glass path, and scrub telemetry before it leaves your network. Then verify it continuously with canary data (unique marker strings seeded into a test tenant) that you search for in every downstream system, including vendors you do not control.
Why this leak exists at all
In most SaaS products the primary database is protected by tenant-scoped queries or row-level security (RLS: a database feature that filters rows by a policy such as tenant_id = current tenant). The side channels are not. A stack trace logs the SQL statement with a customer's email in it; a debug line dumps a whole request body; a nightly backup contains every tenant in one file; an APM agent (application performance monitoring, for example a hosted tracing product) captures HTTP payloads. A support engineer with read access to the log index investigating tenant A's ticket then sees tenant B's data in the same search results. Nobody broke a rule; the rules simply never covered these stores.
Controls, layer by layer
1. Logging: keep the data out, then scope what remains
| Control | What it does | Why it matters |
|---|---|---|
| Allowlisted structured logging | Logs are JSON with a fixed set of permitted fields (timestamp, level, tenant_id, request_id, route, status, error code). Unknown fields are dropped, not masked | A denylist ("mask fields called ssn") fails the first time someone logs a field called social. An allowlist fails safe |
| Redaction as a second net | Pattern scrubbing (emails, card numbers, tokens) on free-text fields such as error messages | Catches values that sneak in through exception messages |
Mandatory tenant_id on every record | Injected by the logging library from the request context, never by the caller | Without it you cannot scope access or delete a tenant's logs on offboarding |
| Per-tenant access scoping | Either one index per tenant (or per tenant tier), or a shared index where the log platform enforces a document-level filter (it checks the tenant_id on every individual record before returning it, not just at the index level) on tenant_id | The support engineer's query is physically limited to the tenant on the ticket |
| Just-in-time (JIT) support access | Access is granted for one tenant, tied to a ticket ID, expires after a few hours, and every query is audit-logged | Removes standing access; an auditor can match every search to a ticket |
| Short retention for verbose logs | Debug and request-level logs kept days, not years | Less data exposed, and less to erase later |
A minimal allowlisting formatter, run as shown:
import json, re
# Fields a log line may carry. Anything else is dropped, not masked.
ALLOWED = {"ts", "level", "tenant_id", "request_id", "route", "status", "latency_ms", "error_code"}
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
def scrub(event: dict) -> dict:
out = {k: v for k, v in event.items() if k in ALLOWED}
dropped = sorted(set(event) - ALLOWED)
if dropped:
out["dropped_fields"] = dropped # names only, never values
for k, v in out.items():
if isinstance(v, str):
out[k] = EMAIL.sub("[email]", v) # second net for free text
return out
raw = [
{"ts": "2026-09-01T10:00:00Z", "level": "error", "tenant_id": "t_acme",
"request_id": "r1", "route": "/invoices/42", "status": 500,
"error_code": "DB_TIMEOUT", "sql": "SELECT * FROM invoices WHERE customer='bob@acme.io'"},
{"ts": "2026-09-01T10:00:01Z", "level": "info", "tenant_id": "t_globex",
"request_id": "r2", "route": "/export", "status": 200, "latency_ms": 812,
"body": {"ssn": "123-45-6789", "note": "CANARY-GLOBEX-7F3A"}},
]
shipped = [json.dumps(scrub(e)) for e in raw]
for line in shipped:
print(line)
# Verification: seeded canary strings must never appear in anything shipped.
canaries = ["CANARY-GLOBEX-7F3A", "bob@acme.io", "123-45-6789"]
leaks = [c for c in canaries if any(c in line for line in shipped)]
print("leaked canaries:", leaks)
Output:
{"ts": "2026-09-01T10:00:00Z", "level": "error", "tenant_id": "t_acme", "request_id": "r1", "route": "/invoices/42", "status": 500, "error_code": "DB_TIMEOUT", "dropped_fields": ["sql"]}
{"ts": "2026-09-01T10:00:01Z", "level": "info", "tenant_id": "t_globex", "request_id": "r2", "route": "/export", "status": 200, "latency_ms": 812, "dropped_fields": ["body"]}
leaked canaries: []
Note what the engineer still gets: the tenant, the route, the error code and the request ID to correlate with. That is enough to debug most tickets; the rare case needing payload data goes through the JIT path against the tenant's own data store.
2. Backups: one tenant's restore must not expose the others
- Encrypt with per-tenant keys where the data is separable (silo databases, per-tenant object prefixes, per-tenant logical exports). With envelope encryption (each backup encrypted by a data key, which is itself encrypted by the tenant's master key in a key management service), access to the backup file alone reveals nothing.
- Pooled database backups cannot be split by key, so they are treated as the most sensitive artifact: stored in a separate backup account, readable only by an automated restore role, never by humans directly.
- Restores go to an isolated environment through a break-glass workflow (a pre-approved emergency path that requires a second approver and is fully logged). The restore job extracts only the target tenant's rows; the full restored copy is destroyed afterwards.
- Backup ACLs (access control lists) deny
readto the support role entirely. Support never touches a backup.
3. Telemetry and third-party pipelines: scrub before egress
- Run all traces, metrics and error reports through a collector you operate (for example an OpenTelemetry Collector, the open-source agent that receives, processes and exports telemetry) and apply attribute allowlists there. Vendors only ever receive the scrubbed stream.
- Turn off payload capture in APM and error-tracking agents (request bodies, SQL parameter values, local variables in stack frames); these defaults are the usual leak.
- Hash or pseudonymize tenant identifiers sent to vendors if the vendor has no need to know the customer's name.
- Metric labels carry tenant tier or a tenant ID, never user-level identifiers (each distinct label value creates its own stored time series, so a label that can take millions of values, like a user ID, multiplies storage and query cost by millions: a high-cardinality cost blow-up).
- Contractually: a data processing agreement (a contract clause binding the vendor to your privacy and security requirements for any data you send them), the vendor on your sub-processor list (the vendor's published list of who else touches your data on their behalf, which your own contracts require you to track), a region pin, a retention setting you have verified in their console, and their independent audit report (for example SOC 2 Type II, a report confirming an auditor actually tested the vendor's security controls over several months, not just reviewed a design on paper) reviewed annually.
Verifying what you do not control
You cannot inspect a vendor's storage, so you test the outputs and the inputs:
- Canary tenant. A synthetic tenant whose records contain unique strings (
CANARY-GLOBEX-7F3A, a fake but valid-format email). A scheduled job exercises it, including error paths that historically log payloads. - Search every sink for canaries daily through each system's API: your log platform, the APM vendor, the error tracker, the data warehouse, the support tool. Any hit is a sev-2 incident (the second-highest urgency tier: high priority, but not an all-hands page) with a known origin because each canary is unique per source path.
- Egress inspection. (Egress is data leaving your network for an outside destination, here a vendor.) Sample the collector's outbound stream and run a DLP (data loss prevention) scanner over it for card numbers, emails and the canaries. This checks the scrubbing before the vendor ever sees data.
- Support-access audit. Weekly reconciliation: every log query by a support engineer must map to a ticket whose tenant matches the query's tenant filter. A mismatch is investigated.
- Contract and configuration drift checks. Vendor retention, region and payload-capture settings read back through their API on a schedule and diffed against the expected values.
Trade-offs and pitfalls
- Per-tenant log indexes vs a shared index with filters. Separate indexes make access control and deletion trivial but cost more (index overhead per tenant) and break cross-tenant operational queries. Recommendation: shared index with enforced document-level filtering for the long tail, dedicated indexes for tenants whose contracts demand it.
- Dropping fields slows debugging. The honest answer is that it does, occasionally. The JIT path to the tenant's own store is the pressure valve; do not reopen the log floodgates.
- Pitfall: redacting only at the log platform. By then the data has already crossed the network and possibly been buffered by an agent on disk. Scrub at the source and at the collector.
- Pitfall: forgetting derived stores. Search indexes, analytics exports and support-tool attachments hold copies too. Canaries find these; architecture diagrams usually do not.
- Pitfall: canaries only in the happy path. Leaks come from error handlers and retries. Exercise failures deliberately.
Unlock Full Question Bank
Get access to all 45 Multi-Tenancy and Isolation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.