Nov 23, 20266 min read

Multi-Tenant Database Design for SaaS

Shared tables with a tenant ID, a schema per tenant or a database per tenant: how the three models compare on isolation, cost and migrations, and how to design the shared model so one tenant cannot touch another.

Illustration for Multi-Tenant Database Design for SaaS

Every SaaS product serves many customers from one codebase, and the database has to decide how their data lives together. The choice affects cost, how risky a bug is, how migrations roll out and what you can promise a customer who asks where their data sits.

This guide compares the three common models, then designs the shared one so the tenant boundary holds even when application code makes a mistake.

How do the three models compare?

Shared schemaSchema per tenantDatabase per tenant
IsolationLogical, enforced by keys and policiesNamespaced, shared serverStrongest, separate database
Cost per tenantLowestLowHighest
MigrationsOne run for everyoneOne run per schemaOne run per database
Noisy neighborsPossiblePossibleIsolated
Per-tenant restoreHardModerateEasy
Tenant count it suitsThousands and upTens to hundredsFew, high-value

The AWS SaaS architecture whitepaper calls these pool, bridge and silo models, and notes that many products mix them, with small tenants pooled and large ones siloed. Citus's multi-tenant data modeling guide covers the shared model in depth, including why the tenant ID belongs in every table.

When is a schema or database per tenant worth it?

Choose a separate schema or database when a customer contract requires isolation, when one tenant's data volume would dominate the shared tables, or when you must restore one customer's data without touching others. The cost is operational: a migration becomes a loop over hundreds of schemas, connection pools fragment, and a tenant count in the thousands strains catalogs and tooling.

Starting shared and moving the few tenants who need it is much easier than starting siloed and consolidating later, as long as the shared design keeps tenants cleanly separable.

How do you design the shared model?

  • Tenant ID everywhere. Every tenant-owned table has a tenant_id column, including join tables.
  • Scoped keys. Make the primary key (tenant_id, id) or keep a global ID and add a unique (tenant_id, id) for foreign keys to reference.
  • Composite foreign keys. A foreign key from invoices to customers should include tenant_id, so an invoice cannot point at another tenant's customer.
  • Scoped uniqueness. Unique constraints such as email or slug are unique per tenant, UNIQUE (tenant_id, email).
  • Tenant first in indexes. Index (tenant_id, created_at), not (created_at), so queries touch one tenant's rows.
  • Backstop in the database. Add row-level security so a missing WHERE in application code returns nothing instead of everything. See Postgres row-level security for multi-tenant apps for the policy setup.

Where does the tenant ID come from?

The tenant ID comes from the authenticated session and never from a request parameter, because the auth handler resolves the token to a user and a tenant and handlers read the tenant from that context. A client that can send its own tenant_id can read any tenant's data.

How do you build it with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and a multi-tenant service declares its Postgres database in code and carries the tenant in the auth data that every endpoint marked auth: true receives. Encore provisions the database in your AWS or GCP account.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create saas-api --example=ts/hello-world$ cd saas-api && mkdir -p billing/migrations

The schema

-- billing/migrations/1_create_tenant_tables.up.sql CREATE TABLE customers ( tenant_id UUID NOT NULL, id BIGINT GENERATED ALWAYS AS IDENTITY, email TEXT NOT NULL, name TEXT NOT NULL, PRIMARY KEY (tenant_id, id), UNIQUE (tenant_id, email) ); CREATE TABLE invoices ( tenant_id UUID NOT NULL, id BIGINT GENERATED ALWAYS AS IDENTITY, customer_id BIGINT NOT NULL, amount_cents BIGINT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id, id), -- The tenant is part of the key, so an invoice cannot reference another tenant's customer. FOREIGN KEY (tenant_id, customer_id) REFERENCES customers (tenant_id, id) ); CREATE INDEX invoices_by_tenant_time ON invoices (tenant_id, created_at DESC);

The service

