Skip to content

Multi-Tenant SaaS Architecture

Advanced 48 min read Part 10 of 18

Serve many customers on one platform: silo, pool and bridge models, tenant data isolation, RLS, noisy neighbours, cells, routing, residency, metering.

Summary#

A multi-tenant system serves many customers, called tenants, from one shared platform. Each tenant is typically a company, team or workspace with its own users, data, configuration and bill. Every tenant must feel like it has the product to itself:

  • it can never see another tenant's data;
  • its performance doesn't suffer because of another tenant's load;
  • it gets the features, limits and compliance guarantees it paid for.

Meanwhile the provider wants the economics of sharing: one codebase, one deploy pipeline, and infrastructure packed densely enough that a small tenant costs pennies.

The core design choice is how much to share:

  • Silo: each tenant gets dedicated resources, such as its own database or its own whole stack.
  • Pool: all tenants share the same resources, and every row is tagged with a tenant_id.
  • Bridge (hybrid): some layers are shared and others dedicated, or most tenants are pooled while big or regulated tenants get silos.

At the data layer this becomes database per tenant, schema per tenant, or shared tables with a tenant_id column, often enforced by row-level security (RLS).

Around that choice sit the problems that make multi-tenancy an advanced topic:

  • noisy neighbours, controlled by per-tenant quotas, rate limits and fair scheduling;
  • tenant-aware sharding and placement, which puts big tenants on their own shards and packs small ones together;
  • cell-based architecture, which caps the blast radius;
  • tenant routing and identity, which resolves the tenant on every request;
  • data residency, which keeps EU tenants' data in the EU;
  • onboarding, migrations and tenant moves;
  • cost attribution and metering for billing and margins;
  • metadata-driven designs, like Salesforce's, which let thousands of tenants customise schemas without DDL.

Why It Exists#

Economics. A single-tenant deployment per customer (the old "managed hosting" model) multiplies everything by the number of customers: servers, databases, upgrades, monitoring and on-call. With 10,000 customers, you can't run 10,000 copies of the stack. Even at a modest $300/month of baseline infrastructure per copy, that's $3M/month before anyone uses the product. Most SaaS tenants are small. In a typical B2B SaaS, the top 1% of tenants generate a large share of the load, while the long tail of free and small accounts barely uses anything. Pooling lets the long tail share capacity, and statistical multiplexing means peaks rarely align, so you provision for the aggregate rather than the sum of individual peaks.

Operational agility. One codebase and one deploy for everyone means every tenant gets fixes and features at once. There are no "version 3.2 for customer A, 3.7 for customer B" support nightmares. This is what makes SaaS different from shipped software.

But sharing creates three risks, and the whole architecture exists to control them:

  1. Isolation failures: a bug, a missing WHERE tenant_id = ?, or a cache key without the tenant prefix leaks one customer's data to another. That's often a company-ending incident in B2B.
  2. Interference: one tenant's bulk import, runaway integration or viral moment saturates shared databases, queues or CPU, and everyone else slows down. This is the noisy neighbour problem.
  3. Blast radius: a bad deploy, a poison-pill request or a database failure in a fully shared stack takes down all tenants at once.

Different tenants also need different things:

  • Enterprise customers ask for dedicated infrastructure, customer-managed encryption keys, data residency in their country, SSO, audit logs and custom SLAs.
  • Regulated industries need certifications that may require physical or logical separation.
  • Free-tier users need to cost nearly nothing.

A good multi-tenant architecture supports this whole range with one product and one codebase, varying only the deployment and policy per tenant.

How It Works#

Tenancy models: silo, pool and bridge#

AWS's SaaS guidance popularised three names for the sharing spectrum. They apply per layer (compute, storage, network, identity), not just to the whole system.

  • Silo model. Each tenant has dedicated resources: its own database, its own compute (separate containers, VMs or even a separate cloud account) and sometimes its own network (VPC). Isolation is structural: no query can return another tenant's rows, because those rows aren't in the database you're connected to. Noisy neighbours vanish at the siloed layer, and per-tenant cost is trivially measurable (tag the account). The downsides are cost per tenant (idle capacity everywhere), slow onboarding (provisioning infrastructure takes minutes to hours), and operational scale. Migrations, upgrades and monitoring must run across N stacks, and there are limits on how many accounts, databases or VPCs you can manage.
  • Pool model. All tenants share the same resources: one fleet of services and one database cluster, where every record carries a tenant_id. It gives the best density and cost, instant onboarding (insert a row) and one thing to operate. Isolation becomes a software property, enforced by code, policies and RLS, which raises the stakes of every bug. Noisy neighbours and blast radius must be managed explicitly, and per-tenant cost must be estimated from metering.
  • Bridge model. This is a mix. Either some layers are pooled and others siloed (shared web and API tier, but a database per tenant), or some tenants are pooled and others siloed (free and standard tiers in the pool, enterprise and regulated tenants in silos). Most mature SaaS platforms end up here. A tiered offering ("dedicated" as a premium SKU) is a bridge model sold as a product feature.
DimensionSiloPoolBridge
Data isolationStructural: separate DB, account or keysLogical: tenant_id, RLS, app checksPer layer or per tier
Noisy neighbour riskNone at the siloed layersHigh; needs quotas and fair schedulingLow for siloed tenants, managed for pooled
Cost per small tenantHigh: idle capacity per tenantVery low: penniesLow for pooled, high for siloed
Onboarding timeMinutes to hours (provision infrastructure)Milliseconds (insert rows)Depends on tier
OperationsN stacks to deploy, migrate, monitorOne stackMixed; tooling must handle both
Cost attributionExact (tagging)Estimated (metering, apportioning)Mixed
Blast radiusOne tenantAll tenants, unless cells are usedContained for siloed tenants
FitsFew large, regulated or high-paying tenantsMany small tenants, self-serve, freemiumMost real SaaS with tiers

The crucial principle: tenancy is a deployment and policy choice, not a code fork. The same code runs in pooled and siloed deployments. Tenant context flows through it identically, and only configuration decides where a tenant's data lives and which resources serve it. Teams that write different code paths for silo tenants end up with two products.

Data layer options: database per tenant, schema per tenant, shared tables#

At the storage layer, the three classic options map onto the sharing spectrum.

