System DesignVol. 12 · Part XII
0 / 0

Shelves / System Design

SD·133

Multi-Tenancy

Designing SaaS systems that serve many customers safely and economically: tenancy models (shared database and schema with tenant IDs and row-level security, schema per tenant, database per tenant, and hybrid tiering), tenant context propagation, isolation at every layer (data, compute, network, caches, queues, search, files, logs), noisy neighbours and fairness, quotas and rate limits per tenant, tenant-specific configuration and feature flags, tenant onboarding and offboarding, data residency, encryption with per-tenant keys, cell-based tenant placement, cost attribution, and testing isolation.

27 topics · ~19 min read · 30-question quiz
Updated Suggest a correction

Start here: many customers, one system, no leaks

The tiffin centre now sells its ordering software to other kitchen chains. Each chain is a tenant: its own customers, menus and orders, all served by one shared system. Multi-tenancy is what makes software-as-a-service affordable (one fleet, one deploy, shared capacity) and it adds two requirements that single-customer systems never had: one tenant must never see another's data, and one tenant must never ruin the service for the others.

A forgotten WHERE clause

Orders for two tenants live in one table with a tenant_id column. The application is logged in for hyd-kitchens, and one query forgot its where tenant_id = …:

Text
without row-level security:
 hyd-kitchens | Asha  | 252
 hyd-kitchens | Ravi  | 180
 blr-tiffins  | Meena | 300     ← another company's customers
 blr-tiffins  | Kiran | 120
 blr-tiffins  | Arjun |  90

One missing filter, among thousands of queries, leaks every tenant's data. PostgreSQL's row-level security (RLS) makes the database add the filter itself:

SQL
alter table t_orders enable row level security;
create policy tenant_isolation on t_orders
  using (tenant_id = current_setting('app.tenant', true))
  with check (tenant_id = current_setting('app.tenant', true));
Text
same buggy query, RLS on:              only hyd-kitchens' 2 rows
insert a row for blr-tiffins:          ERROR: new row violates row-level security policy
no tenant set on the connection:       0 rows visible

The application sets app.tenant once per request (from the authenticated user), and every query on the table is filtered, including the ones somebody forgets to filter. One catch showed up in the lab: the database superuser still saw all 5 rows even with FORCE ROW LEVEL SECURITY, because superusers bypass RLS entirely. The application must connect as an ordinary role.

The noisy neighbour (simulation)

A simulation of one shared pool of 4 workers (20 ms per request, capacity 200 per second). Tenant A starts a runaway import at 300 requests per second; tenant B sends its normal 20:

Text
one shared pool, no limits:
   tenant A: p50  9,159 ms   p95 17,243 ms
   tenant B: p50  9,061 ms   p95 17,207 ms      ← B suffers for A's mistake
tenant A limited to 2 requests in flight (excess rejected with 429):
   tenant A: p50 20.0 ms, 6,504 rejected
   tenant B: p50 20.0 ms   p95 21.7 ms

With no limits, B's orders waited 9 seconds behind A's flood although B's own traffic was tiny. A per-tenant limit (a quota, a rate limit, or a concurrency cap: chapter 130's bulkhead, per tenant) rejected A's excess and left B untouched. Limits are a product decision as much as a technical one: tighter caps protect neighbours better but leave A less of the spare capacity (a cap of 3 served A 45% more requests and let B's p95 rise to 28.5 ms).

How deep to go in multi-tenancy

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain tenancy models and the two isolation requirements
L2 Propagate tenant context and enforce data isolation with RLS or equivalent
L3 Explain the trade-offs of shared, schema-per-tenant and database-per-tenant models and tiering
L4 Find isolation leaks and noisy-neighbour effects with tests and metrics
L5 Design a SaaS architecture: tenancy model, per-tenant limits, onboarding, migrations, billing data
L6 Operate a multi-tenant platform with tenant-level SLOs, cost attribution and compliance

What multi-tenancy is

