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.
As a Solutions Architect, outline a test plan to verify tenant isolation before a production release, for a platform that has never had this kind of testing before. What levels of testing would you build, how would you actively try to break the isolation boundary rather than just confirm it, and how would you keep test data from contaminating other tenants?
Sample Answer
Direct answer
I would build tenant-isolation testing in four layers (static checks on code, unit and property-based tests, integration tests that attack a running system with two real tenants, and a periodic penetration test), and I would make every test adversarial: authenticate as tenant B and try, through every door, to read or change tenant A's data. All of it runs in CI (continuous integration, the pipeline that runs on every change) against dedicated, clearly marked test tenants, so a regression blocks the release instead of reaching a customer.
Why "confirm" tests are not enough
Most suites already test that tenant A can read tenant A's invoice. That test passes whether or not isolation works. Isolation is a negative property ("B can never see A's data"), so the tests must try to make it fail. A useful mental model: every place data is stored or served (database, cache, search index, file storage, logs, exports, background jobs, event streams) is a door, and every door gets a test that tries to walk through it as the wrong tenant.
The layers
1. Static checks (cheapest, run on every commit)
- A lint rule or query-builder wrapper (a shared helper every query must be built through, so a missing tenant filter is caught in one place instead of at every call site) that fails the build when a query touches a tenant-scoped table without a tenant filter, for example failing with something like
invoices.py:42: query on tenant-scoped table 'invoices' has no tenant filter, use invoice_repo.for_tenant(...). - A check that every cache key, object-storage path and search index name is built through one helper that includes the tenant id.
- Database: confirm row-level security (RLS, where the database itself adds the tenant filter to every query) is enabled on every tenant table, by querying the catalog (the database's internal metadata tables, which record each table's settings, including whether RLS is on; in Postgres for example,
SELECT relrowsecurity FROM pg_class WHERE relname = 'invoices';should return true) in a test.
2. Unit and property-based tests
A property-based test generates many random inputs and checks that a rule (a "property") always holds, instead of checking one hand-picked example. For isolation the property is: across any random interleaving of operations by two tenants, no response ever contains the other tenant's data. It finds bugs that depend on ordering and ID collisions that no one would think to write by hand.
A small runnable illustration. The service has a realistic bug: its read cache is keyed by invoice number only.
import random
class InvoiceService:
"""Toy service with a realistic bug: the read cache is keyed by invoice number only."""
def __init__(self):
self.db = {} # (tenant, invoice_no) -> amount (DB layer is tenant-scoped)
self.cache = {} # invoice_no -> (tenant, amount) BUG: tenant missing from key
def create(self, tenant, invoice_no, amount):
self.db[(tenant, invoice_no)] = amount
def get(self, tenant, invoice_no):
if invoice_no in self.cache:
return self.cache[invoice_no] # returns whoever cached it first
if (tenant, invoice_no) not in self.db:
return None # 404 for other tenants' invoices
row = (tenant, self.db[(tenant, invoice_no)])
self.cache[invoice_no] = row
return row
class FixedInvoiceService(InvoiceService):
def get(self, tenant, invoice_no):
key = (tenant, invoice_no) # tenant is part of every cache key
if key in self.cache:
return self.cache[key]
if key not in self.db:
return None
self.cache[key] = (tenant, self.db[key])
return self.cache[key]
def happy_path_test(svc_class):
svc = svc_class()
svc.create("acme", 1, 500)
return svc.get("acme", 1) == ("acme", 500) # the test most teams already have
def check_isolation(svc_class, seed, steps=200):
"""Random interleaving of two tenants; invariant: a response never carries another tenant's data."""
rng = random.Random(seed)
svc = svc_class()
for step in range(steps):
tenant = rng.choice(["acme", "globex"])
invoice_no = rng.randint(1, 20) # small ID space, so tenants collide on numbers
if rng.random() < 0.5:
svc.create(tenant, invoice_no, rng.randint(1, 10_000))
else:
got = svc.get(tenant, invoice_no)
if got is not None and got[0] != tenant:
return f"seed={seed} step={step}: {tenant} read invoice {invoice_no} owned by {got[0]}"
return None
for cls in (InvoiceService, FixedInvoiceService):
failures = [r for r in (check_isolation(cls, s) for s in range(50)) if r]
print(f"{cls.__name__}: happy-path test passes={happy_path_test(cls)}, "
f"{len(failures)} of 50 random runs broke isolation")
if failures:
print(" first failure:", failures[0])
Output from running it:
InvoiceService: happy-path test passes=True, 50 of 50 random runs broke isolation
first failure: seed=0 step=98: acme read invoice 7 owned by globex
FixedInvoiceService: happy-path test passes=True, 0 of 50 random runs broke isolation
The happy-path test passes for both versions; only the randomized two-tenant test separates them. In a real codebase I would use a library such as Hypothesis (Python) or fast-check (JavaScript), which also shrink a failure down to the shortest sequence that reproduces it.
3. Integration and API-level attack tests
Against a deployed test environment with at least two tenants holding overlapping IDs and similar data:
| Attack | How the test does it |
|---|---|
| Swap object IDs (IDOR: insecure direct object reference, reaching an object by guessing its ID) | As tenant B, call every endpoint with tenant A's IDs; expect 404, not 403 (403 confirms existence) |
| Tamper with the tenant claim | Modify the tenant id in a token, header or subdomain; expect rejection because the server derives tenant from the verified token |
| List and search endpoints | Search for a unique marker string planted in A's data while authenticated as B |
| Async paths | Trigger exports, emails, webhooks and reports as B; inspect outputs for A's markers |
| Shared infrastructure | Cache, search index, file storage presigned URLs (a temporary, pre-authorized link that grants access to one specific file without a separate login, commonly used for direct upload or download), message queues |
| Admin and support tools | Support staff impersonation must be scoped and logged |
The planted marker strings (for example ISOLATION-CANARY-7f3a in tenant A's records) make detection mechanical: any response, file or log visible to B containing A's marker is a failure.
4. Penetration test before the first release
An external or internal red team (a group whose job is to attack the system the way a real adversary would, to find gaps before one does) gets two tenant accounts and one goal: reach the other tenant. Findings become new automated tests in layer 3 so they cannot regress.
Keeping test data from contaminating other tenants
- Dedicated test tenants with reserved ids (a prefix or a flag column), never real customer accounts.
- Separate environment first. Layers 1 to 3 run in CI and staging. Only a small read-only subset (planted marker checks through the public API) runs in production, and only against the test tenants.
- Synthetic data only, generated, never copied from production.
- Exclude test tenants from billing, analytics and aggregate reports, so their data does not skew real tenants' benchmarks.
- Teardown with verification: delete test tenants' data after runs and assert zero rows remain under their ids, so leftovers cannot pollute later runs.
- Mark every artifact: test tenants' files, emails and webhooks go to sinks you own, never real addresses.
Worked example: rolling this out on a platform with no tests
Week 1: add the RLS catalog check and the query-lint rule; both run on every commit. Week 2: write the randomized two-tenant test for the three highest-risk services (billing, documents, search). Week 3: build the integration suite with two seeded tenants and markers covering the 40 highest-traffic endpoints, then extend. Before release: external penetration test. From then on, every new endpoint must ship with a "tenant B tries A's ID" test, enforced in code review.
Trade-offs and pitfalls
- Full coverage of every endpoint is expensive; prioritize by data sensitivity and by how new the code is. Generate the "wrong tenant" test from the route list so new endpoints are covered by default.
- Pitfall: testing only the database. Most real leaks in pooled systems (multi-tenant systems sharing one schema or database, as opposed to a separate database per tenant) come from caches, search, exports and background jobs, where the tenant filter is easiest to forget.
- Pitfall: test tenants with non-overlapping IDs. If A's invoices are 1 to 100 and B's are 101 to 200, a cache keyed only by ID never collides and the bug in the example above stays hidden.
- Pitfall: 403 versus 404. Returning "forbidden" for another tenant's object tells an attacker it exists. Test for "not found".
Design a production test harness that continuously verifies tenant isolation and data consistency using live telemetry and sampled data, without adding meaningful load or risk to the production system it's watching. What would you actually probe, how would you tell a real isolation failure from noise, and how would you tune it so on-call doesn't start ignoring it?
Sample Answer
Direct answer
I would build the harness from three kinds of probe that cost almost nothing to run: synthetic canary tenants that continuously try to cross the isolation boundary through the public API, in-path assertions that check every response's tenant against the caller's tenant and emit a counter, and sampled consistency checks that compare a small random sample of rows between primary and replicas at the same replication position (a marker, such as a log sequence number, saying how far a replica has caught up; comparing at the same position means comparing what the replica knew at a moment it had actually reached, not one it has not replicated yet). I separate real failures from noise by the kind of signal: a confirmed cross-tenant read has zero tolerance and pages immediately (automatically alerts the on-call engineer's phone right away, rather than just opening a ticket), while consistency mismatches must survive a recheck after lag has drained before they alert anyone. Fault injection (partitions, replica lag, misconfigured ACLs) runs on a schedule, only against canary tenants in a dedicated cell (an independent slice of the platform with its own app servers and databases), so the harness proves it can detect what it claims to detect.
1. What to probe
Canary tenants (active, outside-in)
Two or more synthetic tenants per cell, living alongside the real tenants that cell serves. Tenant A plants records containing unique marker strings. Every few minutes, a prober authenticated as tenant B:
- requests A's object IDs on each tenant-scoped endpoint (expect "not found"),
- searches for A's markers (expect zero hits),
- triggers an export and scans the file for A's markers,
- writes a record and reads it back through a replica (read-your-writes).
These probe the whole stack, including caches and search, which is where pooled systems (services where many tenants' data sits together in the same tables or indexes, relying on filtering rather than physical separation to keep tenants apart) most often leak.
In-path assertions (passive, inside-out)
A middleware (a shared layer of code every service routes its requests through, here doing one extra check before returning data) compares the tenant id on each row or document being returned with the tenant id from the caller's verified token. On mismatch it blocks the response and increments cross_tenant_block_total{service, endpoint}. This watches 100% of real traffic at the cost of one comparison per row, and it turns a leak into a blocked request plus an alert rather than an exposure.
Sampled consistency checks
Pick random rows (by random primary key within random tenants), read them from the primary and from each replica at the same replication position, and compare hashes. Also check that the replica's copy still carries the same tenant_id.
Configuration drift
Periodically read access control lists (ACLs, the rules saying which identity may access which resource), bucket policies and database RLS (row-level security) policy definitions, and diff them against the declared configuration in source control.
2. How much to sample, and the load it costs
If a fraction f of rows has diverged, the chance that n independent random samples find at least one is:
P(detect)=1−(1−f)nWith f = 0.001 (one row in a thousand) and n = 3,000 samples per hour:
1−0.9993000≈0.950So 3,000 samples an hour catch that level of divergence within an hour 95% of the time. That is 3,000 / 3,600, under one read per second per replica: negligible next to production traffic. The canary probes add, for example, 50 endpoint checks for 2 tenants every 5 minutes, 100 / 300 s, about 0.33 requests per second. Sampling will not find a single corrupted row among billions; that is the job of full nightly checksums on a replica or a backup, not of the live harness.
3. Real failure versus noise
| Signal | Likely noise | Rule |
|---|---|---|
| Canary B sees A's marker | None plausible | Page immediately; confirm once, then treat as an incident |
cross_tenant_block_total increments | Rarely: a test tenant, a support tool with legitimate cross-tenant scope | Page; allowlist (add to an explicit approved list) legitimate callers explicitly, never by suppressing the metric |
| Replica row differs from primary | Replication lag | Recheck after twice the current lag; if it still differs, open a ticket, not a page, unless the same row fails a third consecutive recheck |
| Canary read-your-writes fails | Brief lag, a failover in progress | Alert if it fails in 3 consecutive rounds or in multiple cells |
| ACL drift | Planned change not yet committed to source control | Ticket, page only if the drift grants cross-tenant access |
The recheck arithmetic. The sampler above runs 3,000 samples an hour, 72,000 a day. If 0.5% of samples hit transient lag: 72,000 x 0.005 = 360 false alerts a day before any recheck, enough to train on-call to ignore the harness within a week. Requiring the mismatch to persist on a recheck of that same row after lag has drained, and assuming the two checks fail independently, gives 72,000 x 0.005 x 0.005 = 1.8 false alerts a day, about one every 13 hours: a roughly 200x reduction, but still too many to page on directly. That is why the rule above routes a single persisting mismatch to a ticket, and reserves a page for a row that fails three consecutive rechecks or for many rows failing at once, either of which is far rarer than 1.8 a day. The independence assumption breaks when lag is chronic, which is why the recheck waits for twice the measured lag rather than a fixed delay.
4. Fault injection that proves the harness works
A detector that never fires might mean the system is healthy or that the detector is broken. So on a schedule, in a dedicated canary cell that serves only synthetic tenants:
- Network partitions between the cell's primary and replica: the harness should report read-your-writes failures and then recovery.
- Replica lag injected at the replication link: the sampler should show mismatches that clear on recheck (proving the noise filter works) and nothing that escalates.
- Misconfigured ACLs: deploy a deliberately wrong rule that lets tenant B's role read tenant A's storage prefix. The canary probe must catch it within one probe interval, and the drift check must flag it.
Each run has an automatic stop (end injection if any real tenant's error rate moves) and a time limit. If the harness fails to flag an injected fault, that is itself a page-worthy defect in the harness.
5. Keeping on-call trust
- Every alert has an owner, a runbook (a written, step-by-step procedure for responding to this specific alert), and a link to the evidence (the leaked marker, the differing row pair).
- Route by severity: isolation breaches page, consistency drift opens tickets unless it persists or grows.
- Review alert precision monthly: of alerts fired, how many were real? Tune thresholds for noisy signals only; never tune the zero-tolerance ones.
- Report "harness health" (probes run, faults detected in scheduled injections) so people can see it is working when it is quiet.
Worked example
A deploy changes the search service's index naming so two tenants in the same cell share an index. Within 5 minutes, canary tenant B's search for ISOLATION-CANARY-7f3a returns a hit. At the same time the in-path assertion on the search endpoint increments cross_tenant_block_total for real traffic, and those results are blocked. Two independent signals agree, the page fires with the matching document ids, and the deploy is rolled back. No customer saw another tenant's data because the assertion blocked it; without it, the canary alone would have limited exposure to one probe interval.
Trade-offs and pitfalls
- In-path assertions need a tenant id on every returned object. Retrofitting that is work, but it is the strongest signal you can have.
- Canaries only test the paths they exercise. Generate probe lists from the route table so new endpoints are covered automatically.
- Pitfall: synthetic tenants that are too small or too quiet never trigger size- or concurrency-dependent bugs. Give them realistic data volume.
- Pitfall: reading from the primary to check it, adding load exactly where it is scarcest. Read from replicas and from change streams (a live feed of row-level changes a database can emit, so you can check consistency without querying the primary directly) where possible.
Explain a safe tenant onboarding and offboarding process for a SaaS product: steps required to provision isolation resources (databases, IAM), apply tenant-specific encryption keys, seed or migrate data, validate access controls, and securely erase and validate data deletion on offboarding to satisfy audits and compliance.
Sample Answer
Direct answer
Tenant onboarding and offboarding should be a single automated, idempotent workflow (safe to re-run after a failure without creating duplicates), not a runbook of manual steps. Onboarding provisions isolation resources from code, creates the tenant's encryption key, loads data with verified counts, and refuses to activate the tenant until automated cross-tenant access tests pass. Offboarding is the mirror image: export, hold for the contractual grace period, delete live data, destroy the tenant's key so any remaining copies (including backups) become unreadable, and produce a signed deletion record an auditor can check.
The lifecycle as a state machine
Model the tenant as a record with an explicit state, advanced by a workflow engine (for example AWS Step Functions, a managed service that runs multi-step workflows with retries, or Temporal, an open-source workflow engine with the same job):
REQUESTED → PROVISIONING → SEEDING → VALIDATING → ACTIVE → OFFBOARD_REQUESTED → EXPORTED → GRACE → DELETING → KEY_DESTROYED → CLOSED
Every step writes its result back to the tenant record, so a failure halfway leaves a known state that the workflow resumes from, and an auditor can read the history.
Onboarding
1. Provision isolation resources
The resources depend on the tenancy model (silo: dedicated resources per tenant; pool: shared resources with a tenant_id on every row; bridge: a mix, such as shared compute with a dedicated database):
| Resource | Pool tier | Silo tier |
|---|---|---|
| Database | Tenant row in the tenant registry; RLS (row-level security) policies already cover it | Dedicated database or cluster created from an infrastructure-as-code (IaC) template |
| Storage | Tenant prefix s3://data/tenants/{tenant_id}/ | Dedicated bucket |
| Identity (IAM, AWS Identity and Access Management) | Shared service roles; access restricted by a session tag (a label attached to a temporary credential when it is issued, here tenant_id) checked in policy conditions (ABAC, attribute-based access control: the IAM rule only allows an action when the tag matches the resource being accessed) | Dedicated role per tenant scoped to its own resources |
| Network | Shared | Optional dedicated VPC (Virtual Private Cloud) or private endpoint |
Everything is created from versioned templates, never by hand, so tenant 4,000 is configured identically to tenant 4.
2. Tenant-specific encryption keys
Create a per-tenant key (or, for the long tail, a per-tenant data key wrapped by a shared master key, encrypted under it, the standard "envelope encryption" pattern explained next) in a key management service such as AWS KMS (Key Management Service). Use envelope encryption: data is encrypted with a data key, and the data key is stored encrypted under the tenant's master key. Tag the key with the tenant ID, restrict its key policy so only that tenant's roles can use it, and record the key identifier in the tenant registry. This one decision is what makes offboarding provable later.
3. Seed or migrate data
- Seed default configuration, roles and an admin user from templates.
- Migrate customer data (from a previous system or a trial environment) through a staged pipeline: land in a quarantine area encrypted with the tenant's key, transform, load, then reconcile: row counts and checksums per table between source and target must match before the step succeeds.
- Every row written carries the tenant ID; the loader refuses a row whose tenant ID does not match the job's tenant.
4. Validate access controls (the activation gate)
The tenant is not ACTIVE until an automated suite passes:
- A token for the new tenant can read its own seeded objects.
- The same token cannot read a fixed canary tenant's (a permanent test tenant seeded with known data, used only to verify that isolation checks catch a leak) objects by ID, search, or export (expect 404, not 403, so existence is not revealed).
- A canary tenant's token cannot read the new tenant's objects.
- The IAM role for the tenant is denied access to another tenant's storage prefix and key (checked with a policy simulator, a tool that evaluates what an IAM policy would allow without actually performing the action, or a live attempt).
Offboarding
1. Export and grace period
Deliver a complete export in a documented format, encrypted, with a checksum manifest. Hold the data for the contractual grace period (commonly 30 days) in a suspended state: no logins, no processing, but restorable if the customer changes their mind.
2. Delete live data
- Silo: destroy the database, bucket and roles via IaC.
- Pool: delete by tenant ID in batches (to avoid long locks), across every store: primary database, search indexes, caches, queues, analytics copies, file storage. Driving this from a data inventory (a registry of every store that holds tenant data) is what prevents a forgotten store.
3. Destroy the key (crypto-shredding)
Backups and replicas are the hard part: you usually cannot surgically delete rows from a snapshot. If the tenant's data in those copies was encrypted with the tenant's key, scheduling the key for deletion renders them unreadable. AWS KMS enforces a waiting period of 7 to 30 days before a scheduled key is actually deleted, which doubles as a safety window. For pooled tenants, only what was actually encrypted with their data key becomes unreadable this way, typically file attachments and exports written through the application under the tenant's own storage prefix. Pooled database snapshots hold the bulk relational rows, which are not encrypted per tenant (they rely on RLS while live, not a per-tenant key) and simply age out under the backup retention policy; the deletion record states that date separately.
4. Validate deletion and produce evidence
- Query every store in the data inventory for the tenant ID and record a count of zero for each.
- Record the key deletion event from the provider's audit log (for AWS, CloudTrail, its API audit log).
- Generate a deletion certificate: tenant ID, stores checked with counts, key ID and deletion date, backup expiry date, workflow run ID, signed off by the system and a named owner.
Worked example
A pooled-tier customer with 2.1 million rows across 14 tables offboards on 1 March with a 30-day grace period:
- 1 March: export delivered, tenant suspended.
- 31 March: live deletion runs in 5,000-row batches, so 2,100,000/5,000=420 batches; the inventory check shows 0 rows in all 14 tables, 0 documents in search, 0 objects under the storage prefix.
- 31 March: tenant data key scheduled for deletion with the maximum 30-day window; deleted 30 April.
- Backups: daily snapshots with 35-day retention, so the last snapshot containing live data (taken 30 March) expires 4 May. This tenant's file attachments were encrypted with its data key; its relational rows in the shared pooled database were not, so the certificate's two dates track two different mechanisms. The certificate lists 4 May as the date after which no copy exists in any form (the last unencrypted database snapshot containing this tenant's rows has aged out of the 35-day retention window), and 30 April as the date after which no encrypted copy can be read (the data key is gone, so any surviving copy of an attachment becomes unreadable).
Trade-offs and pitfalls
- A dedicated master key per tenant vs per-tenant data keys under a shared master key. Dedicated keys give the cleanest audit story and per-tenant revocation but add key cost and API quota pressure at tens of thousands of tenants. Recommendation: dedicated keys for silo and regulated tenants; per-tenant data keys (stored in the tenant registry) for the pool.
- Pitfall: crypto-shredding a key that encrypted more than one tenant. Verify the key-to-tenant mapping is one-to-one before scheduling deletion.
- Pitfall: forgetting derived data. Analytics warehouses, ML (machine learning) feature stores and support tickets are where offboarded tenants live on. The data inventory must include them.
- Pitfall: activating before validating. Provisioning that "succeeded" with a misconfigured policy is how a new tenant starts life able to see an old one.
Describe how to build tenant-aware query routing in a distributed SQL engine so queries are served by the correct primary or region-replica. Include routing metadata, cache/coordinator design, routing under failover, and how to maintain per-tenant residency and read-your-writes guarantees.
Sample Answer
Direct answer
I would put a small, versioned tenant placement map (tenant to home region, primary, and the replicas it is allowed to use) at the center, cache it in every query coordinator, and make every routing decision a pure function of three inputs: the tenant's placement entry, the statement type (read or write), and the client's session consistency token. Writes always go to the tenant's current primary. Reads go to an in-region replica only if that replica has caught up to the session token, otherwise to the primary. Residency is enforced by construction, because the map never lists a replica outside the tenant's permitted regions, and failover can only promote a replica from that same list.
Terms used below
- Coordinator (or gateway): the node that receives a SQL statement, decides where it runs, and returns the result. In a distributed SQL engine every node can usually act as one.
- Primary / leaseholder: the one replica allowed to accept writes for a piece of data. A lease is a time-limited right to act as primary; when it expires, another replica may take over.
- Epoch (or generation number): a counter bumped every time the primary for a tenant changes. Anything stamped with an older epoch is known to be stale.
- Read-your-writes (RYW): after you commit a write, your own later reads must see it, even if they land on a different node.
- Data residency: a contractual or legal rule that a tenant's data (including copies) stays in named jurisdictions, for example "EU only".
1. Routing metadata
One row per tenant, stored in a strongly consistent system table (replicated with a consensus protocol such as Raft, where a majority must agree before a change is visible):
| Field | Example | Why it exists |
|---|---|---|
tenant_id | t-4812 | Lookup key |
allowed_regions | [eu-west, eu-central] | Residency boundary; nothing outside this set may hold data |
primary | eu-west/node-7 | Where writes go |
replicas | [eu-west/node-3, eu-central/node-2] | Candidate read targets, all inside allowed_regions |
epoch | 41 | Detects stale cache entries after failover |
migration_state | none or moving(to=...) | Lets the router handle a tenant mid-rebalance |
For very large tenants that are sharded internally, the entry points to a list of key ranges, each with its own primary and epoch. The shape is the same, one level down. If you run CockroachDB, the closest built-in is a REGIONAL BY ROW table, where each row carries a region column and the engine homes the row there; the tenant map above is what you build when you want that decision per tenant rather than per row.
2. Coordinator cache design
- Full replica of the map in memory on every coordinator. 50,000 tenants at about 200 bytes per entry is 50,000 x 200 = 10,000,000 bytes, about 10 MB. That fits comfortably, so there is no reason for a remote lookup on the hot path.
- Kept fresh by a change feed (a stream the metadata store pushes to subscribers whenever a row changes, instead of subscribers polling it), not a TTL (time-to-live). The metadata store (the strongly consistent system table from section 1, holding the placement map) pushes every change with its epoch; coordinators apply it. A TTL alone either serves stale routes for the whole TTL or hammers the store.
- Self-correcting on staleness. Every request carries the epoch the coordinator used. The receiving node compares it to its own view. If the node is no longer primary for that tenant it rejects with "not primary, current epoch is 42, primary is X". The coordinator updates its cache from that hint and retries once. A stale cache therefore costs one extra round trip, never a wrong write.
- Fail closed on a cache miss for an unknown tenant: fetch from the metadata store, and if that is unreachable, return an error. Never guess a default region, because a guessed default is exactly how EU data ends up in a US replica.
sequenceDiagram
participant C as Client
participant G as Coordinator
participant R as EU replica
participant P as EU primary
C->>G: SELECT ... (tenant t-4812, token ts=1005)
G->>G: map lookup: epoch 41, allowed EU only
G->>R: read if applied_ts >= 1005
R-->>G: applied_ts=990, too old
G->>P: read at primary (epoch 41)
P-->>G: rows, commit_ts=1005
G-->>C: rows + token ts=1005
3. Read-your-writes
Every commit returns a session token: the commit timestamp (or log position) of that write. The client driver or the application's session layer sends the highest token it holds with every later statement.
A replica may serve the read only if it has applied the log (replayed the primary's stream of committed changes, the same replication log every replica reads from) up to that token. If it has not, the coordinator can wait briefly for it to catch up (I would cap the wait at about 20 ms) and otherwise send the read to the primary. Statements with no token (a brand-new session, a batch job) can read any in-region replica with bounded staleness (a known limit on how far behind the data might be, rather than unlimited staleness).
The subtle case is the token surviving a failover. Tokens must be timestamps on a clock that keeps increasing across primary changes (hybrid logical clocks, which combine wall-clock time with a counter, do this), or log positions (an offset into that replication log: essentially "how many changes has this replica applied so far") that include the epoch. Otherwise a new primary could hand out a position that compares as "older" than a write the client already saw.
4. Routing under failover
- The old primary's lease expires (say 9 s lease). Replicas in
allowed_regionselect a new primary. Only replicas listed for the tenant are eligible, so residency cannot be broken by failover. - The new primary bumps the epoch to 42 and writes the new map entry to the metadata store. The change feed delivers it to coordinators.
- A coordinator that has not yet seen epoch 42 sends a write to the old primary. The old primary (if alive) sees its lease is gone and rejects it with the hint. If the old primary is partitioned away instead (cut off from the rest of the cluster by a network failure, though still running), the lease rule protects you: the new lease cannot be granted until the old one has expired, and the old primary stops accepting writes when its own lease runs out. This relies on clock drift between nodes being bounded: each node judges its own lease expiry against its own clock, and if the old primary's clock could run arbitrarily slower than the rest of the cluster's, it could still believe its lease was valid long after everyone else had already handed the lease to a new primary, giving you two nodes simultaneously believing they are primary, a split brain. Bounding clock drift is what rules that out. The epoch also works as a fencing token: storage rejects any write stamped with an epoch lower than the highest it has seen.
- Writes are unavailable for roughly lease expiry plus election plus propagation. Reads that do not need the latest data can keep going on in-region replicas throughout.
When the whole allowed region set is down, the correct behavior for a residency-bound tenant is to fail its requests, not to fail over to another jurisdiction. That is a product decision to make explicitly with the customer: offer two EU regions if they need regional failover.
Worked example
Tenant t-4812 is EU-only, primary in eu-west, replicas in eu-west and eu-central, epoch 41.
- A user updates an invoice. It commits at timestamp 1005; the client now holds token 1005.
- 30 ms later the same user loads the invoice list. The coordinator in eu-central picks the local replica, which has applied up to 990. 990 < 1005, so it waits up to 20 ms; the replica reaches only 998, so the read goes to the eu-west primary and returns the updated invoice.
- eu-west loses power. After lease expiry the eu-central replica becomes primary at epoch 42. A coordinator still on epoch 41 sends a write to eu-west, gets a connection error, refreshes the map, sees epoch 42, and retries against eu-central.
- A US coordinator receives a request for
t-4812. The map saysallowed_regions = EU, so it forwards the statement to an EU coordinator. It never reads a US copy, because there is no US copy in the map to read.
Trade-offs and pitfalls
- Caches, logs and backups are also copies. A coordinator that caches result sets, a query log with literal values, or a backup job writing to a default bucket in another region all break residency while the routing table looks perfect. Check each against
allowed_regions. - Waiting for a replica versus going to the primary trades latency for primary load. If most reads carry fresh tokens (chatty user sessions), routing them to the primary is honest; do not pretend replicas are taking that load.
- Cross-tenant queries (an internal report over all tenants) cannot follow per-tenant residency; run them over a separately governed, residency-aware aggregate store rather than letting the router fan out globally.
- Pitfall: trusting a routing cache TTL as the correctness mechanism. Correctness must come from the epoch check at the storage node; the cache is only a performance optimization.
- Pitfall: letting a tenant move between regions by updating
primaryalone. A move is copy, catch up, flip with a new epoch, then delete the old copies, and residency must hold at every step (both source and destination insideallowed_regions).
Design a secure multi-tenant microservice platform where tenant isolation, data protection, and noisy-neighbor mitigation matter. Compare isolation options (namespaces, containers, VMs), per-tenant quotas and throttling, encryption choices, monitoring requirements, and the operational trade-offs between cost and isolation strength.
Sample Answer
Direct answer
I would treat isolation as a ladder and put each tenant on the lowest rung its threat allows. If tenants only use our code and send us data, per-tenant Kubernetes namespaces with quotas, network policies and per-tenant encryption keys are enough and cost little. If tenants run their own code on our platform, containers alone are not a security boundary (they share the host's kernel), so I would move them into a sandboxed runtime or small virtual machines. Noisy-neighbour protection is a separate problem from security: it is solved with per-tenant quotas and throttling at every shared resource, and it is proved with per-tenant monitoring.
A few terms used throughout
The kernel is the core program that mediates every process's access to CPU, memory, files and network, by handling system calls (the requests a running program makes to it, like "open this file" or "send this data"); containers on the same machine all share one kernel. A container escape, sometimes via a kernel exploit (a bug in the kernel itself), is when code inside a container breaks out of its boundary and reaches the host, and from there potentially every OTHER tenant's containers on that same machine, not just its own. A hypervisor is the layer that lets one physical machine run several virtual machines, each with its own emulated hardware, which is why a VM-level boundary survives a kernel exploit that a container-level one does not. Attack surface is the total set of ways in an attacker could exploit, so a smaller attack surface means fewer such ways in. The control plane is the part of a cluster that manages it (schedules workloads, stores configuration) rather than running the tenant workloads themselves.
First, name the threat
- Accident and noise: a tenant's workload uses too much CPU, memory or I/O, or a bug in our code crosses tenants. Our code is trusted; tenants are not attackers.
- Malicious or untrusted tenant code: a tenant uploads a plugin, script or container. Now a kernel exploit in that code is a cross-tenant breach.
The first threat is mostly about fairness and correctness; the second is about hard security boundaries. Mixing them up leads either to overspending (VMs for everyone) or to a real breach (containers for untrusted code).
Isolation options compared
One ambiguity to clear up: "namespaces" can mean Linux namespaces (the kernel feature that gives a process its own view of processes, network and filesystem, which is what a container is built from) or Kubernetes namespaces (a named partition inside one cluster for organising objects, quotas and permissions). Below, "namespace" means the Kubernetes kind.
| Option | What is shared | Boundary strength | Cost and density | Good for |
|---|---|---|---|---|
| Kubernetes namespace per tenant (pods from many tenants on the same nodes) | Nodes, kernel, cluster control plane | Policy-level: role-based access control (RBAC), network policies, quotas. A kernel or container escape crosses tenants | Highest density, lowest cost | Trusted code, noise and accident isolation |
| Containers on dedicated nodes per tenant | Cluster control plane only | A container escape reaches only that tenant's nodes | Lower density: idle node capacity per tenant | Large tenants, strong noise isolation |
| Sandboxed containers (gVisor, which puts a second, unprivileged kernel-like layer between the container and the real kernel, so even code that finds a way to misbehave is intercepted by that layer instead of reaching the host's actual kernel) or microVMs (Firecracker, Kata Containers: a tiny virtual machine per pod) | Host hardware, hypervisor | Much smaller attack surface than a shared kernel | Some per-pod overhead in memory and startup | Untrusted tenant code at scale |
| Full VMs or separate clusters per tenant | Nothing but hardware or nothing at all | Strongest | Highest cost, most to operate | Regulated or contractual isolation |
Per-tenant quotas and throttling
Every shared resource needs its own limit, because a noisy tenant will find the one you forgot.
- Admission (API edge): a per-tenant token bucket: each tenant earns request tokens at a fixed rate up to a burst size; with no token, the request gets HTTP 429 and a retry hint. Plus a per-tenant cap on concurrent in-flight requests, which catches slow expensive requests that a rate limit misses.
- Compute: a
ResourceQuotaper namespace (caps total CPU, memory and object counts a tenant can request) and aLimitRange(default and maximum per container, so nothing runs unbounded). Priority classes (labels that tell the scheduler which workloads to keep and which to kill first when a node runs short on resources) decide who is evicted first under pressure. - Data stores: per-tenant connection limits in the connection pooler (a component that shares a small, fixed number of real database connections across many requests, since the database itself can only hold so many open at once), statement timeouts, and per-tenant partitions or weighted fair scheduling (giving each tenant a guaranteed proportional share of throughput, instead of pure first-come-first-served) on shared queues.
- Network: network policies default-deny (block all traffic unless a rule explicitly allows it) traffic between tenant namespaces; egress limits stop one tenant saturating shared bandwidth.
Encryption choices
- In transit: TLS at the edge, and mTLS (mutual TLS: both sides present certificates, so each service proves its identity) between services, typically from a service mesh (an infrastructure layer that runs alongside every service to manage service-to-service traffic, including issuing and rotating the certificates mTLS needs, without changing application code). mTLS also gives every call an authenticated workload identity you can check against the tenant it claims to act for.
- At rest, per tenant: envelope encryption. Each tenant has its own key-encryption key in a key management service (KMS); data is encrypted with data keys that are themselves encrypted by the tenant's key. Benefits: a leaked backup is useless without that tenant's key, you can rotate one tenant's key, and deleting a tenant's key makes all its data unreadable (crypto-shredding), which helps with deletion requests.
- Customer-managed keys (the tenant holds the key in its own account and can revoke it) as a premium option for regulated tenants. The trade-off: if they revoke it, their service stops, and your support team must understand that.
Monitoring requirements
You cannot manage noisy neighbours you cannot see. Every metric, log line and trace carries tenant_id, and you alert on per-tenant saturation (share of quota used, throttled request rate, p99 latency by tenant: p99 is the 99th percentile, the latency 99% of requests beat).
The cardinality trap, with numbers. A request-latency histogram with 12 buckets exports 14 time series (12 buckets plus a sum and a count). Labelled by 20 endpoints and 10,000 tenants:
14×20×10,000=2,800,000 time seriesThat is from one metric. The fix: keep full-detail metrics per endpoint without the tenant label, emit per-tenant metrics only for a few coarse signals (requests, errors, throttles, CPU seconds), and put per-tenant detail in logs or traces, which are sampled and queried on demand.
Worked example: choosing rungs for a real platform
A workflow-automation platform: 3,000 tenants, 2,950 using only built-in steps, 50 enterprise tenants, and a new feature letting tenants run custom JavaScript steps.
- Built-in steps (trusted code): shared nodes, namespace per tenant, quotas, default-deny network policy, per-tenant KMS key.
- Custom JavaScript steps (untrusted code): run in a separate node pool using a sandboxed runtime or microVMs, with no network access except a proxy that enforces the tenant's allowlist, and hard CPU-time and memory caps per execution.
- 50 enterprise tenants: dedicated node pools for predictable performance and an easy story for their security reviews.
The design choice that matters: the untrusted-code pool is separated by what runs, not by who the customer is. A small tenant's custom script is as dangerous as a large one's.
Operational trade-offs between cost and isolation strength
- Each rung up the ladder lowers density: dedicated nodes waste the capacity a tenant does not use, and a cluster per tenant multiplies control-plane cost and upgrade work.
- Stronger isolation also slows operations: patching 3,000 VMs is harder than patching 40 shared node pools.
- The cheapest real improvement is usually not a stronger rung but a missing quota; most noisy-neighbour incidents come from an unbounded shared resource (connections, a queue, a cache), not from weak compute isolation.
Pitfalls
- Treating Kubernetes namespaces as a security boundary for untrusted code.
- Rate-limiting requests but not concurrency, so one tenant's slow reports exhaust a worker pool.
- Per-tenant encryption keys with a shared application role that can decrypt everything anyway. The key boundary only holds if key access is scoped per tenant too.
- What would change my recommendation: if every tenant ran custom code (a hosting or compute platform), sandboxing becomes the default rung for everyone, not an exception.
Unlock Full Question Bank
Get access to all Multi-Tenancy and Isolation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.