1. Database per tenant (silo storage). Each tenant gets its own database, or a separate cluster for the largest.

  • Pros:
    • strongest logical isolation;
    • per-tenant backup and restore ("restore tenant A to yesterday 3 p.m." is one command);
    • per-tenant encryption keys;
    • easy data residency (place the DB in the tenant's region);
    • easy tenant deletion (drop the database);
    • per-tenant schema versions during migrations;
    • clean noisy-neighbour boundaries if the databases sit on separate hardware.
  • Cons:
    • connection management (each app instance may need pools to many databases);
    • fleet-wide schema migrations across thousands of databases;
    • monitoring at scale;
    • per-database overhead (memory, catalogue, background workers);
    • cross-tenant analytics need an ETL into a warehouse.
  • Limits: practical counts depend on the engine. Thousands of small databases per Postgres or MySQL server are feasible with care. Managed services have per-instance database limits, and SQL Server and Azure SQL offer elastic pools designed for exactly this pattern.

2. Schema per tenant. One database, with a separate schema (namespace) per tenant containing identical tables, for example tenant_123.orders. The app sets search_path (Postgres) or qualifies the table names.

  • Pros: moderate isolation (no accidental cross-tenant joins unless explicitly qualified), per-tenant restore via schema-level dump, one database to operate, and cheap creation (CREATE SCHEMA plus tables).
  • Cons: catalogue bloat. 10,000 tenants × 200 tables = 2 million tables, so the system catalogue, planner, autovacuum and backups suffer badly in Postgres. Migrations still run per schema. Connection poolers in transaction mode must reset search_path safely. Most teams that try schema-per-tenant at large tenant counts later migrate away from it. It works well for tens to low thousands of tenants.

3. Shared tables with a tenant_id column (pool storage). One set of tables, where every tenant-owned table has tenant_id, every index and unique constraint leads with tenant_id, and every query filters on it.

  • Pros: maximum density, one schema to migrate, no per-tenant objects, trivial onboarding, and natural cross-tenant analytics (for the provider). It shards naturally on tenant_id.
  • Cons: isolation depends on every query being correct (hence RLS and framework-level enforcement), per-tenant restore is hard (you must extract rows), noisy neighbours share buffers and I/O, per-tenant deletion is a large DELETE, and per-tenant keys need application-level encryption.

The tenant_id column needs specific design rules:

  • Composite primary keys (tenant_id, id), or globally unique IDs plus tenant_id, so that rows from one tenant cluster together on disk and in indexes. The B-tree locality speeds up per-tenant queries.
  • Uniqueness per tenant: UNIQUE (tenant_id, email), not UNIQUE (email). Two companies can each have a user bob@gmail.com.
  • Foreign keys include tenant_id: FOREIGN KEY (tenant_id, project_id) REFERENCES projects (tenant_id, id). The database then proves that a task can't point to another tenant's project. This is a cheap, under-used safety net.
  • Partitioning: large shared tables can be list- or hash-partitioned by tenant_id, or a big tenant can get its own partition, which lets you detach and drop it.

Choosing the database model. The database model matters as much as the tenancy layout. A relational database (PostgreSQL or MySQL) is the default for SaaS. Tenants, users, projects, invoices and permissions form a web of relationships with integrity constraints, and per-tenant transactions (a single tenant's checkout or approval flow) need ACID guarantees. Relational systems also scale further than their reputation suggests, with read replicas, partitioning, pooling, caching and sharding by tenant. Facebook and Airbnb are examples of very large relational deployments (PostgreSQL in Practice). The other models fit specific needs:

  • Document databases (MongoDB, Firestore) suit tenants with highly variable, custom-shaped records. Per-tenant custom fields can be embedded as nested attributes, at the cost of more denormalisation and harder cross-document constraints.
  • Key-value stores (Redis, DynamoDB) hold sessions, feature flags, per-tenant config and rate-limit counters, keyed by tenant:{id}:.... They're often paired with a relational source of truth.
  • Wide-column stores (Cassandra, HBase) handle write-heavy per-tenant event and telemetry streams, with a partition key like (tenant_id, day) and clustering by timestamp.
  • Graph databases are rarely needed for tenancy. Permission graphs and org hierarchies are usually modelled fine in relational tables or a Zanzibar-style authorisation service (Graph Databases).

The general advice is to start relational, and add specialised stores only when an access pattern clearly demands one (Data Modeling).

Enforcing isolation: tenant context, row-level security and defence in depth#

In a pooled system, isolation is only as good as the weakest query. One forgotten filter in a reporting endpoint, an admin tool or a background job leaks data. Robust designs use several independent layers, so that a single bug isn't enough to cause a breach.

Layer 1: tenant context resolved once, carried everywhere. At the edge of the system (gateway or middleware), the request's tenant is determined from authenticated identity, never from a client-supplied parameter that isn't verified. It's then attached to a request context: thread-local or async-local storage, plus propagated headers and message metadata for downstream services and queues. Every layer reads the tenant from the context, never from the request body. Background jobs and event consumers must restore tenant context from the message envelope before doing any work.

Layer 2: data access layer that injects the filter. Repositories or ORM scopes automatically add WHERE tenant_id = :ctx_tenant. Examples include Hibernate filters and Rails default scopes, or better, explicit tenant-scoped repository APIs. Raw SQL must go through a reviewed helper. Lint rules or static analysis can flag queries on tenant tables without a tenant predicate.

Layer 3: row-level security in the database. PostgreSQL's row-level security lets the database itself enforce the filter. You enable RLS on a table and define a policy with a USING expression (which rows can be seen, updated or deleted) and a WITH CHECK expression (which rows can be inserted or updated into). The tenant is passed as a session or transaction setting:

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY;   -- apply even to the table owner
 
CREATE POLICY tenant_isolation ON orders
  USING      (tenant_id = current_setting('app.tenant_id')::uuid)
  WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);
 
-- Per request, inside the transaction (safe with transaction-mode poolers):
BEGIN;
SET LOCAL app.tenant_id = '7f3c9e2a-0b1d-4c5e-9f00-1a2b3c4d5e6f';
SELECT * FROM orders WHERE status = 'open';    -- RLS adds the tenant predicate
COMMIT;

Important details:

  • Who bypasses RLS: superusers and roles with BYPASSRLS always do. Table owners bypass it unless you use FORCE ROW LEVEL SECURITY. The application should connect as a non-owner role without BYPASSRLS, and migrations should run as a separate owner role.
  • Use SET LOCAL (transaction-scoped) rather than SET (session-scoped) when using a pooler like PgBouncer in transaction mode. Otherwise the setting can leak to the next client that reuses the connection, the exact cross-tenant bug RLS was meant to prevent.
  • If the setting is missing, current_setting('app.tenant_id') raises an error, which fails closed. The two-argument form with missing_ok returns NULL, and the comparison then matches nothing. Once a custom setting has been used on a connection, it can linger as an empty string, and casting '' to uuid also raises an error. All of these fail closed. Choose deliberately, and test the no-context path.
  • Performance: the policy predicate is added to every query, so indexes must lead with tenant_id. Keep policy expressions simple, avoiding subqueries per row. A STABLE setting lookup is cheap.
  • Views and functions: views run with the owner's privileges by default and can bypass RLS. Postgres 15+ supports security_invoker views. SECURITY DEFINER functions need care.
  • Other engines: SQL Server has row-level security with security predicates, and Oracle has Virtual Private Database (VPD). MySQL has no native RLS, so you use views plus definer rules, or enforce in the app or proxy. Distributed SQL engines vary.

Layer 4: tenant-scoped credentials and keys.

  • Storage: object paths are prefixed by tenant (s3://bucket/tenants/{id}/...) and paired with IAM policies scoped to that prefix. Short-lived per-tenant credentials are minted by a token vending service, so even buggy code holding tenant A's credentials can't read tenant B's objects. This is the AWS "dynamic policy generation" pattern.
  • Encryption: use per-tenant data keys (envelope encryption), with customer-managed keys (BYOK or HYOK) for enterprise tiers. Revoking a tenant's key makes its data unreadable everywhere, including backups, which is crypto-shredding at offboarding (Data Lifecycle, Tiering and Retention).

Layer 5: every cache, index and queue is tenant-aware.

  • Cache keys include the tenant: t:{tenant}:user:{id}.
  • Search indexes either filter on tenant (a mandatory filter clause) or use per-tenant indexes or aliases for big tenants.
  • Message topics carry tenant metadata.
  • Logs and traces carry tenant_id, both for debugging and for metering. Logs must never contain another tenant's data in shared admin views.
  • Leaks often happen in exactly these "side" systems, because the database had RLS but the cache key didn't.

Layer 6: testing and monitoring for isolation.

  • Automated cross-tenant tests: create two tenants, then try every API as tenant A on tenant B's resource IDs and expect 404s, not 403s (a 403 leaks existence).
  • Fuzzing ID parameters.
  • Canary rows: a sentinel record per tenant that must never appear in another tenant's responses, monitored in production.
  • Periodic audits of queries lacking tenant predicates.
  • Audit logs of admin and support access to tenant data.

Noisy neighbours: quotas, rate limits and fair scheduling#

In a pool, tenants share finite resources: CPU, DB connections, IOPS, buffer cache, queue throughput, third-party API quotas. A noisy neighbour is a tenant whose usage degrades others. Examples:

  • a 10-million-row CSV import;
  • a misbehaving integration retrying in a tight loop;
  • a dashboard with an unindexed filter scanning a huge table;
  • a marketing campaign that multiplies traffic 50×.

The controls form a layered toolbox.

1. Per-tenant rate limits at the edge and gateway. Use token buckets keyed by tenant (and by user or API key within the tenant), sized by plan tier. For example, the free tier gets 10 requests/s with a burst of 20, and enterprise gets 1,000 requests/s with a burst of 2,000. Exceeding the limit returns 429 with Retry-After (Rate Limiting and Throttling). Stripe has described layering several limiters:

  • a request rate limiter (requests per second per user);
  • a concurrent request limiter (in-flight requests per user, which protects against expensive endpoints);
  • load shedders that drop low-priority traffic when the fleet is under stress.

2. Quotas on resources and objects. Caps on storage GB, number of users, projects, API calls per month, file sizes, rows per import, webhooks per second. Hard quotas reject. Soft quotas alert and bill overage. Quotas protect the platform and define plan tiers.

3. Concurrency and work isolation in shared workers. Background job systems are where noisy neighbours hurt most. One tenant enqueuing 1 million jobs starves everyone behind it in a FIFO queue. Fixes:

  • per-tenant queues (or partitions) with a fair scheduler across them: round-robin, deficit round-robin or weighted fair queuing by tier;
  • per-tenant concurrency caps (at most N workers busy for tenant X at once);
  • priority lanes (interactive vs bulk);
  • separate pools for the largest tenants.

4. Database protection.

  • Statement timeouts per role or tier.
  • Per-tenant connection limits at the pooler.
  • Query cost limits: reject or queue queries whose estimated cost exceeds a threshold.
  • Read replicas for heavy reporting.
  • Moving heavy analytics off the OLTP database entirely. Store raw events in a write-optimised store, pre-aggregate in batches or streams into an analytics store, and serve per-tenant dashboards from there. Tenant reports then never scan OLTP tables. For example, 10k events/s batched every 5 minutes is about 3 million events, or about 300 MB per batch. That's small enough for one machine, though Spark or Flink gives a path to scale (Data Pipelines, Warehouses and Lakes).

5. Admission control and load shedding. When shared capacity is saturated, shed load fairly. Reject the tenants that exceed their fair share first, and protect interactive traffic over bulk. Shared platforms in front of a common store often use per-use-case or per-tenant bounded queues: when a tenant's queue fills, only that tenant gets back-pressure (Resilience Patterns: Timeouts, Retries and Circuit Breakers).

6. Placement and isolation by tier. Move persistently heavy tenants to their own shard, cell or silo. This is the most reliable fix, and it's discussed next.

7. Shuffle sharding. Give each tenant a random subset of workers, so that two tenants rarely share the same subset. A poison-pill tenant that crashes its workers only takes down tenants whose shard fully overlaps its own. For example, take 8 workers and assign each tenant 2: there are C(8,2) = 28 distinct pairs. A tenant that crashes its 2 workers fully affects only the tenants assigned the same pair, about 1/28 of tenants. Everyone else keeps at least 1 healthy worker. With 100 workers and shards of 5, C(100,5) is about 75 million combinations, so full overlap is vanishingly rare. AWS has described using shuffle sharding in services including Route 53, in the Amazon Builders' Library article "Workload isolation using shuffle-sharding".

Tenant-aware sharding and placement#

A pooled database eventually outgrows one machine. Sharding by tenant_id is the natural choice for B2B SaaS (Partitioning and Sharding):

  • almost all queries are single-tenant, so they hit one shard;
  • per-tenant transactions stay local, with no distributed transactions;
  • tenant moves become the unit of rebalancing.

The risk is skew: tenant sizes follow a power law. One tenant can be 1,000× the median, and outgrow a shard by itself.

Placement strategies:

  • Hash placement: shard = hash(tenant_id) mod N, or consistent hashing (Consistent Hashing). It's simple and spreads tenants evenly by count, not by load. Large tenants collide unpredictably, and rebalancing means moving tenants when N changes.
  • Directory (lookup) placement: a tenant catalogue maps tenant_id → shard (and cell, region, tier). It allows deliberate placement: put big tenants on less-loaded shards, put a regulated tenant in its region, isolate a whale on dedicated hardware. Moving a tenant is just copying its data and updating the catalogue entry. Most large SaaS platforms use this, at the cost of a catalogue that must be highly available and cached.
  • Bin packing: treat placement as a multi-dimensional bin-packing problem (storage, QPS, CPU and growth rate per tenant) and place new tenants on the shard with the most headroom. Periodically rebalance by moving the tenants whose move yields the most balance per byte copied.
  • Logical shards on physical hosts: create many more logical shards than machines, for example 4,096 logical shards on 32 hosts. Tenants map to logical shards, and logical shards map to hosts. Rebalancing moves whole logical shards between hosts without touching the tenant mapping. Notion's 2021 sharding of Postgres used this idea: 480 logical shards (as schemas) across 32 physical databases. Logical shards also bound per-shard size for faster restores and migrations.
  • Whale handling: a tenant that outgrows a shard needs either a dedicated cluster (bridge or silo), or sub-sharding inside the tenant by a secondary key, such as (tenant_id, project_id) or (tenant_id, channel_id). Slack is an example. It originally sharded MySQL by workspace, then moved to Vitess, and resharded heavy tables by other keys such as channel, because the largest workspaces outgrew single shards.

Managed distributed databases make this easier. Citus (a Postgres extension) distributes tables by tenant_id. It co-locates all tables with the same distribution key on the same node, so joins and transactions within a tenant stay local. It supports reference tables (small shared tables replicated to all nodes) and can isolate a large tenant to its own shard. Vitess (MySQL) shards by keyspace ID with vindexes and supports online resharding. DynamoDB, Cassandra and MongoDB shard automatically by partition key. Use a tenant_id prefix in the partition key, and add a suffix (such as tenant_id#bucket) for large tenants to avoid hot partitions (Amazon DynamoDB in Practice). The mechanics differ: Cassandra uses token ranges with virtual nodes, DynamoDB splits partitions internally as they grow, and MongoDB uses range-based chunks moved by a balancer. All of them route queries for you, so in an interview it's enough to say "DynamoDB with tenant_id in the partition key" or "Citus distributed on tenant_id, with whales isolated to dedicated shards".

Cell-based architecture for tenants#

Sharding the database isn't enough if everything above it is shared. One bad deploy or one poison request can still take out the whole service. A cell-based architecture splits the entire stack (load balancers, services, caches, queues, databases) into many independent, identical cells. Each serves a subset of tenants, and they share nothing (Designing for High Availability). A thin cell router maps each request's tenant to its cell.

Why cells suit multi-tenant SaaS especially well:

  • Blast radius ≈ 1 / number of cells. With 20 cells, a failure hits at most about 5% of tenants.
  • Deploy waves. Roll out to a canary cell (internal tenants), then 1 cell, then 10%, then the rest, watching per-cell SLOs. A bad change is caught while affecting few tenants.
  • Bounded size. Each cell has a maximum capacity (tenants, QPS, data) that's been load-tested. You never operate a system bigger than anything you've tested, and you scale by adding cells, not by making cells bigger.
  • Natural fit for tiers and residency. Dedicated cells for enterprise tenants (bridge model) and per-region cells for data residency.
  • Noisy neighbours are contained to one cell, and whales can be moved into cells of their own.

Costs:

  • Duplicated infrastructure: each cell has fixed overhead, so cells shouldn't be too small.
  • Cross-cell features: global search, cross-tenant sharing, and the platform admin's global views need aggregation layers.
  • The router and catalogue become critical, and must be extremely simple and highly available. Cache the mapping at the edge, and make it static-stable: if the catalogue is down, keep using the last-known mapping.
  • Tenant migration between cells must be a well-oiled operation.

Choose the cell size by balancing per-cell overhead against blast radius. Common practice is to size cells so that the largest expected tenant fits comfortably, and to keep the cell count high enough that a single cell is a small percentage of the business.

Tenant routing and identity#

Every request must answer "which tenant is this?" reliably, early, and in a way the client can't forge.

Where the tenant comes from:

  • Subdomain: acme.app.example.com. This is friendly, works with cookies scoped per tenant, and allows per-tenant TLS (wildcard certificates or automated issuance for custom domains).
  • Custom domain: app.acme.com maps via CNAME, and a domain → tenant mapping is resolved at the edge.
  • Path: /t/acme/.... This is simple but easy to get wrong with relative links and caching.
  • Token claim: the access token (JWT) carries tenant_id (and roles within it) after login. This is the authoritative source. Subdomain and path are hints that must match the token's tenant, or the request is rejected.
  • API keys map to a tenant in the key store, and machine clients use per-tenant OAuth client credentials.

Identity across tenants. Users often belong to multiple tenants: a consultant in five client workspaces. Model the user (global identity: login, MFA, email) separately from the membership (user × tenant × roles). Login authenticates the user. Then the user selects a tenant (or the subdomain implies it), and the token is minted for that membership. Switching tenants mints a new token. Never let one token carry broad multi-tenant access by default.

Enterprise SSO. Each enterprise tenant configures its own identity provider via SAML 2.0 or OpenID Connect (Okta, Entra ID, Google Workspace) (Authentication and Authorization). This brings several mechanisms:

  • Home realm discovery routes a user to the right IdP, typically by email domain (verified via DNS TXT records, so a tenant can't claim someone else's domain) or by subdomain.
  • SCIM (System for Cross-domain Identity Management) lets the tenant's IdP provision and deprovision users automatically. When someone leaves the customer company, they lose access within minutes.
  • Tenant-scoped roles (RBAC within the tenant) and tenant admins who manage their own users.

Routing flow. The gateway authenticates the token, extracts tenant_id, looks up the tenant in the catalogue (cached locally with a TTL), and forwards to the right cell or shard with the tenant context in headers. Internal services trust the tenant header only from authenticated internal callers, such as service-mesh mTLS identities. Async messages carry the tenant in the envelope, and consumers reject messages without one.

Data residency#

Data residency means a tenant's data is stored, and often processed, only in specified jurisdictions: EU data in the EU, Australian government data in Australia. It's driven by:

  • law: GDPR restrictions on transfers outside the EEA (the 2020 Schrems II ruling invalidated the EU–US Privacy Shield, and the EU–US Data Privacy Framework followed in 2023); sector rules; and localisation laws in some countries, such as Russia's personal-data localisation law, China's PIPL with its cross-border transfer rules, and India's DPDP Act of 2023 with its transfer provisions;
  • contracts: enterprise customers demand it;
  • public-sector procurement.

Architecturally, residency turns multi-tenancy into multi-region tenancy:

  • Regional cells or stacks. Tenants are pinned to a home region at signup (chosen by the customer, or derived from the billing country). The catalogue stores tenant → region, and all their primary data, backups, search indexes, logs and caches live there (Multi-Region and Global Data).
  • The global control plane is minimal. Some things are inherently global: login discovery ("which region is this email's tenant in?"), billing and the tenant catalogue. Keep the global layer to routing metadata with no customer content, or replicate it per region.
  • Watch the side channels. Telemetry, logs, error reports (Sentry-type tools), support tooling, analytics pipelines, ML training sets and third-party sub-processors all copy data. Residency failures usually happen there, not in the primary database. Scrub PII from telemetry, or keep regional telemetry pipelines.
  • Processing location matters too. An EU tenant's data processed by a US-hosted LLM or job runner may violate the commitment. Route processing jobs to the tenant's region.
  • Moving a tenant between regions is a tenant migration with legal sign-off. It uses the same copy, CDC and cutover machinery as a shard move.
  • Encryption with regional keys, using KMS keys in the tenant's region and optionally customer-managed keys. This adds a technical control: data copied elsewhere is unreadable without keys that never leave the region.

Onboarding, tenant lifecycle and migrations#

Onboarding (provisioning) should be an automated, idempotent workflow driven by a tenant management service, not a runbook:

  1. Create the tenant record (ID, plan, region, tier, status provisioning) in the catalogue.
  2. Pool tier: insert rows (default settings, admin user) into the pooled shard chosen by placement. This takes milliseconds.
  3. Silo or bridge tier: run infrastructure as code (Terraform, CloudFormation or Pulumi) to create the dedicated database, schema, cell or account. This takes minutes. Then run migrations to the current schema version, seed the data, and register the routing.
  4. Configure identity: the tenant admin, an SSO connection if enterprise, SCIM tokens.
  5. Set quotas and limits from the plan, and start metering.
  6. Mark the tenant active. Emit a TenantCreated event so that billing, analytics, CRM and support tools react.

Because provisioning spans many systems, model it as a saga with compensations, or as a durable workflow (Temporal, Step Functions) that retries each step idempotently (Pattern: Multi-Step Processes and Workflows). Pre-provision warm pools of silo resources if onboarding latency matters for paid tiers.

Lifecycle states: provisioning → active → (suspended for non-payment or abuse) → (scheduled for deletion) → deleted. Each state is enforced by the router and services. A suspended tenant gets read-only access or a payment page. Offboarding includes:

  • data export (customers expect a full export);
  • a grace period;
  • deletion across all stores, or crypto-shredding of the tenant key;
  • deletion certificates for enterprise contracts.

Schema migrations across tenants. With shared tables, a migration runs once, but it touches every tenant's rows. Use expand–contract (add the column, backfill in batches, switch the code, drop the old column) to stay online (Online Data Migrations and Schema Evolution). With database- or schema-per-tenant, a migration is a fleet operation across thousands of databases:

  • run it in waves (canary tenants first);
  • make the code tolerate both schema versions during the rollout;
  • track each tenant's schema version in the catalogue;
  • make each migration idempotent and resumable;
  • alert on stragglers.

A single failing tenant mustn't block the fleet. Quarantine it and continue.

Tenant moves (shard to shard, cell to cell, pool to silo, region to region) are the core rebalancing operation:

The write freeze affects only the moving tenant, typically for seconds. The catalogue update is the atomic switch. Caches keyed by tenant must be invalidated, and in-flight requests that hit the old location must fail with a retryable error, not write to the old shard. Shopify's open-source Ghostferry tool was built for this kind of move: it copies a shop's MySQL data between database pods using binlog tailing, with a short cutover.

Cost attribution and metering#

In a pool, the cloud bill arrives for the whole platform. To know gross margin per tenant, price plans sensibly, catch abusive tenants and bill usage-based plans, you must meter each tenant's consumption and attribute shared costs.

Metering records usage events as they happen:

  • API calls by endpoint class;
  • storage GB-hours;
  • compute seconds or job minutes;
  • messages sent, seats, active users;
  • bytes egressed;
  • AI tokens consumed.

The pipeline:

Design rules for metering:

  • Events are idempotent. Each event carries a unique ID, and the aggregator deduplicates it. Billing errors destroy trust, so this must be exact (Idempotency and Safe Retries).
  • Separate the fast path from the accurate path. Quota enforcement needs near-real-time approximate counters (Redis, in-memory with periodic flush). Billing needs exact, auditable totals computed from the durable log and reconciled.
  • Rollups are immutable once the period closes. Late events go into adjustments, not rewrites.
  • Meter at the right layer. Measure where the cost is incurred (DB time, storage, egress), not just request counts. A tenant making few but heavy requests can cost more than a chatty one.

Cost attribution maps the cloud bill to tenants:

  • Siloed resources: exact allocation, using resource tags (tenant=acme), separate accounts or projects, and Kubernetes namespaces with OpenCost or Kubecost.
  • Pooled resources: apportion each shared cost pool by the tenant's share of the driver metric that best explains it. Database cost goes by DB CPU-seconds or storage. Search cost goes by index size and query count. Egress cost goes by bytes egressed.
  • Unallocatable overhead (the control plane, idle headroom) is spread proportionally, or shown as a platform cost line.

The result is showback (reporting cost per tenant) or chargeback (internal billing). These analyses usually show that a handful of tenants, or a handful of features, are unprofitable at their plan price. That evidence drives pricing changes, quotas or moves to dedicated tiers.

Salesforce-style metadata-driven multi-tenancy#

Salesforce runs a huge number of customer organisations on shared database instances, and lets each customer add custom objects and fields, validation rules, workflows and code, without any per-tenant DDL. The design is described in "The Design of the Force.com Multitenant Internet Application Development Platform" (Weissman and Bobrowski, SIGMOD 2009) and in Salesforce's multitenant architecture whitepapers.

The key idea is that the schema is data. Instead of creating real tables per customer object, a few large shared tables store everything:

  • Objects metadata: one row per custom object per org, holding its name, org ID and object ID.
  • Fields metadata: one row per custom field, holding its data type, which flex column slot it maps to, and validation rules.
  • Data table: one huge table holding the records of all custom objects of all orgs. Each row has GUID, org ID, object ID, name, and a few hundred generic flex columns (Value0 … ValueN) stored as variable-length strings. Field "Amount" of object "Invoice" for org 123 might live in Value7, while for org 456 Value7 holds an unrelated text field. The fields metadata tells the runtime how to interpret and cast each slot.
  • Pivot and index tables: because the flex columns hold mixed types as strings, normal indexes don't work. Salesforce maintains typed index tables that copy indexed field values into strongly typed columns (string, number, date) with real database indexes, plus tables for unique fields and for relationships (foreign keys between custom objects).
  • Every table is partitioned and keyed by org ID, so each query touches only one tenant's slice. The org ID is the first predicate of every generated query.

The runtime compiles each tenant's query (in SOQL, Salesforce's query language) into SQL over these generic tables. It uses metadata to map field names to flex columns, joins index tables for selective filters, and applies tenant-specific optimiser statistics, because one org's data distribution is nothing like another's. Metadata is aggressively cached, since every request reads it.

Results:

  • Instant schema changes per tenant. Adding a field is a metadata insert, with no table rewrite and no lock.
  • One physical schema to upgrade. Salesforce can upgrade all customers at once, with three major releases a year.
  • Extreme density.

Costs:

  • A huge engineering investment in the query compiler, index maintenance and statistics.
  • Storage overhead, because values are stored as strings and copied again into index tables.
  • Governor limits: strict per-tenant execution limits on queries, CPU and records per transaction. These are the platform's noisy-neighbour defence.

Most SaaS products don't need full metadata-driven schemas. Lighter variants handle per-tenant custom fields:

  • a JSONB column with GIN or expression indexes in Postgres;
  • an EAV (entity–attribute–value) table, which is flexible but slow to query;
  • a document store for custom records;
  • the Salesforce-style flex-column-plus-index-table pattern, when you truly need thousands of tenants to define their own objects at scale.

When to Use It#

Design for multi-tenancy explicitly when:

  • You sell one product to many organisations (B2B SaaS, platforms, marketplaces with seller workspaces, developer platforms) and want one codebase and one deploy.
  • Most tenants are small. Pooling is the only way the long tail is profitable. A typical signal is hundreds or more tenants with power-law usage.
  • Enterprise customers need guarantees (isolation, residency, dedicated capacity, customer-managed keys) that you want to sell as tiers, rather than fork the product for.
  • You run an internal platform (shared Kafka, databases, a CI service, an ML platform) used by many internal teams. The same problems appear: noisy neighbours, quotas, chargeback, isolation between teams.

Pick something else instead when:

  • You have a handful of very large customers with strict compliance, each paying enough for dedicated stacks. A single-tenant-per-customer deployment (still automated, from the same code) is simpler to reason about and sell. It's a fully siloed variant of the same architecture.
  • It's a consumer app where users don't form organisations. Ordinary per-user data ownership and authorisation are enough. You still shard by user, but tenancy machinery such as org-level quotas, SSO and residency is overkill.
  • The product is on-premises software installed by customers. Tenancy is their problem, not yours.

When NOT to Use It#

  • Don't start with database-per-tenant for a self-serve freemium product. You'll drown in thousands of nearly empty databases and fleet migrations. Start pooled and add silos for paying tiers.
  • Don't start with schema-per-tenant on Postgres if you expect tens of thousands of tenants. Catalogue bloat and migration fan-out will hurt.
  • Don't build Salesforce-style metadata schemas unless tenant-defined objects are the product. JSONB custom fields cover most needs.
  • Don't build cells on day one for a small product. Do design the tenant catalogue and tenant-scoped data model so that you can add cells later without a rewrite.
  • Don't rely on a single isolation layer, whether app filters only or RLS only, for sensitive data.

How to Implement It#

  1. Define the tenant model. Decide what a tenant is (company, workspace, project), the user ↔ tenant membership model, and the tiers (free, standard, enterprise, dedicated) with their isolation, residency and SLA promises.
  2. Make tenant_id first-class everywhere. It goes on every tenant-owned table, leading every index and unique key, included in foreign keys, in every cache key, object path, message envelope, log line and trace attribute.
  3. Resolve tenant context at the edge from authenticated identity (token claim, verified against the subdomain or custom domain). Propagate it through request context, internal headers trusted only over mTLS, and message metadata.
  4. Enforce isolation in depth:
    • a tenant-scoped data access layer;
    • RLS with SET LOCAL per transaction and a non-owner app role;
    • prefix-scoped storage credentials;
    • per-tenant encryption keys for higher tiers;
    • automated cross-tenant tests.
  5. Build the tenant catalogue, mapping tenant → tier, region, cell and shard, plus status and quotas. Make it highly available, and cache it in every router with static stability.
  6. Choose the storage layout per tier: pooled shared tables for most tenants, and a dedicated DB or cluster for enterprise or residency tenants. Shard pools by tenant using Citus, Vitess or a managed NoSQL partition key.
  7. Add noisy-neighbour controls:
    • per-tenant rate limits and concurrency limits by tier;
    • per-tenant queues with fair scheduling for background work;
    • statement timeouts;
    • separate analytics paths;
    • shuffle sharding for shared worker fleets.
  8. Automate the lifecycle: provisioning as a durable workflow, suspension, export, deletion or crypto-shredding, fleet migrations in waves, and tenant moves with copy, CDC, verification and cutover.
  9. Meter usage with idempotent events into a durable log, then aggregate into per-tenant rollups. Use them for quotas, billing and cost attribution, and tag siloed resources.
  10. Observe per tenant: SLOs and dashboards broken down by tenant and cell (top-N tenants by load and errors), alerting when one tenant drives a resource beyond its share (Observability: Logs, Metrics and Traces).
  11. Introduce cells when the blast radius or the size of the shared stack becomes the dominant risk. Route by tenant, deploy in waves, and cap the cell size.

A tenant-aware request pipeline in TypeScript-style pseudo-code, covering context, the rate limit, the routing lookup and the RLS-scoped transaction:

async function handle(req: Request): Promise<Response> {
  const claims = await verifyToken(req.headers.get("authorization"));       // 401 if invalid
  const tenantId = claims.tenant_id;
  if (hostTenant(req.headers.get("host")) !== tenantId) return status(403);  // subdomain must match token
 
  const tenant = await catalogue.get(tenantId);           // cached: tier, cell, shard, region, status
  if (tenant.status === "suspended") return status(402);
  if (!(await limiter.take(`t:${tenantId}`, tenant.tier.rps, tenant.tier.burst)))
    return status(429, { "Retry-After": "1" });
 
  return withTenantContext({ tenantId, userId: claims.sub, roles: claims.roles }, async () => {
    const db = pools.forShard(tenant.shard);              // per-shard pool, app role without BYPASSRLS
    return db.transaction(async (tx) => {
      await tx.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]); // true = SET LOCAL
      const rows = await tx.query("SELECT id, total FROM invoices WHERE status = $1", ["open"]);
      meter.emit({ tenantId, metric: "api.read", qty: 1, id: req.headers.get("x-request-id") });
      return json(rows);
    });
  });
}

