Database Per Tenant vs Shared Schema: How to Choose

You are about to put a second company on a codebase that was built for one. Maybe it is a sister brand, maybe a large customer who wants their own space, maybe the group owner has bought another business and wants it on the same platform by next quarter. Before anyone writes a model, somebody has to decide where the wall between tenants goes.
The database per tenant vs shared schema question has a short answer and a long tail. The short answer is about leaks. The long tail is about what you pay afterwards: every migration, every connection and every report that needs a number across all tenants. This post is mostly about the second half, because the wall can force a second system that the first estimate leaves out. If you are still pricing the whole product, our breakdown of what a multi-tenant SaaS build costs in year one treats tenancy as the first line in that budget.
Database per tenant or a shared schema, in one paragraph
Share one schema when tenants are many, small and alike: it is cheaper, and one migration covers everyone. Give each tenant its own database when a leak between two of them would be a commercial problem. The price is that every migration runs once per tenant, connections multiply, and no group-wide question survives a single JOIN.
The deciding question is not scale. It is what happens on the day one query forgets its tenant filter. If the answer is "a customer sees another customer's invoice and we apologise", a shared schema with an engine-level guard rail is fine. If the answer is "one of our companies reads a sister company's cost sheet and the group has a problem", the wall belongs in infrastructure, not in a WHERE clause.
The second question is how many tenants you will ever have. A SaaS roster that grows by the week pushes you toward sharing, because a database per tenant means a database per signup. A fixed group of four or five companies, known on day one, pushes the other way, because the per-tenant overhead is multiplied by a small number that never moves.
What is multi-tenancy in a database?
Multi-tenancy in a database means one application serves several customers or companies, called tenants, while keeping each one's data apart. There are three common models: a shared schema with a tenant id column on every table, a separate schema per tenant inside one database, and a separate database per tenant. They differ in where the wall sits.
Model | Where the wall is | Migrations | A group-wide total | MySQL |
|---|---|---|---|---|
Shared schema, tenant column | A filter in every query | Run once | One query | Available |
Schema per tenant | A namespace inside one database | Run once per tenant | Possible across schemas | Not a separate option |
Database per tenant | A separate database | Run once per tenant | Needs a pipeline | Available |
The middle row does not exist on MySQL. The MySQL 8.4 Reference Manual, read 2026-11-30, says it in one line: "CREATE SCHEMA is a synonym for CREATE DATABASE". On MySQL a schema is a database, so "schema per tenant" and "database per tenant" are the same build, and a team that picked the middle pattern because it sounded lighter has in fact picked the heaviest one. Of the five comparison pages we read on 2026-11-30 for this keyword (Bytebase, a dev.to practitioner post, two Microsoft Azure guides and the Citus documentation), none mentions MySQL at all, measured on the raw HTML of each.
On PostgreSQL the three models really are three. A schema is a namespace inside one database, and the wall between schemas is a matter of privileges and search_path. The wall between databases is harder: PostgreSQL's own documentation on schemas, read 2026-11-30, states that "A client connection to the server can only access data in a single database, the one specified in the connection request." That one sentence is both the benefit and the cost of a database per tenant, and the rest of this post is about the cost.
Why give each tenant its own database instead of a tenant column?
Because a shared table with a tenant filter puts every future query one mistake away from showing one tenant's rows to another. A separate database turns isolation into a property of the connection rather than a habit of the developer, and it gives each tenant its own backup, restore and retention without touching the others.
Picture the failure. A developer adds a report six months after launch. It joins three tables, filters the first by tenant and forgets the other two. In a shared schema, that query returns rows from every tenant and nobody notices until a customer does. In a database per tenant, the same query runs against one tenant's database and the forgotten filters cost nothing, because there is no other tenant's data on that connection to leak.
Three more things come with the wall, and they matter more for a group of related companies than for a SaaS roster:
Restore one tenant without touching the rest. If one company's data is damaged by a bad import, you restore that database. In a shared schema you restore a point in time for everyone or you write a careful row-level repair.
A contract can say where one tenant's data lives. A separate database can sit in the region that contract names without moving anyone else.
Noisy neighbours stay in their own room. Microsoft's Azure architecture guide on tenancy models, read 2026-11-30, lists the noisy neighbour problem as something separate deployments reduce. A heavy nightly import for one tenant does not slow a page load for another when they sit on separate databases, and better still when they sit on separate servers.
Separation stays cheap later. If one tenant is sold or leaves, its data already sits in its own database, so handing it over is a copy. If your customers can demand their data on exit, which the EU Data Act's switching rules now require of cloud services, that difference is the size of the project.
None of this replaces testing. The same Azure guide closes on an instruction worth pinning above any tenancy design: "be sure to test your solution to verify that one tenant's data isn't accidentally leaked to another". If a buyer later asks for a SOC 2 Type II report, that test is the evidence you will be glad you already have.

