skip to content
Articles

Designing a Multi-Tenant System

Watch the video: Designing a Multi-Tenant System

When is Multi-Tenancy needed?

There are many other articles on the internet that talk about multi-tenancy as a SaaS application that serves multiple users, known as tenants. Each tenant’s data is isolated and invisible to others, ensuring privacy and security.

But that is a default design for any application whether it serves business-to-consumer (B2C) or business-to-business (B2B).

Business to Consumer (B2C)ProductUser 1User 2User 3
Business to Business (B2B)ProductOrg 1User 1User 2User 3Org 2User 1User 2User 3Org 3User 1User 2User 3

In our article we deep dive into the concept of multi-tenancy where the B2B application serves multiple business teams and organizations as tenants. Each tenant has multiple users who may have their own isolated data and can share some data with other members of the tenant, which is isolated and invisible to other tenants, ensuring privacy and security.

It’s a building block that has nothing to do with the functionality of your application but will have a significant influence on the footprint of your system architecture, code, and business.

The best examples of multi-tenant systems are:

  • Slack - each organization can have their own workspace where users can DM each other and be part of public or private channels
  • Google Workspace - each organization can have their own central domain, allowing users to collaborate via professional emails, share calendars, drive, docs, sheets, slides, etc.

Slack

Slack One product
Acme Roboticsacme.slack.com
#general public
🔒founders private
✉Priya → Marcus DM
Members
PRPriya MAMarcus LILin
Bluefin Bankbluefin.slack.com
#trading-desk public
🔒risk-review private
✉Ana → Tomas DM
Members
ANAna TOTomas RURuth
Cedar Schoolscedar.slack.com
#staff-room public
🔒admissions private
✉Sam → Noor DM
Members
SASam NONoor DADara

Google Workspace

Workspace One product
Acme Robotics@acmerobotics.com
Shared inside the domain
Gmail Calendar Drive Docs Sheets Slides
PRpriya@acmerobotics.com MAmarcus@acmerobotics.com
Bluefin Bank@bluefinbank.com
Shared inside the domain
Gmail Calendar Drive Sheets
ANana@bluefinbank.com TOtomas@bluefinbank.com
Cedar Schools@cedarschools.org
Shared inside the domain
Gmail Calendar Drive Docs
SAsam@cedarschools.org NOnoor@cedarschools.org

Fundamentals

While designing the approach, we don’t decide an architecture first and then figure out how the business works on top of that. Instead, the system design and the business goals work together to find the right balance to achieve the best possible outcome for a given situation. You might be in an early stage bringing in your first few customers or in a growth stage with a rapid increase in customers and scale in revenue. Both can employ their own unique design approach to design and architect their multi-tenant environment.

We start with a monolithic service first where the compute and storage are single instances shared by your first few tenants. Then as the application requirements scale, we will break down the system into multiple components based on the use case demands.

No matter what approach we go with, the following fundamentals apply to the system as a whole:

Onboarding

The first user that signs up on the product and creates a Workspace kickstarts the Onboarding process of the new tenant. This includes assigning a unique identifier to our tenant that will be leveraged across most of the moving parts of our multi-tenant architecture. And then provisioning and configuring any application level resources for that tenant.

User 1ProductWorkspace 1Tenant Resources1. signs-up2. new workspace3. provisionUser 2ProductWorkspace 14. signs-up5. join workspace

Identity

In a multi-tenant environment, being able to authenticate a user is not enough. Your system should be able to bind a user to a tenant. In most of the cases a user that has signed up on the product has to belong to at least one tenant. In most systems, a user may also belong to multiple tenants - Slack, Discord, Notion, etc., where they would have different roles and access grants in the tenants.

User 1ProductWorkspace 1signs-up1. createsownerUser 2ProductWorkspace 2signs-up2. joinsmember3. createsowner

Tenant Context

When a user makes any request on the application, that request should always be functioning in the context of a specific tenant. As a system architect, you’ll have to make sure the tenant context flows in all the services called. The tenant context is used to resolve the tenant and its resources. Any request without it should be considered an invalid request. A user who belongs to multiple tenants may request a service using only one tenant identifier in the context.