set_config(name, value, true) is the function form of SET LOCAL, so parameter binding works. The setting disappears at commit, and the next borrower of the pooled connection starts clean.

TechnologyFits when
PostgreSQL RLS; SQL Server RLS; Oracle VPDDatabase-enforced isolation for pooled tables
Citus (Postgres)Distributing pooled tables by tenant_id with co-location, reference tables, tenant isolation to own shard
Vitess (MySQL)Large MySQL fleets sharded by tenant, with online resharding
DynamoDB, Cassandra, MongoDBNoSQL pools with tenant-prefixed partition keys; per-tenant sub-partitioning for whales
Azure SQL elastic pools; Aurora; Cloud SQLMany small per-tenant databases sharing pooled capacity
Envoy or API gateways (Kong, Apigee, AWS API Gateway usage plans)Per-tenant rate limits, API keys and quotas at the edge
Okta, Entra ID, Auth0, Keycloak, WorkOSPer-tenant SSO (SAML or OIDC), SCIM provisioning, organisation membership
Temporal, AWS Step FunctionsDurable provisioning, migration and offboarding workflows
Terraform, Pulumi, CrossplaneProvisioning silo resources per tenant as code
AWS KMS, Cloud KMS, Key Vault, VaultPer-tenant keys, customer-managed keys, crypto-shredding
Kafka + Flink, or Metronome, Orb, Stripe BillingUsage metering pipelines and usage-based billing
OpenCost, Kubecost, cloud cost tagsCost attribution for siloed and namespaced resources