What a database per tenant costs you after you choose it
Three costs arrive after launch, and each is multiplied by the number of tenants: migrations, connections and cross-tenant questions. None of them is a reason to avoid the model. All of them belong in the estimate before the wall goes up.
Every migration runs once per tenant. Django's documentation on multiple databases, read 2026-11-30, is plain about it: "The migrate management command operates on one database at a time." With four tenants, a release that changes the schema is four migrations. The real risk is the third one failing. You now have two tenants on the new schema, two on the old one, and one codebase that has to serve both until you fix it. That is why the migration loop below stops at the first failure, and why expand and contract migrations, where the old and new shapes coexist for a while, matter more here than in a single database.
Connections multiply. Do this arithmetic with your own numbers, not ours. Django's database reference, read 2026-11-30, says "Since each thread maintains its own connection, your database must support at least as many simultaneous connections as you have worker threads." That sentence assumes one database. With persistent connections, a thread keeps one connection per database alias it has used, so the ceiling becomes threads times tenants. Take an example with stated inputs: 3 application servers running 8 worker threads each is 24 threads. On a shared schema, that is up to 24 connections. With 4 tenant databases on the same server, it is up to 96. Add 2 background workers with a concurrency of 4, which is 8 more threads, or 32 more connections across 4 tenants, and you are at 128. MySQL 8.4's documented default for max_connections is 151, so that fits with little room. PostgreSQL's documentation says its default is typically 100 connections, so the same setup is already over the default before a single admin opens a console. Put each tenant on its own server and each server only sees 32. Replace any input above with yours; the multiplication is the point.
No cross-tenant question survives a JOIN. "What did the whole group sell last month?" was one query in a shared schema. Now it is four queries, four connections, and a merge in application code. Django will not help you join across them: its documentation states "Django doesn't currently provide any support for foreign key or many-to-many relationships spanning multiple databases." The honest fix is a second system, covered two sections down.
Routing each Django request to its tenant database
In Django, a database per tenant is a database router plus something that tells the router which tenant the current request belongs to. The router below reads the tenant from a context variable that a middleware sets from the request's host name, refuses to run any query when no tenant is set, and keeps relations inside one database. If you are new to the framework, start with what Django is and what it is used for.
# tenancy.py
from contextlib import contextmanager
from contextvars import ContextVar
from django.http import HttpResponseNotFound
TENANT_HOSTS = {
"north.example.com": "tenant_north",
"south.example.com": "tenant_south",
}
_current = ContextVar("tenant_db", default=None)
@contextmanager
def tenant(alias):
token = _current.set(alias)
try:
yield
finally:
_current.reset(token)
class TenantMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
alias = TENANT_HOSTS.get(request.get_host().split(":")[0])
if alias is None:
return HttpResponseNotFound("unknown tenant")
with tenant(alias):
return self.get_response(request)
class TenantRouter:
def _alias(self):
alias = _current.get()
if alias is None:
raise RuntimeError("no tenant set; refusing to guess a database")
return alias
def db_for_read(self, model, **hints):
return self._alias()
def db_for_write(self, model, **hints):
return self._alias()
def allow_relation(self, obj1, obj2, **hints):
return obj1._state.db == obj2._state.db
def allow_migrate(self, db, app_label, **hints):
return db in TENANT_HOSTS.values()
In settings, DATABASES gets one entry per tenant alias, default is left as an empty dictionary so nothing can fall through to it, MIDDLEWARE lists tenancy.TenantMiddleware above SessionMiddleware, so a session saved on the way out still knows its tenant, and DATABASE_ROUTERS is ["tenancy.TenantRouter"]. Background jobs and scripts wrap their work in with tenant("tenant_north"):, so a job that forgets to say which tenant it is for fails loudly instead of writing to whichever database it guessed.
The migration loop is a management command, so it runs the same way on a laptop and in a deploy:
# yourapp/management/commands/migrate_tenants.py
from django.core.management import BaseCommand, call_command
from tenancy import TENANT_HOSTS
class Command(BaseCommand):
def handle(self, *args, **options):
for alias in sorted(set(TENANT_HOSTS.values())):
self.stdout.write(f"migrating {alias}")
# raises on failure, so the loop stops at the first broken tenant
call_command("migrate", database=alias, interactive=False, verbosity=0)
Two design choices are doing the work here. The router raises instead of defaulting, because a silent default is exactly the shared-schema leak you built the wall to avoid. And the loop stops at the first failure, because carrying on means more tenants on a schema you now know is broken. We ran both files on Django 5.2 against two SQLite tenant databases: a row written through the north host was invisible through the south host, an unknown host returned 404, a query with no tenant set raised, and a migration loop pointed at an unreadable north database exited with status 1 before it touched south. Swap the engine for MySQL or PostgreSQL in DATABASES and nothing else changes.
The wall is not only the database
A database per tenant isolates rows. It does not isolate uploaded files, cached values, queued jobs or scheduled tasks, and each of those needs its own tenant namespace or the wall has a hole that no database review will find.
Media. If every tenant uploads to one bucket under one prefix, a guessed or reused file key serves one tenant's document to another. Give each tenant its own bucket, or at least its own prefix with access scoped to it.
Cache. A cache key like dashboard:summary built without the tenant in it will happily serve one company's summary to the next company that asks. Prefix every key with the tenant, or give each tenant its own cache namespace.
Queues and scheduled jobs. A job pulled off a queue runs outside any request, so the middleware above never sees it. The job must carry its tenant as an argument and set it before touching a model. Scheduled jobs are worse: a nightly task written for one tenant quietly runs for none of the others, or for all of them against one database.
A word of caution on Redis, because it is often where teams put that cache and queue namespace. Redis lets you select numbered databases on one server, but its own documentation on the SELECT command, read 2026-11-30, describes them as namespacing, notes that "all databases are still persisted in the same RDB or AOF file", and says "Redis Cluster only supports database zero". So a Redis database number separates keys within one application, which is what you want here, but it is not a security boundary and it will not survive a move to Redis Cluster. Plan the key prefix as the durable answer.
Feature switches are the last surface people forget. When a contract lets one tenant opt out of something, switching an AI feature off for one tenant is a per-tenant setting that has to live somewhere the router can see it.
How do you report across tenants once they are separate?
You copy each tenant's data into one warehouse, add the tenant as a column on the way in, and run group reports there instead of against the tenant databases. The warehouse is a second system with its own lag, so every report has to say when it last loaded, and every number has to be computed in one place.
The pages we read give this question very little room. Of the five comparison pages we read on 2026-11-30, none names a data warehouse, measured on raw HTML, and the two Microsoft guides raise reporting across tenants in one or two sentences each. The Azure tenancy models guide says "Plan for how you can query and manipulate data across multiple deployments." It does not say what that plan costs, and that cost is the bill that arrives later.