A multi-tenant system serves many customers (tenants: companies, workspaces, organisations) from shared infrastructure and code, while making each tenant feel like it has its own isolated system. Almost all B2B SaaS products are multi-tenant.

Why share:

  • Cost efficiency: pooled infrastructure is far cheaper per tenant than dedicated stacks; most tenants are small.
  • Operational efficiency: one codebase, one deployment pipeline, one fleet to monitor and upgrade.
  • Speed: new tenants onboard in seconds.

What sharing risks:

  • Isolation failures: one tenant seeing another's data (the worst possible SaaS incident), or one tenant's load degrading others (noisy neighbours).
  • Compliance constraints: some tenants require data residency, dedicated infrastructure, customer-managed keys.
  • Blast radius: a bad deploy or a poison request affects every tenant at once.

Multi-tenant design is about choosing where to share and where to isolate, per layer and per tenant tier.

Tenancy models

shared schema orderstenant_id=A …tenant_id=B …tenant_id=A …tenant_id=C … schema per tenant tenant_a.orders tenant_b.orders tenant_c.orders database per tenant DB A DB B DB C isolation ↑ · cost per tenant ↑ · operational overhead ↑ · tenant density ↓ most SaaS: shared for the long tail, dedicated for premium/regulated tenants
Three data tenancy models. In the shared model, all tenants' rows live in the same tables, distinguished by a tenant_id column and protected by row-level security. In schema-per-tenant, tenants share a database server but have separate schemas with identical tables. In database-per-tenant, each tenant gets its own database (or cluster). Isolation, per-tenant cost and operational overhead all increase from left to right.

Shared database, shared schema

All tenants' data lives in the same tables; every row carries a tenant_id.

Pros Cons
Lowest cost; highest density (millions of small tenants fine) Isolation depends on every query filtering by tenant (bugs leak data)
One schema to migrate; simple operations Noisy neighbours share the same database resources
Cross-tenant analytics easy (for the provider) Per-tenant backup/restore, export and deletion are harder
Easy to onboard tenants instantly Large tenants can dominate tables and indexes

Make it safe:

  • Tenant ID in every table (including child tables; denormalise it even where a foreign key implies it) and leading every index ((tenant_id, created_at)), which also makes the tenant a natural shard key later (Citus, chapter 127).
  • Enforce in the data layer, not by convention: repositories/ORM filters that require a tenant (Hibernate @TenantId / filters, EF Core global query filters, Django managers, Prisma/Drizzle extensions) and, as defence in depth, database row-level security.
  • Composite foreign keys including tenant_id to prevent cross-tenant references.
SQL
-- PostgreSQL row-level security: the database itself enforces tenant isolation
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;          -- applies even to the table owner

CREATE POLICY tenant_isolation ON invoices
    USING (tenant_id = current_setting('app.tenant_id')::uuid)
    WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);

-- The application sets the tenant per transaction (from the authenticated principal)
BEGIN;
SET LOCAL app.tenant_id = '6f1c2a3e-…';
SELECT * FROM invoices WHERE status = 'OPEN';           -- only this tenant's rows, even if the query forgets
COMMIT;

Caveats: the application role must not be a superuser or have BYPASSRLS; use SET LOCAL (transaction-scoped) so pooled connections don't leak the setting to the next request; test policies; watch query plans (policies add predicates).

Shared database, schema per tenant

Each tenant gets its own schema (namespace) with identical tables in a shared database server.