Trade-offs#

OptionProsConsPick when
Shared tables + tenant_id + RLSCheapest, simplest ops, instant onboarding, easy shard-by-tenantIsolation is software-enforced; per-tenant restore and deletion are hard; noisy neighboursMany small tenants, self-serve SaaS
Schema per tenantModerate isolation; per-tenant dump and restoreCatalogue bloat at scale; migrations fan outTens to low thousands of tenants on one cluster
Database per tenantStrong isolation; per-tenant backup, keys, residency, deletionConnection and migration fan-out; per-DB overhead; cross-tenant analytics need ETLEnterprise, regulated or large tenants; bridge tier
Full silo stack per tenantMaximum isolation; dedicated capacity; exact costHighest cost and ops burden; slow onboardingFew high-value or regulated tenants, "dedicated" SKU
Hash placementSimple, no catalogueSkew from whales; rebalancing moves many tenantsEarly stage, uniform tenants
Catalogue-based placementDeliberate placement; easy moves; tiers and residencyCatalogue is critical infrastructureMost production SaaS
CellsBounded blast radius; deploy waves; tested size limitsDuplicated overhead; cross-cell features harderLarge SaaS where one outage hitting all tenants is unacceptable
Metadata-driven schema (Salesforce-style)Per-tenant custom objects without DDL; one physical schemaVery complex query compiler and indexing; storage overheadPlatforms where tenant-defined data models are the product