One pull per tenant, the same definitions for all of them. The pipeline reads each tenant database with the same extraction code and writes into shared warehouse tables keyed by tenant. If "net sales" is defined in the pipeline, it is defined once. If it is defined in each report, it will drift, and two dashboards will disagree about the same month. That problem is not unique to tenancy; definitions are the actual project in any dashboard build. Tenancy just guarantees you will have it.
Lag is now a feature of every number. The group report is as fresh as the last load. Show the load time on the report, or someone will compare a live tenant screen with a warehouse figure from last night and file a bug.
It also protects the operational database. Analytical scans that read months of history compete with the writes your application needs. Moving group analysis to a warehouse takes that load off the tenant databases, which is a reason to build it even when there is only one tenant.
When the shared schema is the right answer
A shared schema is right when tenants are many, small and similar, when one tenant seeing another's data would be a bug rather than a breach between companies, and when you need group-wide numbers often. On PostgreSQL, make the tenant filter an engine rule with row level security rather than a habit every query has to remember.
Row level security moves the tenant filter out of application code and into a policy on the table. It has a safe default: PostgreSQL's documentation on row security policies, read 2026-11-30, states that "If no policy exists for the table, a default-deny policy is used", so a table with security enabled and no policy returns nothing rather than everything.
Check who your application connects as before you trust it. The same page says "Superusers and roles with the BYPASSRLS attribute always bypass the row security system when accessing a table." and "Table owners normally bypass row security as well". Many web applications connect as the role that ran the migrations, which owns every table. In that setup the policies exist, the tests that use a different role pass, and production ignores all of it. Either connect as a separate role that does not own the tables, or use ALTER TABLE ... FORCE ROW LEVEL SECURITY, which the documentation names as the way a table owner opts in.
The shared schema also wins whenever the tenant count is large or unknown. It can also grow past one server: the Citus documentation, read 2026-11-30, advises partitioning distributed tables by a common tenant_id column. Running a database per signup means provisioning, migrating, backing up and monitoring thousands of databases, which is a platform team's full-time job. If your plan is a self-serve product, share the schema, add row level security on day one, and move only the tenants who pay for isolation onto their own databases later. Moving one tenant out of a shared schema is an extraction: every table filtered by tenant id, every file and cache key found and moved. Plan for it as a project, not a script, with the same care as a migration you might need to roll back.
How we drew the wall on an apparel platform
Stylebank runs four apparel businesses on one Django codebase, and we built it as a dedicated team. We chose a database per tenant rather than a tenant column, and rejected one database with row level filtering on a tenant id. The reason recorded in the Stylebank case study is short: separate factories and books, and per-tenant ETL heavy enough that one should not slow another.
The wall covers more than rows. Each tenant runs on its own MySQL database, its own S3 bucket and its own Redis database number, so records, media and queues never share a namespace. Because it is MySQL, that is also schema per tenant, since on MySQL the two are the same thing. The project is nine Django apps with fifteen external systems integrated, and those are scope figures, not results.
We accepted the costs when we chose. Every migration runs four times, connection pools multiply, and no cross-tenant question survives a JOIN. Those are the three costs described above, and they are costs we took on, not outcomes we are claiming. We publish no performance or savings figure for this build.
The group report went to a warehouse. We put analysis in BigQuery and kept MySQL for operations, because the operational database carries a large append-only history stream and analytical scans would compete with the write path. The trade we accepted is the one in the reporting section: a second copy with its own lag, and two places a number could be computed, so the definitions are pinned in the pipeline.
Separation stayed cheap. Because isolation is physical rather than a query filter, separating one business is a copy, not an extraction. For any group whose companies might one day be sold or split, that difference is worth weighing against the four migrations. The same tenancy question comes up early in any garment ERP for a group of apparel businesses, and in education, where multi-tenancy for a group of schools has the same fixed, known tenant count. If you are weighing it for your own platform, our Django development team starts with where the wall goes and what the reporting will cost on the other side of it.
The wall is a one-time decision with a recurring bill. A shared schema bills you in risk on every query you will ever write. A database per tenant bills you in migrations, connections and a warehouse. Pick the bill you can see coming, and put the second system in the estimate before the first one is built.
Frequently asked questions
Neither is better in general. A database per tenant is better when tenants are few and fixed, and a leak between them would be a commercial problem, for example sister companies in one group. A shared schema is better when tenants are many, small and alike, such as a self-serve SaaS product, because one migration covers everyone and a group-wide total is a single query. The cost of a database per tenant is that every migration runs once per tenant, connections multiply, and reporting across tenants needs a warehouse.
A schema is the structure: the tables, columns, keys and other objects that define how data is organised. An instance is the running database server and the data it holds at a given moment. The word schema also has an engine-specific meaning, which matters for tenancy. On PostgreSQL a schema is a namespace inside one database, so schema per tenant is a real middle option. On MySQL, the 8.4 Reference Manual states that CREATE SCHEMA is a synonym for CREATE DATABASE, so a schema per tenant on MySQL is simply a database per tenant.
Not as a separate pattern. The MySQL 8.4 Reference Manual, read on 2026-11-30, says CREATE SCHEMA is a synonym for CREATE DATABASE, so creating one schema per tenant on MySQL creates one database per tenant, with every cost that brings: a migration per tenant, more connections and no JOIN across tenants. If you want a lighter middle option, it exists on PostgreSQL, where a schema is a namespace inside one database. On MySQL the real choice is between a shared schema with a tenant column and a database per tenant.
Only if your application connects as the right role. PostgreSQL's documentation states that superusers and roles with the BYPASSRLS attribute always bypass row security, and that table owners normally bypass it too. Many applications connect as the role that ran the migrations and owns every table, which means the policies are ignored in production. Connect as a separate role that does not own the tables, or use ALTER TABLE with FORCE ROW LEVEL SECURITY. With that settled, a table with security enabled and no policy defaults to showing no rows.
Work it out from your own numbers. Django's documentation says each thread maintains its own connection, so a single database needs at least as many connections as you have worker threads. With persistent connections, each thread can hold one connection per tenant database it has used, so the ceiling is threads multiplied by tenants on that server. For example, 24 web threads and 8 background threads across 4 tenant databases on one server could reach 128 connections. MySQL 8.4 defaults to 151 and PostgreSQL typically to 100, so check before you deploy.
Django's migrate command operates on one database at a time, so you call it once per tenant with the database option. The safest way is a small management command that loops over the tenant aliases and calls migrate for each one, stopping at the first failure. Stopping matters: if the third of four tenants fails, carrying on leaves you with tenants on different schema versions and one codebase that has to serve both. Pair it with expand and contract migrations so the old and new shapes can coexist while the loop runs.
Yes, but plan it as a project. Moving one tenant out of a shared schema is an extraction: you copy every row filtered by that tenant's id from every table, check that no foreign key points at another tenant's rows, and move the tenant's files, cache keys and queued jobs to their new namespace. It is easier if every table carried the tenant id from the start and every file and cache key was already prefixed by tenant. Going the other way, separating one tenant from a database per tenant setup is a copy, because its data already sits apart.

Vikas Choudhary
Vikas has around fifteen years of experience building software and now builds generative AI systems at Zyneto. His work covers retrieval augmented generation, agentic AI, knowledge graphs, AI memory, and the evaluation and guardrails that decide whether any of it is safe to put in front of customers. He has shipped enterprise copilots, document AI, chatbots and predictive analytics for e-commerce, fintech and marketing teams, and works day to day in Python, JavaScript and SQL. He follows multimodal models, business process automation and enterprise AI security closely, and mentors engineers moving into AI. He writes about architecture, inference cost and the failure modes that only show up at production scale.
Zyneto builds custom software, AI and automation
Tell us what you are building and we will reply with a clear next step.









