Tenant Sharding and Cell-Based Architecture for SaaS

Multi-tenancy

Scale multi-tenant SaaS with cell architecture. Learn tenant placement, isolation boundaries, PostgreSQL migration, single-writer cutover, and failure testing.

TL;DR

  • A cell is an independently deployable copy of a service that owns a subset of tenant traffic and state. A cell boundary can limit the impact of overload, faulty releases, and some infrastructure failures.
  • Sharding partitions data across storage systems. Cell architecture is broader: it partitions compute, databases, workers, caches, and often operational ownership together.
  • There is no tenant-count threshold that automatically requires cells. Use measured saturation, failure impact, recovery goals, residency needs, and staffing to justify the added control plane and duplicated infrastructure.
  • Build a tenant-placement directory and a thin router. Resolve the tenant from authenticated context, route to its assigned cell, and pass a placement epoch so stale workers or caches cannot write after a move.
  • Moving a tenant requires a tested data migration and a single-writer cutover. PostgreSQL logical replication can help, but DDL, sequences, large objects, and conflict handling need their own plan.

Why a single shared stack eventually becomes a large failure domain

In a shared multi-tenant service, many organizations rely on the same application deployment, database cluster, worker pool, and cache. Pooling those resources is efficient and simple to operate while capacity and failure impact remain acceptable. As usage grows, one expensive tenant can create contention, a schema migration can affect every customer, and a regional dependency can turn one incident into a broad outage.

Horizontal database sharding addresses one part of that problem by distributing data across several database servers. A cell-based architecture creates a larger isolation boundary. Each cell runs a complete or near-complete copy of the workload and serves an assigned subset of tenants. AWS describes cells as independent instances that handle subsets of requests, with failures limited to the cell when components and state do not cross the boundary. AWS Well-Architected cell-based fault isolation

Cells do not create automatic resilience. A global router, shared identity service, central database, or synchronous cross-cell call can remain a common failure dependency. If every cell receives a bad deployment at once, every tenant can still be affected. The architecture has to preserve independence in its data paths, rollout sequence, dependencies, and operational controls.

A tenant-count title such as “beyond 100,000 organizations” is not a capacity threshold. A product with thousands of heavy tenants may need isolation sooner than one with many small, quiet tenants. Measure database CPU and I/O, connection pressure, vacuum lag, queue age, cache contention, noisy-neighbor incidents, data-residency constraints, and the cost of a broad failure before creating cells.

Separate data sharding from cell architecture

Database sharding assigns records to different database instances, usually by a shard key. The application or a routing layer must know which shard owns a record. PostgreSQL declarative partitioning splits a table inside one PostgreSQL cluster; it is not the same as sharding across independent servers. Partition pruning can help query and maintenance behavior, but it does not isolate application deployments or independent failure domains. PostgreSQL table partitioning

A cell usually includes more than the database. It may have its own API deployment, background workers, cache, queues, search index, and cell-specific telemetry. Some shared control-plane services still exist, such as authentication, tenant placement, artifact distribution, billing, and global reporting. Keep those shared services small, resilient, and outside synchronous paths where possible.

Cells and sharding can be combined. A cell can own a database cluster that is internally partitioned, or a cell can contain several shards. Choose the simplest structure that meets the isolation and capacity requirements. Avoid adding a second routing hierarchy before the first one has clear ownership and failure behavior.

Design tenant placement as control-plane state

A tenant placement directory maps a stable tenant ID to a cell ID, region, placement epoch, and lifecycle status. The directory is control-plane state. It should be strongly protected, auditable, backed up, and available to the routing tier. It should not become a hot, complex business database that every service mutates independently.

Resolve tenant identity only after authenticating the request. The client may send an organization slug or hostname, but the server must validate that it maps to an organization the principal is authorized to access. The trusted placement service then routes to the owning cell. Do not allow a caller to choose an arbitrary cell using a mutable header or path field.