UserProductWorkspace 1Workspace 2make_request(tenant="Workspace 1")routed to

Tenant Isolation

There can be 2 tenants that may or may not share the same compute resources. The data for them may or may not be stored in separate database instances. There is nothing that ensures that Tenant 1 can’t access data of Tenant 2 unless we design it in application logic that uses the tenant context to prevent cross-tenant access and ensure isolation between them.

User 1User 2Workspace 1Workspace 2ownerviewerowner

Functional Requirements

A multi-tenant application will have tons of features where users of various roles and permissions can create, view and share resources. We are just covering the core requirements and design where users can set up tenants and/or join tenants set up by other users of their team. A tenant can be named as a Workspace, Team, or Organization, depending on the use case. We will consider a tenant to be a Workspace in our design.

Core Requirements

  • Users can sign-up/sign-in using their email.
  • When a user signs up, they have the option to create their own workspace or join another workspace.
  • When a user is signed-in, they can switch their workspace from a list of workspaces they are a part of or create a new workspace at any point of time.
  • A user has to belong to at least one workspace.

Out of Scope

  • Users having roles in the workspaces when they join or create one.
  • The other core features of the application where a user can create, edit, view and share resources in the workspace.

Non-Functional Requirements

Even though we are not designing the core features of our multi-tenant application, we still have to consider them while designing our architecture that scales to the system’s need. In the design, we will consider cases where some workspaces will have high usage as compared to others.

Core Requirements

  • A user can only view or edit the workspaces they are part of, and the resources of each workspace stay isolated from the others.
  • Heavy usage on a few workspaces should not impact performance on other workspaces.

Out of Scope

  • Data residency & regional compliance like GDPR, data localization laws. It is relevant once real customer resources and PII are involved at scale, but not needed for the workspace setup/join/switch flow we’re designing here.
  • Disaster recovery and multi-region failover.

Core Entities

From the functional requirements we can get the idea that we need the following core entities:

  • Users
  • Workspaces
  • Memberships

The Users sign up on the application and onboard the Workspaces. Other Users can join these Workspaces. What user belongs to what workspace is defined by memberships where a single user can be part of multiple Workspaces.

User 1User 2ProductWorkspace 1Workspace 2UsersWorkspacesMemberships1. signs up3. signs up2. creates workspace4. joins workspace5. creates workspaceUsersU1User 1U2User 2WorkspacesW1Workspace 1W2Workspace 2MembershipsU1W1U2W1U2W2

APIs

There are 2 types of identities here - the user, and the workspace the user belongs to, i.e. the membership.

The API endpoints will be designed with 3 levels of security:

  1. Unsecured - No auth is required to access these endpoints.
  2. User scoped - A token is required which has the user identity but carries no workspace claim. It cannot read workspace specific data.
  3. Membership scoped - A token is required that carries the membership of the user and the workspace. These endpoints carry the tenant context and provide access to the tenant specific resources.

For keeping the scope limited, we are not considering the expiry of the tokens for the API design.

UnsecuredUser scopedTenant scopedUser 11. sign_upemail, passworduser, identity_token2. create_workspaceidentity_token, name, slugworkspace, workspace_tokenUser 23. sign_upemail, passworduser, identity_token4. join_workspaceidentity_token, workspace_slugworkspace, workspace_tokenUser 15. sign_inemail, passworduser, identity_token6. get_workspace_tokenidentity_token, workspace_idworkspace, workspace_token7. list_resourcesworkspace_tokenresources

Sign Up

POST /api/auth/signup

Request

{
  "email": "string",
  "password": "string"
}

Response

{
  "user": { "id": "string", "email": "string" },
  "identity_token": "string"
}

Sign In

POST /api/auth/signin

Request

{
  "email": "string",
  "password": "string"
}

Response

{
  "user": { "id": "string", "email": "string" },
  "identity_token": "string"
}

Create Workspace

The auth endpoints provide the user identity token that is then used for the workspace endpoints.

POST /api/workspaces
Authorization: Bearer <identity_token>

Request

{
  "name": "string",
  "slug": "string"
}