Common Pitfalls#

  • A missing tenant filter in one query, report, export or admin tool. Use RLS plus a scoped data access layer plus tests.
  • Session-level SET with a transaction pooler leaks tenant context across requests. Use SET LOCAL or set_config(..., true).
  • App connects as the table owner, or as a BYPASSRLS role. RLS silently doesn't apply.
  • Global unique constraints (UNIQUE(email)) block legitimate users across tenants. Scope them by tenant.
  • Cache keys, search queries or object paths without the tenant. The DB is isolated, but the side systems leak.
  • Trusting a tenant ID from the URL or body without checking it against the authenticated token.
  • FIFO job queues shared by all tenants. One bulk import stalls everyone. Use per-tenant queues and fair scheduling.
  • No whale plan. The biggest tenant outgrows its shard at the worst time. Monitor per-tenant growth, and pre-plan dedicated shards and sub-sharding.
  • Schema-per-tenant at 50,000 tenants. Catalogue bloat, slow migrations and painful backups follow.
  • Residency broken by logs, telemetry, support tools or AI processing that ship data to another region.
  • Metering without idempotency causes double billing on retries, or lost usage on failures.
  • Offboarding without deletion everywhere: backups, search, warehouse, third parties.
  • Code forks for silo tenants. The same code must run in every tier, with only configuration differing.

