Database Design Patterns · Lesson 77 of 112

Database Multi-tenant Designs

What you will learn

  • What multi-tenancy means
  • The main designs: shared tables and separate databases
  • How a tenant_id column can fail, and a composite foreign key that prevents one failure
  • The trade-offs

A tenant is one customer organisation using your software (a shop, a school, a clinic). Multi-tenant software serves many tenants at once, and the law of the land is simple: no tenant may ever see or change another tenant's data.

1. Design A: shared tables with a tenant id

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds small tables of its own (prefix t_, so they cannot clash with real ones) to your browser's copy; run the examples from top to bottom, and Reset data starts again.

All tenants live in the same tables, and every row says whose it is.

CREATE TABLE tenants (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO tenants VALUES (1, 'Shop A'), (2, 'Shop B');
CREATE TABLE t_customers (id INTEGER PRIMARY KEY, tenant_id INTEGER NOT NULL REFERENCES tenants (id), name TEXT);
INSERT INTO t_customers VALUES (1, 1, 'Rina'), (2, 2, 'Lee'), (3, 1, 'Sam');
SELECT name FROM t_customers WHERE tenant_id = 1 ORDER BY id;
SELECT name FROM t_customers WHERE tenant_id = 2 ORDER BY id;
name
----
Rina
Sam
(2 rows)

name
----
Lee
(1 row)

If the filter is forgotten:

SELECT name FROM t_customers ORDER BY id;
name
----
Rina
Lee
Sam
(3 rows)
CREATE TABLE tenants (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO tenants VALUES (1, 'Shop A'), (2, 'Shop B');
CREATE TABLE t_customers (id INTEGER PRIMARY KEY, tenant_id INTEGER NOT NULL REFERENCES tenants (id), name TEXT);
INSERT INTO t_customers VALUES (1, 1, 'Rina'), (2, 2, 'Lee'), (3, 1, 'Sam');
SELECT name FROM t_customers WHERE tenant_id = 1 ORDER BY id;
SELECT name FROM t_customers WHERE tenant_id = 2 ORDER BY id;
name
----
Rina
Sam
(2 rows)

name
----
Lee
(1 row)

If the filter is forgotten:

SELECT name FROM t_customers ORDER BY id;
name
----
Rina
Lee
Sam
(3 rows)
CREATE TABLE tenants (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO tenants VALUES (1, 'Shop A'), (2, 'Shop B');
CREATE TABLE t_customers (id INTEGER PRIMARY KEY, tenant_id INTEGER NOT NULL REFERENCES tenants (id), name TEXT);
INSERT INTO t_customers VALUES (1, 1, 'Rina'), (2, 2, 'Lee'), (3, 1, 'Sam');
SELECT name FROM t_customers WHERE tenant_id = 1 ORDER BY id;
SELECT name FROM t_customers WHERE tenant_id = 2 ORDER BY id;
name
----
Rina
Sam
(2 rows)

name
----
Lee
(1 row)

If the filter is forgotten:

SELECT name FROM t_customers ORDER BY id;
name
----
Rina
Lee
Sam
(3 rows)

Each tenant sees only its own rows if every query filters on tenant_id. One forgotten filter leaks everything (last result). Ways to reduce the risk: a data-access layer that adds the filter automatically, views per tenant, and, in some systems, built-in row-level security that enforces the filter inside the database (support and syntax differ by product; check the documentation of yours).

Quick check: In a shared table with a tenant_id column, what is the most dangerous mistake in a query?

Forgetting to filter on tenant_id, which returns other customers' rows and leaks their data.

The filter is not the only risk. A foreign key proves a customer exists, but not that it belongs to the same tenant:

CREATE TABLE t_orders (
  id INTEGER PRIMARY KEY, tenant_id INTEGER NOT NULL REFERENCES tenants (id),
  customer_id INTEGER NOT NULL REFERENCES t_customers (id), total INTEGER);
INSERT INTO t_orders VALUES (1, 2, 1, 500);
SELECT o.tenant_id AS order_tenant, c.tenant_id AS customer_tenant
FROM t_orders o JOIN t_customers c ON c.id = o.customer_id;
order_tenant  customer_tenant
------------  ---------------
           2                1
(1 row)
CREATE TABLE t_orders (
  id INTEGER PRIMARY KEY, tenant_id INTEGER NOT NULL REFERENCES tenants (id),
  customer_id INTEGER NOT NULL REFERENCES t_customers (id), total INTEGER);
INSERT INTO t_orders VALUES (1, 2, 1, 500);
SELECT o.tenant_id AS order_tenant, c.tenant_id AS customer_tenant
FROM t_orders o JOIN t_customers c ON c.id = o.customer_id;
order_tenant  customer_tenant
------------  ---------------
           2                1
(1 row)
CREATE TABLE t_orders (
  id INTEGER PRIMARY KEY, tenant_id INTEGER NOT NULL REFERENCES tenants (id),
  customer_id INTEGER NOT NULL REFERENCES t_customers (id), total INTEGER);
INSERT INTO t_orders VALUES (1, 2, 1, 500);
SELECT o.tenant_id AS order_tenant, c.tenant_id AS customer_tenant
FROM t_orders o JOIN t_customers c ON c.id = o.customer_id;
order_tenant  customer_tenant
------------  ---------------
           2                1
(1 row)

A Shop B order points at Shop A's customer 1, and the database accepted it. The fix: make the foreign key include the tenant. First the parent needs a unique pair (tenant_id, id), then the child references the pair:

DROP TABLE t_orders;
DROP TABLE t_customers;
CREATE TABLE t_customers (
  id INTEGER PRIMARY KEY, tenant_id INTEGER NOT NULL REFERENCES tenants (id), name TEXT,
  UNIQUE (tenant_id, id));
INSERT INTO t_customers VALUES (1, 1, 'Rina'), (2, 2, 'Lee'), (3, 1, 'Sam');
CREATE TABLE t_orders (
  id INTEGER PRIMARY KEY, tenant_id INTEGER NOT NULL, customer_id INTEGER NOT NULL, total INTEGER,
  FOREIGN KEY (tenant_id, customer_id) REFERENCES t_customers (tenant_id, id));
INSERT INTO t_orders (tenant_id, customer_id, total) VALUES (1, 1, 500);
(1 row changed)

Tenant 2 tries to use customer 1, who belongs to tenant 1:

INSERT INTO t_orders (tenant_id, customer_id, total) VALUES (2, 1, 500);
IntegrityError: FOREIGN KEY constraint failed
DROP TABLE t_orders;
DROP TABLE t_customers;
CREATE TABLE t_customers (
  id INTEGER PRIMARY KEY, tenant_id INTEGER NOT NULL REFERENCES tenants (id), name TEXT,
  UNIQUE (tenant_id, id));
INSERT INTO t_customers VALUES (1, 1, 'Rina'), (2, 2, 'Lee'), (3, 1, 'Sam');
CREATE TABLE t_orders (
  id INTEGER PRIMARY KEY, tenant_id INTEGER NOT NULL, customer_id INTEGER NOT NULL, total INTEGER,
  FOREIGN KEY (tenant_id, customer_id) REFERENCES t_customers (tenant_id, id));
INSERT INTO t_orders (tenant_id, customer_id, total) VALUES (1, 1, 500);
(1 row changed)

Tenant 2 tries to use customer 1, who belongs to tenant 1:

INSERT INTO t_orders (tenant_id, customer_id, total) VALUES (2, 1, 500);
IntegrityError: FOREIGN KEY constraint failed
DROP TABLE t_orders;
DROP TABLE t_customers;
CREATE TABLE t_customers (
  id INTEGER PRIMARY KEY, tenant_id INTEGER NOT NULL REFERENCES tenants (id), name TEXT,
  UNIQUE (tenant_id, id));
INSERT INTO t_customers VALUES (1, 1, 'Rina'), (2, 2, 'Lee'), (3, 1, 'Sam');
CREATE TABLE t_orders (
  id INTEGER PRIMARY KEY, tenant_id INTEGER NOT NULL, customer_id INTEGER NOT NULL, total INTEGER,
  FOREIGN KEY (tenant_id, customer_id) REFERENCES t_customers (tenant_id, id));
INSERT INTO t_orders (tenant_id, customer_id, total) VALUES (1, 1, 500);
(1 row changed)

Tenant 2 tries to use customer 1, who belongs to tenant 1:

INSERT INTO t_orders (tenant_id, customer_id, total) VALUES (2, 1, 500);
IntegrityError: FOREIGN KEY constraint failed

Now the database itself refuses a link across tenants. (Lesson 3.1 covers foreign keys, and SQLite needs PRAGMA foreign_keys = ON, which these cells already do.)

3. Design B: one database per tenant

Each tenant gets its own database (in SQLite, its own file), and the application opens the right one.

import os, tempfile
d = tempfile.mkdtemp()
for name in ["shop_a", "shop_b"]:
    c = sqlite3.connect(os.path.join(d, name + ".db"))
    c.execute("CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT)")
    c.execute("INSERT INTO customers (name) VALUES (?)", (name + " customer",))
    c.commit()
    c.close()
print(sorted(os.listdir(d)))

def open_tenant(name):
    return sqlite3.connect(os.path.join(d, name + ".db"))

print(open_tenant("shop_a").execute("SELECT * FROM customers").fetchall(), open_tenant("shop_b").execute("SELECT * FROM customers").fetchall())
['shop_a.db', 'shop_b.db']
[(1, 'shop_a customer')] [(1, 'shop_b customer')]

A forgotten filter cannot leak, because each connection only contains one tenant. Many systems offer a middle path, one schema per tenant inside one database server (lesson 2.8), with its own rules; check what yours supports.

4. Trade-offs

Shared tables + tenant_id Separate database (or schema) per tenant
Isolation by discipline and constraints strong, built in
Cost per tenant tiny larger: more files, connections, upgrades
Many small tenants easy heavy
Backup or delete one tenant needs filtering copy or drop one database
Schema change once repeated for every tenant (lesson 8.7)
Cross-tenant reports easy need extra work
One tenant's heavy load affects others easier to isolate

Worked example: a booking app for tailor shops

The product expects hundreds of small shops, each with a few thousand rows, and one bigger customer chain that demands its data be kept separate. Plan: shared tables with tenant_id and composite foreign keys for the many small shops (cheap to run and upgrade), and a separate database for the chain (isolation it can show its auditors). The application chooses the connection from the logged-in tenant, never from a value in the request. All names are made up.

Common mistakes

  • Trusting a tenant_id sent by the browser. Always take it from the authenticated session (lesson 8.4).
  • Forgetting the filter in one query, report or background job.
  • Plain foreign keys that allow links across tenants.
  • Unique rules without the tenant (two shops cannot both have an invoice number 1001 if it is unique globally). Make uniqueness per tenant: UNIQUE (tenant_id, invoice_no).
  • Choosing separate databases for 10,000 tiny tenants and drowning in upgrades.

Key takeaways

  • Multi-tenant software must never mix tenants' data.
  • Shared tables are cheap but rely on filters and constraints; every query needs tenant_id.
  • Use composite foreign keys (tenant_id, id) to block cross-tenant links.
  • Make uniqueness rules per tenant.
  • A separate database per tenant isolates strongly at higher operating cost.

Practice

1. What is a tenant?

Show answer

One customer organisation using the shared software, whose data must stay separate from other tenants'.

2. In shared tables, what single mistake leaks data between tenants?

Show answer

A query that does not filter on tenant_id.

3. Why did the plain foreign key accept an order for the wrong tenant?

Show answer

It only checked that the customer id existed, not that the customer belonged to the same tenant.

4. Write the idea of the fix in one sentence.

Show answer

Make the parent unique on (tenant_id, id) and have the child reference that pair, so tenant must match.

5. Invoice numbers restart at 1 for each shop. How do you define uniqueness?

Show answer

UNIQUE (tenant_id, invoice_no), not UNIQUE (invoice_no).

6. When would you choose a separate database per tenant?

Show answer

When a tenant needs strong isolation, separate backups or deletion, or heavy dedicated load, and the number of tenants is small enough to operate.