Response

{
  "workspace": { "id": "string", "name": "string", "slug": "string" },
  "workspace_token": "string"
}

Join Workspace

This is when the user joins a new workspace for the first time.

POST /api/workspaces/join
Authorization: Bearer <identity_token>

Request

{
  "workspace_slug": "string"
}

Response

{
  "workspace": { "id": "string", "name": "string", "slug": "string" },
  "workspace_token": "string"
}

Get Workspace Token

This is when the user already belongs to the workspace.

POST /api/workspaces/token
Authorization: Bearer <identity_token>

Request

{
  "workspace_id": "string"
}

Response

{
  "workspace": { "id": "string", "name": "string", "slug": "string" },
  "workspace_token": "string"
}

List Workspace Resources

This endpoint is one such example where the user actually needs the workspace context to access workspace related resources. As we have already discussed, we are not designing the actual application, but the understanding is that till this point the user and the workspace have been onboarded, and now the user can access the application fully.

GET /api/resources
Authorization: Bearer <workspace_token>

Response

{
  "resources": [
    { "id": "string", "name": "string" }
  ]
}

Starting with a Simple Monolith

We start with a single server for compute and a single database instance for storage considering your application will have only 2 - 3 tenants to manage in the beginning.

There are modern databases that support multiple databases in a single instance.

A good practice is to have a common database to store Workspaces, Users, and Memberships, and dedicated databases for each tenant.

UsersServerDatabasecommon_dbWorkspaces, Users, Membershipstenant_1_dbtenant_2_db...

Each of the 3 levels of API security uses the databases differently:

  1. Unsecured - Sign up and sign in only read and write the Users table in common_db.

  2. User scoped - To create a workspace, the server creates a new database for it, then adds the Workspace and the Membership rows in common_db.

    CREATE DATABASE tenant_3_db;

    To join a workspace, the server finds the Workspace in common_db and adds a Membership row.

  3. Membership scoped - The server looks up the Membership and the Workspace in common_db to find the workspace’s database. It then opens a connection to that database and queries the resources in it.

A separate database on a shared instance gives you logical isolation.

In a shared table, every query needs WHERE tenant_id = ?. If you forget in one query, the users in the tenants start seeing all tenant’s data rows.

Taking Postgres as an example, each database is a directory under base/, named by the database’s OID, and it holds the files of its own tables.

Serverglobal/pg_database, pg_authid, ...pg_wal/one WAL for every databasebase/16384/common_db1639016390_fsm16390_vm...the users table: data, free space map, visibility map16400/tenant_1_db1641016410_fsm16410_vm...the resources table: data, free space map, visibility map16420/tenant_2_db1643016430_fsm16430_vm...the resources table: data, free space map, visibility mapconnection 1connection 2connection 3

Postgres allows up to 4,294,950,911 databases in a single instance, so the count of databases is not a concern here.

A single connection can access only one database. Since we are assuming only 2 - 3 tenants here, we will discuss connections when we scale the design for more tenants.

Scaling the Server

From this section onwards, assume we are discussing about the Tenant Scoped requests.

A server handles each request in steps. Some steps use the CPU, and some steps only wait.

Assume an API request takes 200 ms:

  • 20 ms of server CPU - auth, the business logic, and JSON.
  • 100 ms in the database.
  • 80 ms of other waits - network and calls to other services.

A CPU core runs one thing at a time. But a request does not hold the core for the full 200 ms:

  1. A request comes in. The core checks the workspace token and runs the business logic.
  2. The server sends the query to Postgres. The core is now free, so it picks up the next request.
  3. Postgres returns the rows. The core builds the JSON response.

So one core serves many requests at the same time. The server limit depends on the 20 ms of CPU, not on the full 200 ms.

Request 1CPUdatabase 100 msother waits 80 msCPURequest 2CPUdatabase 100 msother waits 80 msCPURequest 3CPUdatabase 100 msother waits 80 msCPUOne core112233free for other requests

So when does the performance start degrading?

Assume a request uses 20 ms of CPU.

Then one core can serve 1 / 0.02 = 50 requests in each second, one after the other.