// billing/billing.ts import { api, APIError } from "encore.dev/api"; import { getAuthData } from "~encore/auth"; import { SQLDatabase } from "encore.dev/storage/sqldb"; const db = new SQLDatabase("billing", { migrations: "./migrations" }); // The tenant always comes from the authenticated session, never from the request. function tenant(): string { const data = getAuthData(); if (!data) throw APIError.unauthenticated("no session"); return data.tenantId; } interface Invoice { id: number; customerId: number; amountCents: number; } export const createInvoice = api( { expose: true, auth: true, method: "POST", path: "/invoices" }, async (req: { customerId: number; amountCents: number }): Promise<Invoice> => { const row = await db.queryRow<{ id: number }>` INSERT INTO invoices (tenant_id, customer_id, amount_cents) VALUES (${tenant()}, ${req.customerId}, ${req.amountCents}) RETURNING id`; return { id: row!.id, customerId: req.customerId, amountCents: req.amountCents }; }, ); export const listInvoices = api( { expose: true, auth: true, method: "GET", path: "/invoices" }, async (): Promise<{ invoices: Invoice[] }> => { const invoices: Invoice[] = []; // Every query filters on tenant_id, and the index leads with it. for await (const r of db.query<{ id: number; customer_id: number; amount_cents: number }>` SELECT id, customer_id, amount_cents FROM invoices WHERE tenant_id = ${tenant()} ORDER BY created_at DESC LIMIT 50`) { invoices.push({ id: r.id, customerId: r.customer_id, amountCents: r.amount_cents }); } return { invoices }; }, );

The auth handler is declared once and resolves the session to a tenant:

// auth/auth.ts import { APIError, Gateway, Header } from "encore.dev/api"; import { authHandler } from "encore.dev/auth"; interface AuthParams { authorization: Header<"Authorization">; } export interface AuthData { userID: string; tenantId: string; } export const auth = authHandler<AuthParams, AuthData>(async (params) => { // Replace with your own token check, for example a session lookup or a JWT. const session = await lookupSession(params.authorization); if (!session) throw APIError.unauthenticated("invalid session"); return { userID: session.userId, tenantId: session.tenantId }; }); export const gateway = new Gateway({ authHandler: auth }); async function lookupSession( header: string | undefined, ): Promise<{ userId: string; tenantId: string } | null> { // Verify the session token or JWT here and return null when it is missing or invalid. // Never accept a header without checking it, since the tenant comes from this result. throw new Error("lookupSession is not implemented"); }

encore run starts a local Postgres and applies the migration, so a test can create two tenants and check that the foreign key rejects a cross-tenant reference and that each tenant lists only its own invoices.

On deploy, the database runs on RDS or Cloud SQL as the AWS and GCP infrastructure docs describe. A coding agent adding a new tenant-owned table copies the pattern, tenant column, scoped key and tenant-first index, and the tests catch a missing filter locally.

Best fit: Teams building a SaaS product that start with a shared database and want the tenant boundary to be a property of the schema.

Things to decide early

  • Tenant ID type. UUIDs avoid guessable IDs and make moving a tenant to another database simple.
  • Big tenants. Plan how a tenant moves to its own database, which is easy when every table has the tenant column and keys include it.
  • Per-tenant limits. Rate limits and quotas per tenant stop one customer from using the shared database's capacity.
  • Deletion. Offboarding a tenant is a delete by tenant ID across every table, so keep a list of the tables and test it.

Frequently asked questions

What are the main multi-tenant database models?

There are three. A shared schema puts every tenant's rows in the same tables with a tenant ID column, a schema per tenant gives each customer its own set of tables in one database, and a database per tenant gives each customer a separate database. They trade isolation against cost and operational effort.

Which multi-tenant model should a SaaS startup start with?

Most start with a shared schema and a tenant ID on every table, because it is the cheapest to run and migrate. Add row-level security as a backstop, and move large or regulated customers to their own database later if they require it.

How do you stop a bug from leaking data between tenants?

Put the tenant ID in every primary key, unique constraint and foreign key, take it from the authenticated session rather than the request, and enforce it in the database with row-level security. Composite foreign keys also prevent a row in one tenant from referencing a row in another.

How do you build a multi-tenant backend with Encore?

With Encore, an auth handler returns the tenant ID in the auth data, and every endpoint reads it from there and passes it to queries on a Postgres database declared in the service. Encore provisions the database in your AWS or GCP account.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders