Web Development6 min read

Multi-tenant SaaS: shared database or one per customer?

A decision guide for founders and CTOs: shared schema or database per tenant, a comparison table, the hybrid exit path and the six row-level leaks to test for.

G George MihaylovPublished Updated
Rows of database servers in a data centre, lit by status lights
Photo by panumas nikhomkhai on Pexels

Start with a shared database and a tenant key on every customer-owned table, and build the application so that one large customer can later be moved to their own database. Choose separate databases from day one only when a contract or a regulator demands it. The shared model is cheaper to run and migrate; the separate model is easier to isolate and restore.

What are the three ways to store tenant data?

Shared database, shared schema. Every table that belongs to a customer carries a tenant_id column and every query filters on it. One database, one set of tables, one migration run per deploy.

Shared database, separate schemas. One server holds a schema per tenant. In practice this option carries the migration burden of separate databases while giving less isolation than buyers expect, so we rarely recommend it.

Database per tenant. Each customer gets a database of their own. A central table of tenants records which connection belongs to whom, and the application switches connection at the start of each request.

Shared database or separate database: the comparison

QuestionShared database, shared schemaDatabase per tenant
IsolationEnforced by application code. One missing where clause exposes another customer's rows.Enforced by the database boundary. A missing where clause shows nothing from other customers.
Running costOne database to host, tune and monitor.One database per customer. Backups, monitoring and connection limits grow with the customer count.
MigrationsOne migration run per deploy.One run per customer database, plus handling of partial failures.
Backup and restore per tenantFull backups are simple. Restoring one customer means extracting their rows from a full dump.Restore one database and the customer is back, with nobody else touched.
Noisy neighboursOne customer's heavy import or report slows everyone on the server.Heavy customers can be moved to their own server.
Compliance asksHarder to demonstrate isolation to an auditor. Data residency per customer needs a separate deployment anyway.Easy to show where a customer's data lives and to delete all of it.
Analytics across tenantsOne SQL query.Needs an export from every database into a reporting store.
Laravel toolingEloquent global scopes, tenant-scoped unique indexes, Tenancy for Laravel in single-database mode.Named connections in config/database.php, the --database option on migration commands, Tenancy for Laravel in multi-database mode.

The hybrid: shared schema with a tenant key and an exit door

The hybrid is the shared model plus a prepared route out. Every customer-owned table carries tenant_id. A central tenants table also stores a connection column; at launch every row says shared. At the start of each request the application resolves the tenant from the subdomain, path or login, reads that record, and uses whichever connection it names. In Laravel, any query can be sent to a named connection with DB::connection('name') or a model's $connection property.

What to decide before the first migration

  1. Put tenant_id on every table a customer owns, indexed, and first in composite indexes.
  2. Scope every unique index to the tenant: (tenant_id, slug), never (slug) alone.
  3. Use ULIDs or UUIDs for primary keys so rows copied into a separate database never collide.
  4. Never add a foreign key from one tenant's rows to another tenant's rows.
  5. Prefix file storage paths and cache keys with the tenant id.
  6. Make every queued job carry the tenant id and restore the tenant context before it runs.

How a large customer moves out

Create a new connection for the customer, then run the same migration files against it; Laravel's migration commands accept a --database option that names the connection to use. Copy every row where tenant_id matches, switch the tenant's connection value, verify the row counts, and only then delete the rows from the shared database. If the checklist above was followed, no application code changes.

Which row-level mistakes leak data between tenants?

In a shared schema every leak is the same bug: a query that forgot the tenant. It hides in six places.

  1. Route model binding. /invoices/{invoice} loads by primary key. Without a scope, any logged-in user can read any invoice by changing the number.
  2. Unscoped unique rules. A validation rule of unique:customers,email fails for tenant B because tenant A already has that address. The error message confirms the address exists somewhere in your system.
  3. Raw queries. Eloquent scopes do not touch DB::table() or raw SQL. The Tenancy for Laravel documentation says it plainly: "The package can only provide scoping logic for the abstraction logic that Eloquent is".
  4. Queued jobs and scheduled commands. They run with no request and therefore no current tenant. A nightly report job that loops over "all bookings" loops over everyone's bookings.
  5. Cache keys without a tenant. cache('dashboard_totals') serves tenant A's totals to tenant B.
  6. Public pages built from a different query. The profile page checks visibility, but the directory, sitemap or search index was written separately and shows accounts that should be hidden.

How global scopes close most of these gaps

The Laravel documentation defines them in one sentence: "Global scopes allow you to add constraints to all queries for a given model." A TenantScope class implements the Scope interface with one apply method that adds where tenant_id = ? for the current tenant. Attach it to each customer-owned model with the #[ScopedBy] attribute. First, when there is no current tenant, the scope should throw rather than return every row; a crash in staging beats a leak in production. Second, treat every withoutGlobalScope call as a code-review flag: it belongs in admin tooling and nowhere else.

Tests that fail when a scope is missing

Create two tenants with factories, log in as the first, and request the second tenant's record by id. Assert a 404, not a 403, so the response does not confirm the record exists. Repeat for every endpoint that takes an id. Laravel's RefreshDatabase trait keeps these fast: the database testing documentation notes that it "does not migrate your database if your schema is up to date. Instead, it will only execute the test within a database transaction."

How SoftBuildLab builds this in practice

Our booking platform REZVA is one Laravel application with one shared schema, serving beauty, wellness, fitness and lessons specialists in 83 countries and 26 languages. Each specialist is a tenant with a booking page, and clients find them in a public directory by trade and city. Hidden, inactive or incomplete accounts must never appear in public, so the specialist model has a single query scope, listed(), that holds every visibility rule in one place. The home page, the directory, the search and the sitemap all call that scope; none of them repeats the conditions. A feature test creates a hidden specialist and asserts that its slug appears on none of those pages. When a visibility rule changes, it changes once.

The same approach shapes client projects. During SaaS MVP development we add the tenant key, the connection column and the scope tests before the first feature. Plan limits and billing state are stored as tenant attributes, which keeps subscription billing separate from the data model. Our database design and multi-tenant SaaS architecture services cover the schema, the move-out procedure and the test suite, and the quote wizard returns a free technical proposal within 3 to 5 business days.

Frequently asked questions

When should a SaaS start with a database per tenant?

When the first paying customers already require it in writing: a public-sector tender, a healthcare or banking client, or a data-residency clause that keeps their data in a specific country. If none of your early prospects asks, start shared and keep the connection column, so the first one who asks can be moved without rewriting the application.

Does PostgreSQL row-level security replace Eloquent global scopes?

It complements them. Row-level security filters inside the database, so raw SQL and reporting tools are covered too, but it needs a session variable set on every connection, including queue workers. Global scopes give readable, testable rules in the application. Teams with strict compliance asks run both; most products start with scopes and tests.

How do you export or delete one customer's data in a shared database?

Every customer-owned table carries the tenant key, so an export is a loop over those tables with one where clause, written as an Artisan command and tested like any other feature. Deletion is the same loop in reverse, run inside a transaction, followed by removing the tenant's files and cache keys. Keep the list of tenant-owned tables in code so the loop never misses a new one.

G

George Mihaylov

Technical Lead

Leads the engineering work at SoftBuildLab: architecture, delivery and the technical proposals clients receive.

Project brief template (PDF)

Nine questions that make a quote accurate: goals, users, must-have features, integrations, data, budget band, timeline. Fill it in and send it with your request.

Working on something similar?

Describe it in six short steps and get a free technical proposal within 3 to 5 business days.

Get a Free Quote