Real-World Examples#

  • Salesforce runs many customer orgs per shared instance (called pods or instances). It uses a metadata-driven schema with flex columns, typed index tables and org-ID partitioning, plus governor limits that cap each tenant's per-transaction resource use (Weissman and Bobrowski, SIGMOD 2009). Its platform upgrades all tenants together in three major releases a year.
  • Shopify splits its platform into pods: isolated sets of datastores (MySQL plus supporting stores) that each serve a subset of shops, with shared stateless application tiers routing by shop. Shops are moved between pods with Shopify's open-source Ghostferry, which copies data using MySQL binlog tailing and a brief per-shop cutover. Pods are a cell-like structure that bounds blast radius.
  • Slack sharded MySQL by workspace. As enterprise workspaces grew, it migrated to Vitess and resharded some tables on other keys, so that the largest customers didn't overload single shards.
  • Notion sharded its Postgres in 2021 into 480 logical shards across 32 physical databases, keyed by workspace ID. Logical shards allowed later rebalancing onto more hosts without changing the tenant-to-shard mapping.
  • AWS publishes SaaS guidance (the SaaS Lens of the Well-Architected Framework, and SaaS Factory material) describing silo, pool and bridge models, tenant isolation via dynamically scoped IAM policies, and tiered deployment. AWS also describes cell-based architecture and shuffle sharding as core isolation techniques for its own services.
  • Stripe has written about layering per-user request-rate limiters, concurrency limiters and fleet-level load shedders, so one customer's traffic can't degrade the API for others.
  • Citus documents multi-tenant SaaS as a primary use case: distribute tables by tenant_id, co-locate them, replicate small shared tables, and isolate large tenants onto dedicated shards.

