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.
Define multi-tenancy in the context of data platforms. Describe and compare the common isolation models: shared-schema (single table with a tenant_id column), shared database with a separate schema per tenant, a separate database per tenant, and fully isolated infrastructure (separate clusters or accounts). For each model, cover security, operational cost, scalability, backup and restore granularity, schema evolution and index design, and onboarding time for new tenants, and give a short example of when you'd pick it.
Sample Answer
Direct answer
Multi-tenancy means one platform (one codebase, one operations team, often shared hardware) serves many customers, called tenants, while each tenant sees only its own data and gets predictable performance. The isolation models form a spectrum: the more you share, the cheaper and faster to onboard, but the weaker the security boundary and the coarser your control over any single tenant. On a data platform I default to the shared model for the long tail of small tenants and reserve heavier isolation for tenants whose contracts, regulators or workloads demand it.
The spectrum in plain terms
Think of an apartment building. Shared-schema is everyone's mail in one big sorted pile, with a label on each letter. Schema-per-tenant gives each flat its own mailbox in the same lobby. Database-per-tenant gives each flat its own locked room. Separate storage and compute (the fourth tier below) gives each flat its own room and its own lift. Fully isolated infrastructure is a separate building per tenant.
- Shared schema (the "pool" model): every tenant's rows live in the same tables, distinguished by a
tenant_idcolumn. Every query must filter on it. - Shared database, schema per tenant: one database server; each tenant gets its own namespace of tables (
tenant_42.orders). - Database per tenant: each tenant gets its own logical database, possibly on shared servers.
- Separate storage buckets and compute warehouses per tenant: common on modern data platforms that separate storage from compute. Each tenant's files live in its own object-storage bucket (or prefix with its own encryption key), and its queries run on its own compute cluster (a Snowflake "virtual warehouse", for example, is a named compute cluster you can size and bill independently). Control plane and catalog are still shared.
- Fully isolated infrastructure (the "silo" model): a separate cluster, cloud account or subscription per tenant. Nothing but the deployment pipeline is shared.
The literature also names a "bridge" model: a mix, where some layers are shared and others are per tenant. Schema-per-tenant and the storage-plus-warehouse tier are both bridge designs.
Comparison across the six dimensions
| Model | Security boundary | Operational cost | Scalability | Backup and restore granularity | Schema evolution and index design | Onboarding time |
|---|---|---|---|---|---|---|
Shared schema + tenant_id | Weakest: one missing filter leaks data. Harden with database row-level security (RLS, where the database itself appends the tenant filter) | Lowest: one set of tables to run and monitor | Best for many small tenants; shard by tenant_id (split the data across multiple database servers, consistently routing each tenant to one shard by its tenant_id) once a single database fills up | Coarse: backups are whole-database, so restoring one tenant means restoring to a side copy and copying that tenant's rows back | One migration covers everyone. Every index should lead with tenant_id (for example (tenant_id, created_at)) so queries touch one tenant's slice | Seconds: insert a tenant row |
| Schema per tenant | Moderate: database permissions per schema, but same server and same superuser (an account with unrestricted access to every schema on the server, the one boundary schema-per-tenant does not divide) | Medium: migrations and monitoring multiply by tenant count | Catalog bloat (the database's own internal table of tables grows by tenant count times table count, and a very large catalog slows down planning and admin queries) past a few thousand schemas (every table counted per tenant) | Per-schema logical dump (an export of the schema's data and structure as portable files, not a copy of the raw on-disk storage) and restore is practical | Migrations run N times and can half-fail; indexes can be tuned per tenant | Seconds to minutes: create schema and run migrations |
| Database per tenant | Strong logical boundary: separate credentials, can use a per-tenant encryption key | Higher: connection pools, backups and upgrades per database | Tenants can be moved between servers individually | Clean: point-in-time restore (restoring to exactly how the database looked at a chosen moment, using continuous transaction logs, not just the last nightly backup) of one tenant without touching others | Per-database migrations; drift (tenants silently ending up on different schema versions when a migration partially fails or is skipped for one database) between tenants is the main risk | Minutes: provision database, apply schema |
| Separate storage bucket + compute warehouse | Strong for data at rest (bucket policy and key per tenant); shared catalog and control plane (the shared management layer tracking table definitions, permissions and job scheduling across every tenant, as opposed to the data itself) | Pay per tenant for compute, but compute can auto-suspend when idle | Excellent: a heavy tenant's queries run on its own compute, so they cannot slow others | Per bucket: versioning or snapshot per tenant | Shared table definitions in the catalog, per-tenant physical layout (partitioning, clustering keys) | Minutes: bucket, key, warehouse, grants via automation |
| Fully isolated infrastructure | Strongest: separate account or cluster, separate network, blast radius of one tenant | Highest: full stack per tenant, plus a fleet to patch | Scales per tenant, but the fleet itself becomes the scaling problem | Whole environment per tenant, trivially isolated | Every environment upgraded separately; versions drift unless automation is strict | Hours to days unless fully automated |
Blast radius in the table means how many tenants one failure or breach can affect.
Worked example: when each wins
A B2B (business-to-business) analytics product with 2,000 customers:
- Shared schema: 1,900 self-serve customers on a free or starter plan, each storing a few gigabytes. Per-tenant infrastructure would cost more than they pay. Put them in shared tables with RLS, with
tenant_idleading every index. - Schema per tenant: a mid-market segment that wants custom columns or per-tenant index tuning, where the count stays in the hundreds today. Worth sizing the operational cost this segment would hit at scale, though: if one migration takes 3 seconds per schema, migrating a fleet that grew to 2,000 tenant schemas would take 2,000 x 3 = 6,000 seconds, 100 minutes of serial migration, and any failure in the middle leaves the fleet on mixed versions.
- Database per tenant: a healthcare customer that needs its own encryption key and a restore of its data to yesterday at 14:00 without touching anyone else.
- Separate bucket + warehouse: a retail customer running heavy nightly scans that would starve others. Give it its own compute warehouse, billed to it directly, while the catalog stays shared.
- Fully isolated infrastructure: a bank or government agency whose contract requires a separate cloud account, its own network and an audit showing no shared compute.
Trade-offs and pitfalls
- Pick per tier, not per platform. Most real systems run two or three of these models at once and route each tenant by plan. The mistake is choosing one model for everyone.
- Shared schema is only safe with enforcement below the application. An ORM (object-relational mapping library) filter is one forgotten
WHEREaway from a leak; RLS or a tenant-scoped data-access layer makes the filter impossible to skip. - Indexes without
tenant_idfirst force the database to scan every tenant's rows to answer one tenant's query, and a unique constraint onemailalone would stop two tenants from having the same user. - Restore granularity is usually discovered during an incident. Decide up front how you will restore one tenant in the shared model (a side restore plus a scripted copy of that tenant's rows) and rehearse it.
- Moving a tenant between models later (shared to dedicated when it grows) is a data migration. Design
tenant_idinto every table and every key from day one so the move is a copy, not a re-model.
Design a solution to enforce per-tenant data residency and compliance in a multi-region SaaS platform where some tenants must keep data in the EU while others must stay within APAC. Include routing, storage placement, failover, and how to prevent accidental cross-region writes.
Sample Answer
Direct answer
I would deploy the platform as independent regional stacks, one set inside the EU and one set inside APAC (Asia-Pacific), and give every tenant a home jurisdiction fixed at signup. All of a tenant's customer data (databases, files, backups, logs, analytics copies) lives only in stacks inside that jurisdiction. A small global layer knows only which jurisdiction each tenant belongs to, so it can route traffic without storing customer data. Accidental cross-region writes are prevented in layers: the router sends requests to the right place, each regional service refuses tenants that do not belong to it, and cloud permissions and encryption keys make writing outside the jurisdiction fail even if the code is wrong.
Terms first
- Data residency: a requirement that data is stored (and usually processed) inside a named geography, set by law, regulation or contract.
- Jurisdiction boundary: here "EU" and "APAC". Read the contracts carefully: "APAC" in a contract may mean one specific country (for example Australia only), which changes which regions count as inside.
- Failover: switching traffic to a standby copy when the primary site fails.
Architecture
flowchart TB
U[User or API client] --> G[Global edge and router]
G --> DIR[(Tenant directory: tenant to jurisdiction, no customer data)]
G -->|EU tenants| EU1[EU primary: Frankfurt]
G -->|APAC tenants| AP1[APAC primary: Sydney]
EU1 -. replicate and back up .-> EU2[EU standby: Ireland]
AP1 -. replicate and back up .-> AP2[APAC standby: Melbourne]
Routing
- At login the user gets a token containing the tenant ID. The global router looks the tenant up in the directory and sends the request to that tenant's primary region. Tenant-specific hostnames (
acme.eu.example.com) make this visible and cacheable in DNS. - The directory holds only tenant ID, jurisdiction and current primary region: configuration, not customer data. It can be replicated globally.
- The router terminates TLS (decrypts the HTTPS connection) at the edge only to read enough to route the request. But terminating TLS means the router necessarily sees the whole request in plaintext at that moment, including its body, not just its destination hostname; so if that edge location sits outside the tenant's jurisdiction, the request body technically passes through, even briefly and even if nothing is stored, outside it. Whether that transient processing outside the jurisdiction is acceptable is a legal question; the conservative choice is regional edge endpoints for regulated tenants, so the TLS termination point itself, not just the storage, stays inside the jurisdiction.
Storage placement
- Each regional stack has its own databases, object storage, search indexes, caches and queues.
- Each region uses its own encryption keys held in that region's key management service (a managed service that generates and stores encryption keys and controls who may use them, so application code asks it to encrypt or decrypt rather than ever handling the raw key itself). A copy of EU data in APAC would be unreadable without EU keys, which gives a second line of defence.
- Global services (billing, product analytics, feature flags: runtime switches that turn a piece of behaviour on or off for specific tenants without a deploy) receive only non-personal or aggregated data. That is a data-classification decision made per field, not per service.
Failover inside the jurisdiction
- EU primary Frankfurt (AWS
eu-central-1) replicates to a standby in Ireland (eu-west-1); APAC primary Sydney (ap-southeast-2) replicates to Melbourne (ap-southeast-4). If an APAC tenant's contract allows Singapore, that is an alternative standby. - The failover runbook (a written, tested set of steps for handling this specific kind of incident, followed by whoever is on call rather than improvised in the moment) changes the directory's primary region for affected tenants to the standby in the same jurisdiction. There is deliberately no automation path that fails an EU tenant over to APAC.
- The honest trade-off: a disaster that takes out both regions in one jurisdiction means downtime for those tenants, because failing over abroad would breach the contract. State that in the SLA (service-level agreement).
Preventing accidental cross-region writes
Enforcement points, from the edge inward:
| Enforcement point | Control |
|---|---|
| Router | Routes by the directory; rejects a request if the token's tenant is unknown |
| Every regional microservice | Middleware checks "does this tenant belong to my region?" before any read or write, and rejects with an error if not. This catches bugs where one service calls another service in the wrong region |
| Service-to-service calls | Service discovery (the system services use to look up each other's current network address at runtime, instead of a service having another service's address hard-coded) returns only same-region endpoints; there are no cross-region service addresses in the EU stack's configuration |
| Cloud permissions | EU workloads run in EU-only accounts whose policies deny any storage or database call to non-EU regions (on AWS, an organization-level service control policy: a permission guardrail set centrally that overrides whatever an individual account's own settings allow, using the aws:RequestedRegion condition key) |
| Encryption keys | Per-region keys; an EU service has no permission to use APAC keys and vice versa |
| Backups | Backup copies go only to the same-jurisdiction standby region; backup-copy rules are defined in code and reviewed |
| Analytics pipelines | Each region runs its own pipeline and warehouse; only aggregated, non-identifying metrics are exported to a global dashboard |
| Logs and traces | Regional log storage; personal fields redacted before any global aggregation |
| CI (continuous integration) checks and audits | Infrastructure-as-code scans reject any replication, backup-copy or bucket rule targeting another jurisdiction; a daily job scans storage inventories for tenant IDs in the wrong region and alerts |
Worked example: an EU tenant during an incident
- Acme (EU jurisdiction, primary Frankfurt) calls the API. The router reads the directory, sees
eu-central-1, forwards to the EU stack. - Frankfurt has a regional outage. The on-call engineer runs the failover runbook: Acme's directory entry becomes
eu-west-1; the Ireland standby is promoted (switched from a read-only replica into the read-write primary that now accepts Acme's writes). - A bug in a newly deployed reporting job tries to write Acme's export to an APAC bucket. The regional middleware passes it (the job believes it is in the EU), but the EU account's permission policy denies the call to
ap-southeast-2, the write fails, an alert fires, and nothing crossed the border. - Acme's nightly backup copy lands in Ireland only; the global usage dashboard receives "Acme: 1.2M API calls today" and no personal data.
Trade-offs and pitfalls
- Cost: two regions per jurisdiction doubles standby cost for each jurisdiction you support, and regional stacks mean more deployments. The alternative, a single global database with row-level region tags, is cheaper but cannot give a clean residency guarantee.
- Support staff abroad viewing EU data is itself cross-border access in many legal frameworks; route support access through tooling that runs in-region with approval and audit.
- Common wrong turns: treating "stored in the EU" as enough while logs, caches, search indexes or a third-party email or monitoring vendor still copy data abroad; allowing a tenant's jurisdiction to be changed by a normal admin action rather than a controlled migration; and forgetting that global disaster-recovery automation will happily fail over across the border unless it is told not to.
Explain encryption at rest and encryption in transit in the context of multi-tenant services. Describe a high-level design for per-tenant encryption keys using a cloud KMS: key isolation, envelope encryption for blobs, key access policies, and operational considerations for key rotation and emergency key revocation.
Sample Answer
Direct answer
Encryption in transit protects data while it moves over a network (TLS, Transport Layer Security, the standard protocol for encrypting a network connection, between clients and the service, and mutual TLS, where both sides present certificates, between internal services). Encryption at rest protects data stored on disks, databases, object storage and backups. In a multi-tenant service both are baseline, but neither separates tenants from each other: a disk encrypted with one platform key is readable by any process allowed to read the disk. Tenant isolation through encryption comes from per-tenant keys held in a cloud KMS (key management service), applied with envelope encryption (encrypting each object with its own one-time data key, then encrypting that small data key, not the object, with the tenant's KMS key; the mechanics are below), with key policies that only let the right tenant's requests use the right key.
Three tiers of key granularity
| Model | How it works | Isolation | Cost and effort |
|---|---|---|---|
| Single platform key | One key encrypts everything (typical default disk or storage encryption) | Protects against stolen disks, not against a bug that reads the wrong tenant's rows | Near zero |
| Per-tenant key | Each tenant has its own KMS key; all of that tenant's data keys are wrapped by it | A leaked data key exposes one object; a disabled tenant key makes that tenant's data unreadable without touching others | One KMS key per tenant (AWS KMS lists 1 US dollar per key per month) |
| Per-entity key | Each record, file or user inside a tenant has its own data key | Finest-grained deletion: crypto-shredding means destroying the key itself, so every copy of the data it protects, including backups, becomes permanently unreadable without touching the data at all ("crypto-shred one customer's record") | Many more keys to store and manage |
The common answer: a KMS key per tenant, plus a fresh data key per object or per file under it. Per-entity keys are added only where you need to delete or revoke individual records cryptographically.
Envelope encryption for blobs
Calling KMS to encrypt every byte would be slow and costly, and KMS limits how much data one call can take. Instead:
- Ask KMS for a new data key (DEK, data encryption key) under the tenant's key. KMS returns it twice: in plaintext and encrypted ("wrapped") by the tenant's key-encryption key (KEK), which never leaves KMS.
- Encrypt the blob locally with the plaintext DEK (AES-256-GCM, a standard, widely used symmetric encryption algorithm).
- Store the ciphertext together with the wrapped DEK; discard the plaintext DEK from memory.
- To read: send the wrapped DEK to KMS, which checks that the caller may use that tenant's key, returns the plaintext DEK, and the service decrypts locally.
sequenceDiagram
participant App
participant KMS
participant Store
App->>KMS: Generate data key (tenant 42 key)
KMS-->>App: plaintext DEK + wrapped DEK
App->>App: encrypt blob with DEK
App->>Store: ciphertext + wrapped DEK
App->>KMS: Decrypt wrapped DEK (context tenant 42)
KMS-->>App: plaintext DEK (if policy allows)
Worked example: tenant 42 uploads a 50 MB file. One KMS call produces a DEK; the 50 MB is encrypted locally; the stored object is 50 MB of ciphertext plus a few hundred bytes of wrapped key. Reading it costs one KMS call, not one per block.
Key access policies
- The tenant's key policy allows only the service role (the identity the application itself, not a person, assumes to call KMS) that handles that tenant, never a wildcard.
- Bind each operation to the tenant with encryption context (non-secret key-value pairs such as
tenant_id=42that must match on decrypt; AWS KMS supports conditions on them withkms:EncryptionContext:condition keys). A request that tries to decrypt tenant 42's data key while claiming tenant 7 fails. - Every KMS call is logged (AWS CloudTrail on AWS), which gives an audit trail per tenant key.
Operational considerations
Rotation. Rotating a KMS key generates new key material for new encryptions while keeping the old material to decrypt old data, so nothing needs to be re-encrypted. The benefit is forward-looking, not retroactive: if one specific key version is later suspected of compromise, only the data keys wrapped under that version are exposed, not every data key the tenant has ever had, and every new object from that point wraps under the fresh version. Many compliance frameworks also require rotation on a fixed schedule regardless of suspicion. AWS documents default automatic rotation every 365 days, with a custom period available, and notes that rotation does not re-encrypt data or rotate the data keys already generated. If a data key itself is suspected compromised, rotation does not help: that data must be re-encrypted with a new DEK.
Emergency revocation. Disabling a tenant's key makes every later decrypt of that tenant's data fail immediately at KMS, which is the fastest containment action. Two caveats: data keys already decrypted and cached in application memory keep working until the cache expires (so keep cache lifetimes short, for example minutes), and scheduling key deletion (AWS enforces a waiting period of 7 to 30 days) is irreversible, so it is used for deliberate crypto-shredding at offboarding, not during an incident.
Cost and scale. 5,000 tenants at 1 dollar per key per month is 5,000 dollars a month before request charges, and each automatically rotated key adds 1 dollar per month for each of its first two rotations. Caching decrypted DEKs briefly keeps request volume and latency down.
Trade-offs and pitfalls
- Assuming "encrypted at rest" means tenants are isolated from each other; it does not.
- One key for all tenants means revoking a single tenant is impossible without re-encrypting everyone.
- Long-lived DEK caches quietly defeat emergency revocation.
- Per-entity keys everywhere add management cost with little benefit unless you need per-record deletion.
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.
Design a tenant-centric key management system using cloud KMS/HSM that supports tenant key creation, rotation, rekeying of stored data, emergency key revocation, access audit trails, and multi-tenant access controls. Explain how you would automate re-encryption of data on key rotation or rekey events while keeping costs reasonable for thousands of tenants.
Sample Answer
Direct answer
I would build a three-level key hierarchy: a per-tenant root key in the cloud KMS (key management service) or HSM (hardware security module, tamper-resistant hardware that holds keys and never exports them) that never leaves it, a per-tenant intermediate key wrapped by that root, and per-object data keys (DEKs) wrapped by the intermediate key. The hierarchy is what makes a forced key retirement cheap. On AWS KMS, routine scheduled rotation of the root needs no re-wrap at all, because KMS keeps old key material so every existing wrapped key keeps decrypting; what is not free is fully retiring a key you no longer trust, a rekey that forces every downstream copy off the old material. The hierarchy is what bounds that cost: retiring the root means re-wrapping one small intermediate key per tenant, not touching billions of objects. A full rekey (re-encrypting the data bytes themselves) is reserved for suspected compromise or policy change, and runs as a throttled background job that re-encrypts lazily on write and sweeps the rest per tenant. Tenant lifecycle (create, rotate, revoke, delete) is automated through a key service; every key use is audited with the tenant ID; and tenants can choose platform-managed keys (we own the root) or customer-managed keys (the root lives in the tenant's own KMS and they can revoke us).
Rotation vs rekey: the distinction everything hinges on
| Rotation | Rekey | |
|---|---|---|
| What changes | The wrapping key's material | The key that actually encrypted the data |
| Work required | Re-wrap the small wrapped keys below it, or nothing if the KMS keeps old material | Read, decrypt and re-encrypt every byte |
| When | Scheduled compliance (for example yearly) | Suspected DEK or intermediate compromise, algorithm change, tenant demand |
On AWS KMS, automatic rotation keeps all previous key material so old ciphertext still decrypts, and AWS states that rotation does not re-encrypt data or rotate data keys. So scheduled rotation of the root is nearly free operationally; the design problem is making rekey affordable.
Architecture
flowchart TB
KMS[Cloud KMS / HSM: tenant root key] -->|wraps| TK[Tenant intermediate key, wrapped copy in key DB]
TK -->|wraps| DEK[Per-object DEKs stored with objects]
KS[Key service: lifecycle + policy] --> KMS
KS --> KDB[(Key metadata DB)]
APP[App services] -->|unwrap via key service| KS
RJ[Rekey worker] --> KS
KMS --> AUD[Audit log per tenant]
Tenant key creation
At onboarding the key service creates the tenant's root key in KMS (tagged with tenant_id, key policy restricted to the key service's role), generates the intermediate key, stores only its wrapped form plus a version number, and records tenant -> root key ID, intermediate version in the key metadata DB. Everything is idempotent (running the same operation twice has the same effect as running it once) so a retried onboarding cannot create two roots.
Platform-managed vs customer-managed keys. For customer-managed keys (often called BYOK, bring your own key) the tenant creates the root in their own cloud account and grants our key-service role permission to use it (on AWS, via a key policy, or a grant, a temporary, revocable KMS permission you can hand to another principal and pull back immediately, faster than editing a key policy). The tenant can then revoke us at any moment, which is the point, so the product must handle "key unavailable" as a normal state: return a clear error, stop background jobs for that tenant, and alert the account team. Platform-managed is the default for the long tail; customer-managed is an enterprise option with its own support runbook.
Multi-tenant access controls
- Only the key service can call KMS; application services ask the key service to unwrap, passing their authenticated tenant context.
- Every KMS call carries encryption context
tenant_id=<id>, and the key policy requires it (AWS supportskms:EncryptionContext:condition keys), so a bug that mixes tenant IDs fails closed (the call is denied by default when something is wrong or missing, rather than silently allowed). - Tag-based policies (attribute-based access control) avoid writing 5,000 bespoke policies.
Access audit trails
KMS logs every call (CloudTrail on AWS) with the key ID and encryption context, so you can answer "who used tenant 42's key in March". The key service adds its own log of which application request caused each unwrap. Expose a per-tenant export of this to enterprise customers.
Emergency revocation
Disable the tenant root key in KMS. New unwraps fail immediately. Unwrapped intermediate keys cached in the key service keep working until their cache expires, so the cache lifetime (for example 5 minutes) is the revocation latency bound, and the key service also supports a push "evict tenant 42" message to drop them at once. Deletion (AWS enforces a 7 to 30 day waiting period) is the crypto-shred step for offboarding: once the root key is gone, every copy of the tenant's data ever encrypted under it, including old backups you can no longer edit individually, becomes permanently unreadable, without having to find and erase each copy.
Automating re-encryption at reasonable cost: worked numbers
Assume 3,000 tenants and 2 billion stored objects, with the AWS KMS list price of 0.03 US dollars per 10,000 requests and 1 dollar per key per month.
Naive design, each DEK wrapped directly by the KMS key. Routine rotation costs nothing extra here either, for the same reason as above: old key material still decrypts. What costs money is fully retiring the key, for example after a suspected compromise, which forces every object's DEK to be re-wrapped under a new key: one KMS call per object, 2,000,000,000 / 10,000 x 0.03 = 6,000 dollars in requests, and far more importantly billions of calls against the account's KMS request-rate quota, which would starve live traffic for days.
Three-level hierarchy. Routine rotation of the root needs no re-wrap at all, same reason. Fully retiring a compromised root means re-wrapping one intermediate key per tenant: 3,000 calls, under 1 cent, done in seconds, not touching a single object or DEK. You would retire an intermediate key on its own, rather than the root, when only one tenant's key material is suspected compromised, or a tenant asks to rotate independently of everyone else: that means re-wrapping that tenant's DEKs locally (fast AES, Advanced Encryption Standard, the symmetric cipher fast enough to run with no network call, operations, no KMS calls per object), without touching the root or any other tenant.
Full rekey of one large tenant (suspected compromise, 20 TB of data). At an assumed 200 MB/s per worker, 20 x 10^12 / (200 x 10^6) = 100,000 s, about 27.8 hours for one worker, or about 2.8 hours with 10 workers. The rekey worker:
- Creates a new intermediate key version; all new writes use it immediately.
- Rewrites objects lazily when they are next written, and sweeps the rest in the background in batches, per tenant, with a rate limit so the tenant's own traffic is not starved.
- Records progress (last object key done) so it resumes after failure; each object is re-encrypted by writing a new version and swapping atomically, so a crash never leaves an object unreadable.
- Retires the old key version only when a scan confirms zero objects still reference it.
KMS key cost: 3,000 root keys at 1 dollar is 3,000 dollars a month, rising to 9,000 once each has been rotated twice (AWS charges 1 dollar a month for each of the first two rotations, then no more). The KMS default quota is 100,000 customer-managed keys per account per Region (adjustable), so per-tenant roots fit comfortably; beyond that, shard tenants across accounts.
Minimizing performance overhead
- Cache unwrapped intermediate keys in the key service for minutes; per-request cost is then local AES, which is cheap next to network and disk.
- Generate DEKs locally from a secure random source and wrap them with the cached intermediate key, instead of a KMS call per object.
- Keep KMS off the hot path (the code executed on every single request, where added latency is felt by every user) for reads: one unwrap per tenant per cache period, not per request.
- Batch rekey work and run it at off-peak rates per tenant.
Trade-offs and pitfalls
- Two-level (KMS key wraps every DEK) is simpler but makes rewrap and rekey scale with object count and KMS quotas.
- Caching improves speed but delays revocation; make the cache lifetime a documented security parameter and support explicit eviction.
- Customer-managed keys give tenants a kill switch over your service; treat key-unavailable as an expected state, not an exception.
- Rekey without resumable progress turns a failure halfway through 20 TB into a restart from zero.
Unlock Full Question Bank
Get access to all 16 Multi-Tenancy and Isolation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.