Keep the router thin. It should authenticate enough to find the tenant, look up placement, forward the request, and preserve trace and authorization context. Business rules remain inside the cell. The router should not aggregate arbitrary cross-cell queries, implement tenant-specific workflow branches, or become a global transaction coordinator.

Cache placement to avoid a directory lookup on every request, but make cache invalidation and tenant moves explicit. Include a placement epoch that increments when ownership changes. A cell can reject writes with a stale epoch, preventing an old worker or long-lived cache entry from mutating tenant state after cutover. Consider signed or server-authenticated routing metadata so clients cannot invent that epoch.

Choose cell boundaries and sizes deliberately

Useful placement keys include tenant ID, residency region, service tier, or an explicit dedicated-cell assignment. Keep one tenant’s strongly related data and request path within one cell when practical. A single tenant split across cells complicates transactions, support, migrations, and failure handling. When large tenants need multiple data partitions, make that a deliberate exception with its own routing model.

Cell size is a tradeoff. Small cells limit the number of tenants affected by one failure and make a move more manageable, but increase duplicated infrastructure, deployment work, and capacity fragmentation. Larger cells use resources more efficiently and require fewer control-plane records, but increase the blast radius. AWS notes that cells should remain independent, bounded, and not share mutable state, and warns that growing cells without bounds undermines the pattern. AWS bulkhead design considerations

Capacity planning should use a per-cell envelope. For each workload class, track sustained and peak CPU, database utilization, connection pool pressure, storage growth, queue age, and tenant-level skew. Leave room for failover and migration headroom. A cell that is 90% full may have no space to receive a tenant from a failing neighboring cell.

Use staged deployments. Roll a release to one or a small group of cells, monitor health and tenant impact, then expand. Avoid changing every cell at once. Keep schema changes compatible with old and new application versions during a rollout. Cell isolation is weakened when a shared release process synchronously flips the entire fleet.

Keep tenant data scoped within the cell

Every cell still needs tenant isolation among the tenants assigned to it. Include tenant ID in database constraints, unique keys, authorization checks, caches, object-storage paths, search filters, and background job payloads. Cell routing prevents accidental cross-cell lookups only if every access path uses the same placement and tenant context.

When a job is enqueued, capture the tenant ID and placement epoch. A worker should confirm that it is still operating on the current placement before committing a write. Long-running jobs may be paused or redirected during migration. Make side effects idempotent so a drain-and-retry workflow cannot duplicate a payment, email, or external API mutation.

Do not use a cell ID as a replacement for a tenant ID in application authorization. A request routed to the correct cell can still access another tenant’s row if query predicates are missing. Continue using database protections such as row-level security where they fit the threat model, and maintain cross-tenant tests. PostgreSQL row-level security for multi-tenant data · Cross-tenant isolation test cases

Move a tenant with a single-writer cutover

Tenant movement is an operational workflow, not a routing-table edit. A safe plan has a destination cell with compatible schema and capacity, a consistent copy of tenant data, a way to catch up writes, a fencing mechanism, and a rollback decision. Practice the process on representative tenant sizes before relying on it during an incident.

  1. Prepare. Create the tenant’s schema, indexes, object prefixes, queues, and access controls in the destination. Verify the destination can support expected workload.
  2. Copy. Take a consistent snapshot of the tenant’s data or use a migration mechanism that captures changes. Validate row counts, checksums, sequence state, and dependent objects.
  3. Catch up. Apply changes made after the snapshot. PostgreSQL logical replication takes an initial snapshot and then sends ongoing changes, but it has restrictions and does not automatically replace every DDL, sequence, extension, or large-object migration requirement. PostgreSQL logical replication
  4. Fence writes. Stop or reject new writes to the source tenant, drain in-flight requests and jobs, confirm replication lag is zero, and advance the placement epoch. A stale source writer must fail closed.
  5. Switch and verify. Update placement, route requests to the destination, and monitor errors, latency, data reconciliation, and queue processing. Keep the source read-only for a defined rollback window.
  6. Retire. Remove source data only after reconciliation and retention requirements are satisfied. Record who approved the move and preserve a recoverable migration log.

A brief write pause is often easier to reason about than unrestricted dual writes. If the product cannot pause writes, use a carefully specified replication and conflict-resolution protocol. Dual-writing to both cells can diverge when one write succeeds and the other fails, so it needs idempotency, reconciliation, and a clear authoritative source.

Rollback becomes difficult after the destination accepts new writes. Define whether rollback is possible only before that first write, or whether reverse replication will be maintained. Do not promise “zero downtime” unless the service can uphold that behavior for the database, cache, queue, object storage, and in-flight work as a whole.

Design shared services so they do not erase isolation

Some dependencies need a global view. Authentication may issue a token usable across cells; tenant routing maps the authenticated tenant to its cell; billing may collect events across cells; analytics may aggregate telemetry. Use asynchronous replication or event pipelines for global reporting where freshness requirements allow. Avoid a synchronous shared service call on every cell request if its outage would take down the whole product.

Global services need their own cell-like capacity and recovery model. The placement directory can be replicated and cached with a controlled freshness bound. If it is temporarily unavailable, existing tenants may continue using cached placements while new tenant creation or moves pause. Define those behaviors instead of allowing arbitrary stale routing.

Cell boundaries should include queues and background work. A shared worker fleet can reintroduce resource contention across all tenants. If shared workers are necessary, use tenant-aware quotas and dispatch rules. See per-tenant worker quotas for fair background processing.

Measure blast radius and operational cost

Track which tenants are assigned to each cell, cell-level saturation, cross-cell calls, migration state, stale-epoch rejections, and deployment version. Define an explicit maximum impact objective, such as the maximum number or proportion of tenants a single cell incident may affect. Base that target on product commitments and test data, not on a universal percentage.

Measure the full cost of cells: duplicated baseline capacity, underutilized headroom, control-plane operations, per-cell upgrades, incident response, and support tooling. Dedicated cells may be appropriate for residency, contractual isolation, or unusually large tenants. Pooled cells can serve smaller tenants efficiently. A hybrid placement model is common, but it adds migration paths and tier-specific operational rules.

Rehearse failure scenarios: take one cell offline, deploy a bad version to a canary cell, overload a tenant, break the placement cache, and move a tenant while workers hold jobs. Confirm unaffected cells keep serving, operators can identify impacted tenants, and recovery follows the documented procedure.

Frequently asked questions

When should a SaaS company move from one database to cells?

Move when measured capacity, noisy-neighbor impact, recovery goals, residency requirements, or the cost of a broad failure justify the additional infrastructure and operations. Tenant count alone is not a threshold. Start with per-tenant workload and failure-impact measurements.

Is PostgreSQL partitioning the same as tenant sharding?

No. Declarative partitioning divides tables inside one PostgreSQL cluster. Sharding distributes data across independent database instances. Cell architecture is broader still because it isolates compute, databases, workers, caches, and often deployment and failure domains.

How can I move a tenant between cells without losing writes?

Copy a consistent snapshot, catch up changes, fence source writes, drain in-flight jobs, advance a placement epoch, then switch routing. Verify data and queue state before retiring the source. PostgreSQL logical replication can help, but DDL, sequence state, and other dependent resources need separate handling.

Do cells eliminate global outages?

No. A shared router, identity provider, control plane, deployment pipeline, or cross-cell dependency can remain a common failure point. Cells limit impact only when data paths, releases, capacity, and operational practices preserve their independence.

Adopt cells when the isolation benefit earns its complexity

Cell-based architecture can limit the number of tenants exposed to a regional overload, failed deployment, or data-plane incident. It also adds a placement directory, migration tooling, duplicated capacity, staged releases, and more operational paths. Use measured limits and recovery objectives to decide when that trade is worthwhile.

Keep placement server-side, make the router thin, maintain tenant isolation inside every cell, and move tenants with a single-writer plan. If you are evaluating tenant sharding or a cell migration, talk with our infrastructure engineers about placement, cutover, and failure testing.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with web applications

Discuss your project