Pros Cons
Stronger logical isolation (queries hit only the tenant's schema via search_path) Thousands of schemas strain catalogs, migrations and connection pooling
Per-tenant backup/restore/export simpler Migrations must run per schema (and can partially fail)
Per-tenant customisation possible (careful!) Still shared server resources (noisy neighbours)

Fits hundreds to low thousands of tenants; less common in new designs than shared schema + RLS or database-per-tenant.

Database per tenant

Each tenant gets its own database (on shared or dedicated servers), or even its own cluster/account.

Pros Cons
Strongest data isolation; per-tenant encryption keys, backup, restore, residency Cost and density: idle databases still cost money
Noisy-neighbour impact limited to shared server level (or none if dedicated) Operational overhead: provisioning, migrations, monitoring across N databases
Easy per-tenant offboarding (drop the database) Cross-tenant analytics need pipelines
Can place tenants in specific regions and tiers Connection management across many databases

Serverless/auto-pausing databases (Aurora Serverless v2, Neon, Azure SQL elastic pools, SQLite-per-tenant platforms such as Turso or Cloudflare D1 for very large numbers of small databases) reduce the cost of many small databases.

Hybrid (tiered) tenancy

Most mature SaaS products mix models by tier:

  • Pool: free and standard tenants share infrastructure (shared schema).
  • Bridge: some layers dedicated (e.g. a dedicated database, shared compute).
  • Silo: enterprise or regulated tenants get dedicated stacks (database, compute, possibly a dedicated cell or account) and customer-managed keys.

A tenant directory/catalogue records each tenant's placement (which cell, database, region, tier), and routing uses it. Moving a tenant between tiers (when it grows or upgrades) should be a supported, automated operation (copy data, sync changes via CDC, switch routing, verify).

Tenant context

Every request, message and job must carry the tenant context, derived from a trusted source:

  • From authentication: the tenant ID is a claim in the access token (or derived from the user's membership), never trusted from a client-supplied header or body parameter.
  • Routing hints (subdomain acme.app.example.com, path /t/acme/…) are for routing and UX; verify the authenticated principal belongs to that tenant.
  • Propagate through the call graph: request context objects, gRPC metadata, message envelopes (tenantId field), job payloads, log and trace attributes (OpenTelemetry baggage/resource attributes).
  • Set it at the data layer boundary (RLS session variable, repository scope) automatically from the context, so business code can't forget it.
// Spring: resolve tenant from the validated JWT, store in a scoped context, apply to DB sessions
@Component
class TenantFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws ServletException, IOException {
        var auth = (JwtAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        String tenant = auth.getToken().getClaimAsString("tenant_id");
        ScopedValue.where(TenantContext.CURRENT, tenant).run(() -> {      // Java 25: ScopedValue
            try { chain.doFilter(req, res); } catch (Exception e) { throw new RuntimeException(e); }
        });
    }
}
// Hibernate 6: @TenantId on entities + CurrentTenantIdentifierResolver reading TenantContext,
// and/or a connection customiser executing SET LOCAL app.tenant_id at transaction start for RLS.

Isolation beyond the database

Every shared component needs a tenant-isolation story:

Layer Risk Isolation technique
Caches Cross-tenant cache hits (key without tenant) Prefix every key with tenant ID (t:acme:invoice:42); never cache tenant data under global keys
Search indexes Results from other tenants Tenant filter enforced in the query layer (filtered aliases, document-level security), or index per tenant/tier
Object storage Shared buckets, guessable keys Prefixes per tenant with IAM conditions, pre-signed URLs scoped to the tenant's prefix, bucket per tenant for silo tiers
Queues/streams Messages processed in the wrong context; one tenant's backlog delays all Tenant ID in envelopes; per-tenant partitioning or fair scheduling; separate queues for large tenants
Background jobs Jobs run without tenant scope Jobs carry tenant; worker sets context before executing
Logs and traces Support staff see other tenants' data; exports leak Tenant attribute on all telemetry; access controls; avoid sensitive payloads
Analytics Cross-tenant data exposed in shared dashboards/exports Row-level filters in BI tools; per-tenant exports
Compute Noisy neighbours, side channels Quotas, priority classes, dedicated node pools for silo tenants, sandboxed runtimes for tenant-supplied code (gVisor, Firecracker, WebAssembly)
Network Tenant-dedicated components reachable by others Network policies, separate VPCs/accounts for silos
AI features RAG retrieving other tenants' documents; shared fine-tunes Tenant-filtered retrieval enforced outside the model; per-tenant indexes or namespaces

Noisy neighbours

A noisy neighbour is a tenant whose workload (bursty traffic, huge imports, expensive reports, pathological queries) consumes shared resources and degrades others. Defences, layered:

  • Per-tenant rate limits and quotas at the edge and in services (requests/s, concurrent requests, API calls per month).
  • Fair scheduling in shared queues and worker pools: per-tenant sub-queues served round-robin or weighted fair queueing, so one tenant's million-job import doesn't starve others; cap concurrency per tenant.
  • Workload separation: expensive operations (exports, reports, bulk imports) run on separate worker pools or read replicas with their own limits.
  • Database protections: statement timeouts, per-tenant connection limits (e.g. via pooler user mapping), query cost guards, partitioning large tenants' data.
  • Bulkheads by tier: premium tenants on dedicated capacity; free tier pooled with tighter limits.
  • Shuffle sharding / cells: limit how many tenants share fate with any given tenant (chapter 125).
  • Placement and rebalancing: monitor per-tenant resource consumption; move heavy tenants to their own shard/cell.
Python
# Fair dequeueing across tenants: round-robin over per-tenant queues (Redis lists), with per-tenant concurrency caps
def next_job(r, tenants: list[str], cap: int):
    for _ in range(len(tenants)):
        tenant = tenants[r.incr("rr:pointer") % len(tenants)]
        if int(r.get(f"inflight:{tenant}") or 0) >= cap:
            continue                                          # tenant at its concurrency cap
        job = r.lpop(f"jobs:{tenant}")
        if job:
            r.incr(f"inflight:{tenant}")
            return tenant, job
    return None

Quotas and limits

Quotas serve fairness, cost control and product tiers:

Kind Example Enforcement
Rate 100 requests/s per tenant Token bucket at gateway (keyed by tenant)
Concurrency 10 concurrent exports Semaphores/counters per tenant
Volume 1M API calls/month, 100 GB storage, 50 seats Metering pipeline + checks at write time; soft vs hard limits
Object counts 1,000 projects, 10,000 webhooks Database checks/constraints
Feature limits SSO only on enterprise tier Entitlements service + feature flags

Design: a central entitlements/limits service (or configuration in the tenant catalogue) defines limits per plan and per-tenant overrides; services cache it. Distinguish soft limits (warn, notify, allow overage billing) from hard limits (reject with clear errors: 429 with quota headers or 403 with problem details explaining the limit). Meter usage accurately (events → aggregation) for billing and limit enforcement.

Tenant-specific configuration

Tenants differ: branding, locale and currency, enabled features, integrations, SSO configuration, workflows, custom fields, data retention periods, regional placement.

  • Store configuration in a tenant configuration store (database tables with schema validation), cached per tenant with invalidation on change.
  • Use feature flags with tenant targeting (OpenFeature with tenant context) for gradual rollouts and entitlements.
  • Support custom fields via structured extension mechanisms (JSONB columns with JSON Schema validation, EAV tables carefully, metadata-driven forms) rather than per-tenant schema changes.
  • Resist per-tenant code forks: they destroy the economics of SaaS. Prefer configuration, extension points (webhooks, plugins/sandboxed scripts such as WebAssembly), and integrations.
  • Version tenant configuration and audit changes (who enabled what, when).

Tenant lifecycle

  • Onboarding: create the tenant record and default configuration, provision tier-specific resources (schema/database/cell placement), seed data, set up identity (SSO/SCIM), all automated and idempotent (a provisioning workflow, often in a durable workflow engine).
  • Changes: plan upgrades/downgrades (moving between tiers/placements), region moves (residency changes), mergers of tenants.
  • Offboarding: export data for the customer, deletion after a grace period (including backups' expiry, caches, search indexes, logs, analytics copies, third-party processors), with evidence of deletion; per-tenant encryption keys make deletion verifiable via crypto-shredding (destroy the key).

Data residency

Some tenants (or regulations) require data to be stored and processed in specific jurisdictions (EU, India, specific countries for government or financial customers).

  • Regional deployments (stacks per region) with tenants pinned to a home region in the tenant catalogue; a global routing layer sends each tenant's traffic to its region (chapter 134).
  • Keep personal and customer data in-region; only non-sensitive global metadata (tenant directory, billing aggregates) in a global control plane, carefully.
  • Audit data flows: logs, traces, backups, analytics, support tools, AI features and third-party processors must also respect residency (a common gap).
  • Contractual commitments (DPAs, sub-processor lists) must match the architecture.

Encryption and keys

  • Encrypt everything in transit (TLS) and at rest (storage-level encryption is the baseline).
  • Per-tenant keys (envelope encryption with a data key per tenant, wrapped by a KMS key) enable crypto-shredding on offboarding and limit exposure of a single key.
  • Customer-managed keys (CMK/BYOK) for enterprise tenants: the tenant controls a KMS key (in their own cloud account, or an HSM) that wraps their data keys; revoking it renders their data unreadable to the provider. Requires designing for key unavailability (the tenant revokes access: fail closed for that tenant, without affecting others).
  • Field-level encryption for especially sensitive fields (national IDs, health data), so even database administrators and broad queries see ciphertext.
  • Key rotation without downtime (key IDs stored with ciphertext; Vol. 10 ch. 107).

Tenant placement and cells

At scale, tenants are placed into cells/shards (chapter 125, 127):

  • A tenant catalogue/control plane records tenant → cell/shard/region/tier.
  • Routing (edge or gateway) reads it (cached) to send requests to the right cell.
  • Placement policy balances load and size, respects residency, isolates very large tenants (dedicated cells), and spreads related risk.
  • Tenant migration between cells is a core capability: copy data (snapshot + CDC), dual-write or freeze writes briefly, switch routing, verify, clean up; used for rebalancing and tier changes.

Cost attribution

Knowing cost per tenant informs pricing, limits and placement:

  • Tag dedicated resources per tenant; for shared resources, meter usage per tenant (requests, CPU time, storage bytes, egress, queue jobs, database time) via telemetry and allocate shared costs proportionally.
  • Detect unprofitable usage patterns (a free-tier tenant consuming like an enterprise) and adjust limits or plans.
  • Show customers usage dashboards; usage-based billing needs accurate, auditable metering pipelines.

Testing isolation

Isolation bugs are catastrophic, so test explicitly:

  • Automated cross-tenant tests for every endpoint: authenticate as tenant A and attempt to read/write tenant B's resources by ID; expect 404/403 (Vol. 10 ch. 109 BOLA).
  • RLS policy tests in the database test suite; a test that runs queries without tenant context and expects zero rows or errors.
  • Static analysis/linters flagging queries without tenant predicates (custom Semgrep rules), and ORM safeguards that fail closed.
  • Cache key reviews and tests ensuring tenant prefixes.
  • Chaos/noisy-neighbour tests: generate heavy load from one tenant and verify others' SLOs hold.
  • Penetration testing focused on tenant isolation for enterprise customers' assurance.

Lab: row-level security and per-tenant limits

PostgreSQL 16 on the lab machine with a shared t_orders table and an ordinary login role tiffin_app; and a discrete-event simulation (Python, seeded) of a 4-worker service shared by two tenants. The simulation is a model, not a measurement of a real service; Volume 11's chapter 119 and Volume 9's chapter 105 show the same queueing behaviour measured for real.

Experiment 1: RLS as a safety net

SQL
set role tiffin_app; set app.tenant = 'hyd-kitchens';
select tenant_id, customer, total from t_orders order by id;   -- the buggy query, no WHERE
Situation Result
RLS off all 5 rows (both tenants)
RLS on 2 rows (hyd-kitchens only)
insert for blr-tiffins ERROR: new row violates row-level security policy
app.tenant not set 0 rows
connected as the owner, a superuser 5 rows, even after FORCE ROW LEVEL SECURITY

How the tenant gets onto the connection matters. With a connection pool, set it per transaction (set local app.tenant = … inside the request's transaction, or select set_config('app.tenant', $1, true)), so a pooled connection can't carry one request's tenant into the next. Test isolation like any other requirement: a suite that logs in as tenant X and asserts it can't read, update or delete any row of tenant Y through every endpoint. Performance note: put tenant_id first in composite indexes so the policy's predicate is cheap.

Experiment 2: the noisy neighbour (simulation)

4 workers × 20 ms = 200/s capacity; A sends 300/s (Poisson), B 20/s, for 30 simulated seconds:

Policy A served A p50 B p50 B p95 A rejected
shared pool, no limits 9,028 9,159 ms 9,061 ms 17,207 ms 0
A ≤ 2 in flight 2,524 20.0 ms 20.0 ms 21.7 ms 6,504
A ≤ 3 in flight 3,655 20.0 ms 20.0 ms 28.5 ms 5,373

Without limits the queue grew for the whole run (A alone exceeded capacity), so latencies for both tenants climbed to many seconds. Real systems combine several per-tenant controls: request-rate limits at the gateway (chapter 110 of Volume 10), concurrency caps per tenant in the service, separate queues or partitions per tenant for background work, statement timeouts per tenant role in the database, and, for the largest tenants, dedicated capacity (a "silo" tier).

Experiment 3: choosing a tenancy model

Model Isolation Cost per tenant Operations Typical use
shared tables + tenant_id + RLS logical lowest one schema to migrate many small tenants
schema per tenant stronger logical low–medium migrations × tenants hundreds of tenants
database per tenant physical (data) high fleet management, many migrations regulated or large tenants
full stack per tenant (silo) strongest highest per-tenant deploys enterprise tiers, residency

Most SaaS products end up hybrid: pooled for the long tail, siloed for the few tenants who pay for or legally need it, with tenant routing that hides the difference from the application.

Try it yourself

  1. Build the cross-tenant test suite: for each table with tenant_id, assert tenant X sees 0 of tenant Y's rows through select, update and delete.
  2. Use PgBouncer in transaction mode with set local app.tenant and show a request can't inherit a previous request's tenant.
  3. Change the simulation so limits adapt: A may use any capacity B isn't using (work-conserving fair queueing). Compare B's p95 and A's throughput.
  4. Add statement_timeout per tenant role and show one tenant's slow report can't hold connections for minutes.

Revision sheet: multi-tenancy

Key ideas

  • Two isolation requirements: data (no cross-tenant access) and performance (no noisy neighbours).
  • Models: pooled (shared tables + tenant ID), bridge (schema per tenant), silo (database or stack per tenant), hybrid tiers.
  • Tenant context: from authentication, propagated through every hop (headers, context, set local on DB connections), never from client input alone.
  • Enforcement in depth: RLS or query scoping in a data-access layer, per-tenant encryption keys where needed, tests for cross-tenant access.
  • Performance isolation: per-tenant rate limits, quotas, concurrency caps, fair queueing, separate queues, timeouts; dedicated capacity for big tenants.
  • Operations: onboarding/offboarding automation, per-tenant migrations, backups and restores per tenant, data residency, tenant-level metrics and cost attribution.

Numbers to remember

  • Lab: one missing filter exposed 3 rows of another tenant; RLS reduced it to 0 and blocked cross-tenant inserts.
  • Lab: superuser connections bypass RLS even with FORCE.
  • Simulation: a tenant at 150% of capacity pushed a small tenant's p50 to 9 s; a per-tenant cap restored 20 ms.

Pitfalls

  • Trusting a tenant ID from the request body or URL without checking it against the authenticated identity.
  • RLS with the application connected as owner or superuser.
  • Session-level tenant settings leaking across pooled connections.
  • Shared caches keyed without the tenant.
  • No per-tenant limits; one tenant's batch job harming everyone.
  • Restoring one tenant's data being impossible in a pooled model.

Glossary

  • Pooled / silo: shared resources / dedicated resources per tenant.
  • RLS: database-enforced row filtering by policy.
  • Noisy neighbour: a tenant whose usage degrades others.
  • Tenant tiering: different isolation and limits per plan.
  • Cost attribution: assigning infrastructure cost to tenants.