Case studies that use this pattern#

In the Interview#

Common follow-ups:

  • "One tenant is 100× bigger than the rest. What do you do?" Move it to a dedicated shard or cell through the catalogue, using copy, CDC and a per-tenant cutover. If it still doesn't fit, sub-shard within the tenant by a secondary key, and give it its own rate limits and worker pool.
  • "How do you guarantee tenant A can never read tenant B's data?" Defence in depth: tenant from a verified token; a data layer that injects the filter; Postgres RLS with SET LOCAL and a non-owner role; tenant-prefixed cache keys and object paths with scoped credentials; per-tenant encryption keys; and automated cross-tenant tests and canaries.
  • "How do you run a schema migration with 5,000 tenant databases?" In waves: canary tenants first, code compatible with both versions, the version tracked per tenant in the catalogue, idempotent and resumable migrations, stragglers quarantined, expand–contract for breaking changes.
  • "How do you bill for usage?" Services emit idempotent usage events to Kafka. A stream job aggregates them per tenant per hour into immutable rollups that feed billing, quotas and cost allocation. Fast approximate counters handle enforcement, and exact totals come from the log.
  • "An EU customer requires residency. What changes?" Pin the tenant to an EU cell: primary data, backups, search, logs and processing jobs all run in the EU, under EU KMS keys. The global layer holds only routing metadata. Audit telemetry and sub-processors for leaks.
Deep Dive: RLS Internals, Query Plans and Connection Math for Tenant IsolationShow

