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.

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.
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.
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.
tenant_id column, including join tables.(tenant_id, id) or keep a global ID and add a unique (tenant_id, id) for foreign keys to reference.invoices to customers should include tenant_id, so an invoice cannot point at another tenant's customer.UNIQUE (tenant_id, email).(tenant_id, created_at), not (created_at), so queries touch one tenant's rows.WHERE in application code returns nothing instead of everything. See Postgres row-level security for multi-tenant apps for the policy setup.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.
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.

Run in your terminal to get started locally.
-- 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);
// 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.
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.
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.
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.
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.