A server with 4 cores: 4 × 50 = 200 requests in each second. This is the absolute maximum, when every core is busy all the time.

Waits start to grow before 100%, at about 70% busy, because requests arrive in bursts and not evenly.

70% of 200 = 140 requests in each second.

There are 2 options for scaling the server here

Vertical Scaling

Add more cores to the server.

Requests/sec before latency rises = cores × 50 × 70%.

CoresRequests/sec
1~35
2~70
4~140
8~280
16~560
32~1,120

Horizontal Scaling

One machine can only hold so many cores.
It is also the single point of failure. If the server stops, the entire application is down. You can add more server and put a Load Balancer in front of them.
The Load Balancer sends each request to one of the server. We are not going in-depth on what is the Load Balancer and how it chooses the server, there are various algorithms for that.

RequestsLoadbalancerDatabaseServer 1Server 2Server 3

Here any Server can process requests for any user belonging to any of the tenants. The users and requests will not be uniformly distributed by the tenants. Expect a skew where some tenants contribute to more usage than others. This is known as a noisy neighbour problem which we will discuss later.

Scaling the Database Connections

A standard Postgres instance has a limit of max 100 connections allowed. A connection runs one query at a time. So that means 100 queries at a given moment serving approx 100 requests. Databases have a connection pool to keep the connections open.

Without a pool:

  1. A request comes in.
  2. The server opens a new connection to Postgres.
  3. The server runs the query.
  4. The server closes the connection.

Opening a connection is slow, because Postgres must start a new process for each one.

With a pool:

  1. The server opens, for example, 10 connections at the start and keeps them open.
  2. A request comes in and borrows a free connection.
  3. The server runs the query.
  4. The request gives the connection back, and the next request uses it.
Without a poolServerDatabaseRequest 1Request 2Request 3new connectionWith a poolServerConnection poolDatabaseRequest 1in useRequest 2in useRequest 3in usekept openRequest 4waits

So when does the performance start degrading?

Assume a request holds a connection for 100 ms.

Then one connection can serve 1 / 0.1 = 10 requests in each second, one after the other.

100 connections × 10 = 1,000 requests in each second. This is the absolute maximum, when every connection is busy all the time.

Waits start to grow before 100%, at about 70% busy, because requests arrive in bursts and not evenly.

70% of 1,000 = 700 requests in each second.

There are 2 options for scaling the database here

Vertical Scaling

You can change the max_connection setting and increase the number but the real limit is memory.
Postgres starts one separate process for each connection. Each process uses its own memory, and a query that sorts uses more. A bigger instance has more memory, so you can safely set a higher number.

An idle connection uses about 7.6 MiB of memory.

So we can estimate:

  • 25% of memory for shared_buffers, as the Postgres docs suggest.
  • 25% of memory for the OS and its cache.
  • 50% of memory for the connections.
  • About 12 MiB per connection - 7.6 MiB idle and one 4 MB sort (work_mem).

max_connections ≈ 50% of memory / 12 MiB

With 100 ms per request, requests/sec before latency rises = max_connections × 10 × 70%.

Memorymax_connectionsRequests/sec
2 GiB~85~600
4 GiB~170~1,190
8 GiB~340~2,380
16 GiB~680~4,760
32 GiB~1,360~9,520
64 GiB~2,730~19,110
128 GiB~5,460~38,220
256 GiB~10,920~76,440

Horizontal Scaling

When we scale the servers horizontally, it adds more connections for the database to manage. So scaling the database instances horizontally helps to spread these connections across more instances. Each instance holds only some of the tenants, so it manages only the connections to their databases.

RequestsServerfinds the instance in common_dbPool 1Database 1common_dbtenant_1_dbtenant_2_dbtenants 1, 2Pool 2Database 2tenant_3_dbtenant_4_dbtenants 3, 4

This is called sharding. Each Postgres instance is a shard, and each shard holds the complete data of some tenants. A tenant’s data lives on one shard only, and never splits across two.

The server picks the shard from the Workspace row in common_db. The row now stores the instance that holds the workspace’s database:

idnamedb_namedb_host
1Acmetenant_1_dbpostgres-1
3Globextenant_3_dbpostgres-2
  1. A request comes in for workspace 3.
  2. The server reads the Workspace row and finds db_host = postgres-2.
  3. The server takes a connection from the pool for postgres-2 and queries tenant_3_db.

The server caches this lookup in memory - workspace 3 → postgres-2, tenant_3_db. A workspace seldom moves, so most requests skip the read from common_db and go straight to the right database.

When a user creates a workspace, the server picks the instance with the fewest tenants. It runs CREATE DATABASE on that instance and saves the host in the Workspace row.

Noisy Neighbour Problem

We have scaled the servers and the database instances to handle the traffic.
In the real world, the traffic is not uniformly distributed across tenants.
It is more likely to follow the Pareto Principle - “80% of the traffic comes from 20% of the tenants”.
These tenants use the CPU and the database connections at a much higher rate than the tenants with fewer users and less usage.

Consider this from the perspective of the tenants:

  • High-usage tenants are your high-profile customers, and they bring you the most revenue. They now compete with each other for the same resources. A performance drop for any one of them breaks their trust.
  • Low-usage tenants are far more in number, and they compete for the same resources too. If their performance drops, it shows that your system cannot handle even their low usage. Any chance that they expand with you is gone.
high usageTenant ATenant Blow usageTenant CTenant DTenant ETenant FLoadbalancerServer 1CPUAABABCServer 2CPUBABBAAServer 3CPUABADBADatabase 1connectionsAAAACholds A, C, DD waitsDatabase 2connectionsBBBBEholds B, E, FF waits

Rate Limiting

The first step is to cap the number of requests that each tenant can send in a time window, for example in each second or in each minute.

The server counts the requests for each tenant. When a tenant reaches its limit, the server rejects the next requests with 429 Too Many Requests. The response has a Retry-After header that tells the client how long to wait before it tries again. When the window resets, the tenant can send requests again.

So a tenant that sends too many requests only slows itself down. The other tenants keep their share of the servers and the database.

Tenant limits and user limits

  • Tenant limit: caps all the requests from one workspace. It protects the other tenants from one busy tenant.
  • User limit: caps the requests from one user in a workspace. It protects the other users in the same workspace from one busy user, for example a script that runs in a loop.

Use both together. The server checks the user limit first, then the tenant limit. A busy user then cannot use all of their workspace’s limit, and a busy workspace cannot use the capacity of the other tenants.

Tenant AUser 1 (script)User 2Tenant BUser 3Serveruser limit429Retry-Aftertenant limit429Retry-AfterDatabase

Rate limits stop abnormal usage, but the high-profile customers expect a higher usage capacity and higher limits. They pay a premium price, so they expect premium usage.

Dedicated Database Instance

The data is sharded across multiple database instances.
Each instance holds the complete data of some tenants.
This causes a few problems when the tenants are not equal in size:

  • Multiple high-profile tenants can land on the same instance. They then compete with each other for the same resources.
  • Connections: the high-usage tenants take most of the database connections of the instance.
  • CPU and disk reads: their heavy queries use most of the CPU and the disk. The queries of the other tenants wait.
  • Memory: the database keeps recent data in memory to skip the disk. The high-usage tenants’ data pushes the other tenants’ data out, so the other tenants’ queries get slower.
  • Storage: a large tenant’s data grows faster. When the disk fills up, every tenant on that instance stops writes.
  • Backups and maintenance: a large tenant makes backups, restores and schema changes slower for the whole instance.

The fix is to move the heavy tenant to its own database instance.

RequestsLoadbalancerDatabase 1sharedcommon_dbtenant_2_dbDatabase 2sharedtenant_3_dbtenant_4_dbDatabase 3dedicated to tenant 1tenant_1_dbServer 1Server 2Server 3

For tenant 1:

  1. Create a new database instance.
  2. Copy tenant_1_db from the shared instance to the new instance. While the copy runs, keep copying the new writes, so the copy stays up to date.
  3. Stop writes for tenant 1 for a short time, so the last writes reach the new instance.
  4. Change the db_host in the tenant’s Workspace row to the new instance.
  5. Clear the cached lookup on the servers, so they connect to the new instance.
  6. Allow writes again. Then remove tenant_1_db from the shared instance.

