Skip to content
Beytullah Toprak

Blog

How to Build a Multi-Tenant Architecture

Shared tables, schema per tenant or a database per tenant: how to choose a multi-tenant architecture, separate tenant data safely and what to watch for.

Reading time
7 min read
Multi-tenant architecture illustration with a database linked to user and lock icons
On this page
  1. What Is a Tenant?
  2. Three Ways to Separate Data
  3. Setting Up Shared Tables Safely in a Multi-Tenant Architecture
  4. Add the Tenant ID to Every Table
  5. Apply the Filter in One Place
  6. A Second Lock at the Database Level
  7. Write Cross-Tenant Tests
  8. Places Outside the Database
  9. How to Identify the Tenant
  10. Shared Resources and Noisy Neighbors
  11. The Tenant Lifecycle
  12. Frequently Asked Questions
  13. Are Shared Tables Safe?
  14. Can I Switch Approaches Later?
  15. When Does Schema per Tenant Make Sense?
  16. When Do You Need a Database per Tenant?

A multi-tenant architecture is one where a single application serves several customers (tenants) and keeps each tenant's data separate from the others. There are three common ways to separate the data: keep all tenants in one database with a tenant ID on every row, give each tenant its own schema in the same database, or give each tenant its own database. The choice depends on the number of tenants, isolation requirements, cost and maintenance load. For most new SaaS products, one database with a tenant ID is a good starting point. This post compares the three approaches and covers what to watch when setting one up.

What Is a Tenant?

A tenant is a customer organization using your product: a company, a school or a shop. A tenant can have many users. Microsoft's guide to tenancy models (opens in a new tab) recommends that before designing a multitenant solution, you need to be clear on how your organization defines a tenant. In a B2B product, the tenant is usually the customer company. In a product sold to individuals, each user may count as a separate tenant.

Three Ways to Separate Data

Approach How it works Pros Cons
Shared tables One database, tenant_id on every row Cheap, easy to set up and maintain, new tenants are instant Separation depends on the app or database policies; one bug can leak data
Schema per tenant A separate schema per tenant in the same database Stronger separation, per-tenant backup and migration get easier Managing migrations gets harder as schemas multiply
Database per tenant Each tenant has its own database The strongest isolation, little performance interference The most expensive; operational load grows with the number of tenants

Microsoft's guide spells out this trade-off: with resources dedicated to each tenant, tenants are unlikely to affect each other's performance, known as the noisy neighbor problem. On the other hand, because infrastructure isn't shared, cost efficiency is low. In the guide's example, if a single tenant requires a certain infrastructure cost, 100 tenants probably require 100 times that cost. That example refers to single-tenant deployments where each tenant gets all of the infrastructure; separating only the database can cost less. The guide also notes that if you expect only a few customers, or your customers have high isolation requirements, dedicated single-tenant resources can make sense even though they cost more.

Setting Up Shared Tables Safely in a Multi-Tenant Architecture

With this approach, the most common starting point, the biggest risk is a query that forgets the tenant filter and shows one tenant's data to another. Several layers are used together to prevent that.

Add the Tenant ID to Every Table

Every table holding tenant data should have an indexed tenant_id column. Uniqueness rules should include the tenant too. An email address, for example, might need to be unique within a tenant rather than across the whole system.

Apply the Filter in One Place

Writing the tenant filter into every query by hand invites mistakes. Most ORMs offer a mechanism that adds a condition to every query on certain models automatically. The tenant ID is determined from authentication at the start of the request and handed to that mechanism. Then even if a developer forgets the filter, the query only returns that tenant's data.

A Second Lock at the Database Level

If you use PostgreSQL, row level security adds a second layer of protection. According to PostgreSQL's documentation on row security policies (opens in a new tab), these policies restrict which rows normal queries can return or modify. If row security is enabled on a table and no policy exists, a default-deny policy applies and no rows are visible. A simple example:

sql
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON orders
  USING (tenant_id = current_setting('app.tenant_id', true)::uuid);

-- On every request, inside a transaction:
-- SELECT set_config('app.tenant_id', $1, true);

There's an important detail here. According to the same documentation, superusers and roles with the BYPASSRLS attribute always bypass row security, and table owners normally aren't subject to the policies either. So the application should connect to the database with a limited role that doesn't own the tables. If you want the table owner subject to the policies too, use FORCE ROW LEVEL SECURITY. Passing the tenant ID as a parameter through set_config, rather than building it into the query text, also avoids injection risk.

Write Cross-Tenant Tests

Microsoft's guide also recommends testing, whichever isolation model you choose, that one tenant's data isn't accidentally leaked to another. Automated tests that create two tenants and try to reach one tenant's records as a user of the other are among the most valuable tests you'll have.

Places Outside the Database

Tenant separation doesn't end with database tables. A few more places are easy to miss:

  • Files: uploaded documents and images should live in separate folders per tenant. File URLs shouldn't be guessable, and downloads should check that the user belongs to that tenant.
  • Cache: if cache keys don't include the tenant ID, a result computed for one tenant can be shown to another.
  • Background jobs: every queued job should carry which tenant it runs for, and the worker should rebuild the tenant context before running it.
  • Search indexes and reports: if you use a separate search service or reporting database, apply the same filter there.
  • Logs: having the tenant ID in error and access logs makes it easier to find which customer hit a problem.

Each of these is a leak path worth checking separately in code reviews and tests.

How to Identify the Tenant

On every request, the application needs to know which tenant it's working for. Common methods:

  • A subdomain: company.app.com.
  • The tenant in the user's session. If a user belongs to several tenants, the selected one is kept in the session.
  • In API requests, the tenant inside the authentication token.

The tenant should never be determined by trusting a parameter the client sends. Verify on the server that the user belongs to that tenant.

Shared Resources and Noisy Neighbors

In a single database, one tenant's heavy report can slow down everyone else. To reduce that, queue heavy work, set per-tenant rate limits and build a structure that can move large tenants to separate resources if needed. Many systems use a hybrid model: most tenants on shared infrastructure, with those that need high isolation or are very large on their own database. A central catalog showing which database each tenant lives in is usually enough to make that possible.

The Tenant Lifecycle

Adding, suspending, changing the plan of and deleting a tenant are operations to think about from day one. When deleting, how all of the tenant's data, files and backups are handled also matters for data protection obligations. I cover where these operations fit in SaaS architecture in how to build a SaaS, and permissions for users within a tenant in RBAC for SaaS.

Frequently Asked Questions

Are Shared Tables Safe?

Yes, if they're set up properly. Applying the tenant filter in one place, row level security at the database level and cross-tenant tests together reduce the risk considerably.

Can I Switch Approaches Later?

Yes, but it takes work. Adding a tenant ID to every table from the start also makes it easier to move a tenant to its own database later, since that tenant's data can be selected with a single condition.

When Does Schema per Tenant Make Sense?

When the number of tenants stays moderate and per-tenant backup or migration is needed often. Because every database change has to be applied to every schema, this approach usually works better for a limited number of tenants rather than hundreds.

When Do You Need a Database per Tenant?

When customers require physical separation of data by contract or regulation, and when there are few tenants and each one is large.

If you'd like to design your multi-tenant architecture together, see the SaaS and Microservice Development service or write to me through the contact page.

Share