How PostgreSQL applies RLS. When a query touches a table with RLS enabled, the planner adds the policy expressions as extra quals. Permissive policies are combined with OR, and restrictive policies with AND. These quals are marked as security barrier quals. The planner must not push user-supplied functions below them in ways that could leak rows. Otherwise, a crafted function in the WHERE clause could be evaluated on rows that the policy would hide, and smuggle out their values through errors or side effects. Only functions marked LEAKPROOF (which can't reveal their arguments) can be evaluated before the security quals. Most built-in comparison operators on standard types are leakproof, so normal tenant_id = … filters and index scans work as expected. A predicate using a non-leakproof function, though, can stop the planner from using an index in the order you expect. The lesson: keep tenant policies as simple equality on an indexed column, and check EXPLAIN for tenant-scoped queries under the application role, not as a superuser (which bypasses RLS and shows a different plan).

Plan caching and tenant skew. Prepared statements in Postgres switch from custom plans to a generic plan after five executions, if the generic plan's estimated cost isn't much worse. In a pooled table where tenant sizes differ by 1,000×, a generic plan chosen for a typical small tenant (an index scan) may be terrible for a whale, where a sequential scan or a different join order would win, or the reverse. Mitigations:

  • plan_cache_mode = force_custom_plan for skew-sensitive queries;
  • partitioning large tenants into their own partitions, so that per-partition statistics apply;
  • moving whales to dedicated shards, where statistics are tenant-specific by construction.

This is the same problem Salesforce solved with tenant-specific optimiser statistics in its query compiler. One org's "small" table is another org's "huge" table, and a shared plan can't serve both.

Index design for pooled tables. Every index should lead with tenant_id: (tenant_id, created_at) and (tenant_id, status, created_at), not (created_at). The tenant predicate then becomes an index range, and per-tenant queries read only that tenant's slice. Clustering a table by tenant_id (periodically with CLUSTER or pg_repack, or naturally via a composite primary key in InnoDB, which clusters by primary key) improves locality. A tenant's rows then share pages, which raises the buffer-cache hit ratio for active tenants and reduces the I/O a noisy neighbour can impose on others.

Connection math for database per tenant. Suppose 200 app instances each keep a pool of 5 connections per tenant database, across 2,000 tenant databases on 20 servers. That's 200 × 5 × 2,000 = 2 million potential connections, or 100,000 per server. Postgres uses a process per connection (several MB each), so this is impossible. Workable designs:

  • Route by tenant to a subset of app instances. Use cells or consistent-hash routing, so each instance talks to a bounded set of tenant DBs.
  • Run a pooler per DB server (PgBouncer in transaction mode) and multiplex many app connections onto a few server connections per database. Size the pool from Little's law: needed connections ≈ query rate × mean query time. For example, 500 queries/s × 4 ms = 2 busy connections per active tenant DB, plus headroom.
  • Open connections lazily and close idle ones aggressively. Most tenant DBs are idle most of the time.

This connection fan-out, more than storage, is usually what limits database-per-tenant at large tenant counts. That's why bridge models silo only the tenants who need it.

Defence-in-depth verification. Teams with strong isolation records add an independent check that doesn't share code with the main path. For example, a response filter that inspects outgoing JSON for tenant_id fields and blocks responses containing any tenant other than the caller's, logging an incident. It costs a few microseconds per response, and it turns a silent leak into a loud error. Combined with RLS (database), scoped repositories (application) and tenant-aware caches, an attacker or a bug must defeat several independent mechanisms at once.

Deep Dive: Fairness Math: Token Buckets per Tier, Fair Queuing and Shuffle ShardingShow

Sizing per-tenant token buckets. A token bucket with rate r and capacity b admits at most b + r·t requests in any window of length t. For tiers:

Free:        r = 10 req/s,    b = 20       → sustained 864k/day, burst of 20
Pro:         r = 100 req/s,   b = 500
Enterprise:  r = 1,000 req/s, b = 5,000 (or custom contract)
Platform capacity check: Σ over tenants of r_i × P(tenant active at peak) ≤ capacity × target utilisation

Oversubscription is normal. If 50,000 free tenants each have r = 10, the nominal sum is 500,000 req/s, but at peak perhaps 2% are active at full rate, which is 10,000 req/s. Rate limits protect against individual abuse. Global load shedding protects against aggregate overload, by shedding the lowest-priority traffic first (free tier, bulk APIs), then degrading features, and protecting critical paths last.

Fair queuing for shared workers. A single FIFO queue gives each tenant throughput proportional to how much it enqueues. That rewards the noisiest tenant. Fair queuing gives each backlogged tenant an equal (or weighted) share of service, regardless of how many jobs it queued. The practical algorithm is Deficit Round Robin (Shreedhar and Varghese, SIGCOMM 1995):

  1. Keep a queue per active tenant.
  2. Each round, add a quantum Q (weighted by tier) to the tenant's deficit counter.
  3. Dequeue jobs while their cost is no more than the counter, subtracting each job's cost.
  4. Move to the next tenant. Empty queues lose their deficit.

DRR is O(1) per job, handles variable job costs (cost = estimated seconds or rows), and gives each tenant roughly a Q / ΣQ share when everyone is backlogged. A tenant that enqueues 1 million jobs gets its fair share, and the tenant that enqueued 10 jobs gets them done promptly instead of waiting behind the million. Combine DRR with:

  • per-tenant concurrency caps, so one tenant can't occupy all workers with long jobs;
  • job cost estimation and splitting (chunk a 10-million-row import into 10,000-row jobs, so fairness has fine granularity);
  • priority classes (interactive above bulk).

Weighted fair queuing (Demers, Keshav and Shenker, SIGCOMM 1989) is the idealised model that DRR approximates. For multiple resources at once (CPU and memory), Dominant Resource Fairness (Ghodsi et al., NSDI 2011) generalises max-min fairness. It equalises each tenant's share of its most-used resource.

Shuffle sharding probability. Assign each tenant a random shard of k workers out of n. A tenant that poisons its own k workers (say, its requests crash workers) affects another tenant fully only if that tenant's shard is identical. That happens with probability:

P(full overlap with a given other tenant) = 1 / C(n, k)
n = 8,   k = 2 → 1 / 28      ≈ 3.6%
n = 100, k = 5 → 1 / 75.3 M  ≈ 1.3e-8
P(other tenant loses at least j of its k workers) = Σ_{i≥j} C(k,i)·C(n−k, k−i) / C(n,k)   (hypergeometric)

With retries against the healthy members of its shard, a tenant survives as long as at least one worker remains. So the useful measure is the full-overlap probability, which falls combinatorially. Compare this with plain sharding into n/k groups. There, a poison tenant kills its whole group, and every tenant in that group, k/n of all tenants, goes down with it. Shuffle sharding turns "1/n of customers are affected" into "about 1 customer is affected". The cost is more complex placement and slightly lower cache locality.

Measuring noisy neighbours. You can't fix what you can't attribute. Emit per-tenant resource usage at every shared layer:

  • DB time per tenant: from pg_stat_statements with tenant tagging via query comments, or from sampled tracing;
  • queue time and worker seconds per tenant;
  • cache memory per tenant prefix.

Alert when any tenant's share of a resource exceeds a threshold, for example 20% of DB time, so you can act (throttle, move or talk to the customer) before others notice.

Deep Dive: Placement as Bin Packing, Cell Sizing and Safe Tenant MovesShow

Tenant sizes follow a power law. In most B2B SaaS, tenant load is heavy-tailed, roughly Zipf- or Pareto-distributed. A few tenants carry a large fraction of traffic and data. The tail is enormous in count but tiny in total. This has three consequences:

  • Hash placement balances counts, not load. With 10,000 tenants on 50 shards, each shard gets about 200 tenants. But whether a shard contains one of the top 20 tenants dominates its load, and two whales on one shard overload it.
  • Placement must be load-aware. New tenants arrive small, but some grow fast. Place by predicted load (plan tier, company size, early growth), keep headroom, and re-place on growth.
  • The top tenants deserve individual decisions (dedicated shard, cell or silo). The tail deserves automation.

Placement heuristics. Treat each tenant as a vector of demands (storage, QPS, CPU, growth) and each shard as a vector of capacities. Exact multi-dimensional bin packing is NP-hard, but greedy heuristics work well:

  • Best-fit decreasing: sort tenants by dominant demand and place each on the feasible shard with the least remaining capacity. This packs tightly, and is good for initial placement.
  • Least-loaded with headroom: place on the shard with the most headroom in its dominant dimension, keeping every shard below about 60–70% utilisation for growth and failover.
  • Power of two choices: pick 2 random shards and place on the less loaded one. It's nearly as good as global least-loaded, at far lower coordination cost (Mitzenmacher, 2001). Useful when placement is decentralised.

Rebalancing chooses moves that maximise balance gained per byte copied. Moving a 2 GB tenant that carries 5% of a hot shard's QPS beats moving a 500 GB tenant with the same QPS. Rate-limit moves so that they don't themselves become noisy neighbours, since copy and CDC load the source.

Cell sizing. Choose a cell's capacity so that three conditions hold:

  1. The largest single tenant fits, with headroom, unless whales get dedicated cells.
  2. Blast radius is acceptable. If losing 5% of customers for an hour is tolerable but 20% isn't, you need at least 20 cells of roughly equal value.
  3. Fixed overhead per cell is amortised. If a cell's fixed cost (control components, minimum instance counts, database HA pairs) is $8,000/month and it serves $400,000/month of revenue, the overhead is 2%. Cells ten times smaller would cost 20%.

Load-test every cell to its maximum size, and enforce that limit through the placement service. When cells fill up, add cells; never raise the cap without re-testing.

Making the catalogue safe. The router's tenant → cell and shard mapping is on every request's path. Design it for static stability:

  • read from a local cache or replica, with a long TTL and refresh-ahead;
  • continue serving the last-known mapping if the catalogue is unavailable;
  • keep writes to the mapping rare and audited (moves, onboarding).

The catalogue itself can be small. Even 10 million tenants × 100 bytes is 1 GB, which fits in memory on every router.

Correctness during a tenant move. The dangerous moment is cutover, when some app instances still believe the tenant lives at the source. A safe protocol uses a per-tenant epoch or fencing token:

  1. The catalogue entry carries (location, epoch). Routers include the epoch in every write.
  2. To cut over, set the tenant to moving (writes are briefly rejected with a retryable error) and wait for in-flight writes to drain, or for the request timeout to pass.
  3. Confirm the CDC stream has applied the source's final change position to the target, and verify row counts and checksums.
  4. Update the catalogue to (target, epoch + 1) and mark the source shard read-only for this tenant, for example with a per-tenant write-block flag checked in the data layer, or a trigger.
  5. Any write still carrying the old epoch, or arriving at the source, is rejected. Clients retry, re-resolve the route and land on the target.

This is the same fencing idea used for distributed locks and leader failover. Freshness comes from the epoch, not from timing assumptions (Distributed Locks). With small tenants, cutover takes about 1–5 seconds of rejected writes. With large tenants, the copy can take hours or days, but the freeze stays short, because the CDC catch-up happens before the freeze.

Pool → silo upgrades (a tenant buys the dedicated tier) are the same move, with a newly provisioned target. Silo → pool downgrades go the other way, and require the tenant's schema version to match the pool's. Fleet migration discipline makes that true. With moves cheap and safe, placement becomes a continuous optimisation instead of a one-time decision.

Key Takeaways#

  • Multi-tenancy trades sharing for risk. Pooling gives density, cheap onboarding and one stack to run. Isolation, noisy neighbours and blast radius must then be engineered explicitly.
  • Silo, pool and bridge apply per layer and per tier. Most mature SaaS pools the long tail and silos enterprise or regulated tenants, with one codebase, where only configuration differs.
  • At the data layer: shared tables with tenant_id scale best, schema-per-tenant suits moderate tenant counts, and database-per-tenant gives the strongest isolation, per-tenant restore and residency, at the cost of fan-out.
  • Make tenant_id first-class. It leads every index and unique key, is part of foreign keys, and appears in cache keys, object paths, messages, logs and traces.
  • Enforce isolation in depth: tenant from a verified token, a scoped data layer, RLS with SET LOCAL and a non-owner role, scoped storage credentials, per-tenant keys, and cross-tenant tests and canaries.
  • Control noisy neighbours with per-tenant rate limits and quotas by tier, fair queuing (DRR) and concurrency caps for background work, query timeouts, separate analytics paths, and shuffle sharding.
  • Place tenants by load, not count, through a catalogue. Isolate whales, rebalance with copy + CDC + fenced cutover, and use logical shards to decouple tenants from hosts.
  • Cells bound blast radius and enable deploy waves and residency. Keep the router and catalogue simple and statically stable.
  • Residency, lifecycle and metering are first-class features: regional cells and keys, automated provisioning and offboarding, fleet migrations in waves, and idempotent usage events feeding billing and per-tenant cost.
  • Salesforce's metadata-driven design (schema as data, flex columns, typed index tables, org-ID partitioning, governor limits) shows how far pooling can go when tenant-defined data models are the product.