The sharding makes this easy. The servers already find each tenant’s instance from the Workspace row, so the code does not change.

Dedicated Server Instance

The high-profile customers expect premium usage and more lenient rate limits.
But a higher limit on the shared servers means more load on the shared servers. Their extra requests use the CPU that the other tenants need. So the other tenants slow down again.

The fix is to give the high-profile tenant its own servers.
The load balancer reads the workspace from each request. It sends tenant 1’s requests to tenant 1’s servers, and all the other requests to the shared servers.

RequestsLoadbalancerroutes by workspacesharedServer 1Server 2Server 3tenants 2, 3, 4tenant 1Server 4Server 5tenant 1Database 1sharedcommon_dbtenant_2_dbDatabase 2sharedtenant_3_dbtenant_4_dbDatabase 3dedicated to tenant 1tenant_1_db

The dedicated servers also give more flexibility:

  • Higher rate limits: the tenant’s limits only affect its own servers, so you can raise them as far as these servers can handle.
  • Large requests: reports, exports and file uploads run on the tenant’s own CPU and memory. If a large request crashes a server, only this tenant’s requests fail.
  • Background jobs: imports, scheduled jobs and other heavy work for this tenant run on its own servers, not next to the requests of other tenants.
  • Sizing: you add servers for this tenant when its usage grows, and you know the cost of each tenant.

Dedicated Deployment

Tenant 1 now has its own servers and its own database instance. But it still shares a few parts of the system with every other tenant:

  • The load balancer: all the requests still pass through it.
  • common_db: every request still reads the Workspace row and the user from it.
  • The region: tenant 1’s data is in the same region as the data of every other tenant.

For performance, this is enough. The noisy neighbour problem is solved. But some customers need more than performance:

  • Isolation: a problem in a shared part still reaches them. If the load balancer or common_db goes down, tenant 1 goes down with everyone else.
  • Region: the law in their country can need their data to stay in that country. A shared deployment in another region cannot meet this.
  • Contract: some large customers, for example banks and governments, put in the contract that nothing is shared with other customers.

The fix is a dedicated deployment. Tenant 1 gets a full, separate copy of the system: its own load balancer, servers, common_db and database instance. It runs the same code, but nothing is shared with the other tenants, and it can run in the region that the customer chooses.

shared deploymentRequeststenants 2, 3, 4LoadbalancerDatabase 1common_dbtenant_2_dbDatabase 2tenant_3_dbtenant_4_dbServer 1Server 2Server 3tenant 1 deployment, in its own regionRequeststenant 1LoadbalancerDatabase 3common_dbtenant_1_dbServer 4Server 5

This is the strongest isolation, and also the most expensive. Each dedicated deployment is one more system to run, monitor and upgrade.

Real World Design - Hybrid

In real production systems, the application has multiple microservices.
The overall design combines all the models above. Each service uses the model that fits its scale and usage.

shared deploymentLoadbalancerTenant 1User 1User 2Tenant 2User 3User 4Tenant 3User 5User 6Service 1: single server, single databaseDatabaseServerService 2: scaled servers, scaled databaseDatabase 1Database 2Server 1Server 2Server 3Service 3: scaled and dedicatedDatabase 1sharedDatabase 2dedicated to tenant 1Server 1Server 2Server 3tenant 1enterprise tenant deploymentLoadbalancerEnterprise TenantUser 7User 8Databaseshared by all 3 servicesService 1Service 2Service 3

You would be familiar with Cost Tiers that SaaS application uses - Basic, Pro, Enterprise.
The design also depends on what Tier the tenant belongs to.

  • Basic: shared servers and shared database instances, with strict rate limits.
  • Pro: the shared deployment, with higher rate limits. A heavy Pro tenant gets dedicated servers or a dedicated database instance for the services that it uses the most, like tenant 1 in Service 3.
  • Enterprise: a dedicated deployment, like the Enterprise tenant.

Sources