Build log/SaaS

Multi-tenancy: how a SaaS keeps each customer’s data apart

Every SaaS has to answer one question early: how is one customer’s data kept away from another’s? There are three common answers, each with different costs.

The short answer

  • Most SaaS products share one database and tag every row with the customer it belongs to.
  • Separate schemas or separate databases give stronger isolation, at a higher running cost.
  • Whatever the model, enforce isolation in the database as well as in the application code.

The question

A SaaS product serves many customers from one system. Each customer, usually called a tenant, must only ever see its own data. Getting this wrong is the most damaging bug a SaaS can have, so the approach should be decided before the first table is created.

Three common models

ModelHow it worksSuits
Shared tablesEvery row carries a tenant IDMost B2B SaaS, especially early on
Schema per tenantEach customer gets its own set of tables in one databaseFewer, larger customers with custom needs
Database per tenantEach customer gets a separate databaseStrict data residency or contractual isolation

Shared tables, done safely

Tagging rows with a tenant ID is cheap to run and simple to operate, but one forgotten filter in one query can leak data. We guard against that in two places: the application scopes every query to the current tenant, and the database enforces it too, for example with PostgreSQL row-level security, so a missed filter returns nothing instead of someone else’s records.

When to isolate more

Some customers require their data in a separate database, or in a specific region. Designing the data access layer so a tenant can be moved to its own database later keeps that option open without paying for it on day one.

The parts people forget

  • Background jobs and exports need the same tenant scoping as the web app.
  • Search indexes and caches must be partitioned by tenant too.
  • File storage should keep each tenant’s uploads under its own path, with access checked on every download.
  • Tests should include a second tenant whose data must never appear.

Why decide early

Changing the tenancy model after launch means migrating live customer data. Choosing deliberately at the start, and writing the reasons down, is one of the cheapest decisions in the whole build.

Written by Flavoureak

We build and run Estimark, CurioKids and CalcStack, and we build web and mobile software for other businesses. Start a project.