How to build a multi-database SaaS app with Laravel

A comprehensive practical guide to building a multi-database Laravel SaaS app, including architecture, tenant provisioning, billing, queues, testing, and production operations.

R
Raşit Apalak
·
·
Updated
·
7 min read

Quick Answer

Quick answer: How to build a multi-database SaaS app with Laravel

A comprehensive practical guide to building a multi-database Laravel SaaS app, including architecture, tenant provisioning, billing, queues, testing, and production operations.

See supporting documentation

How to build a multi-database SaaS app with Laravel

Multi-database tenancy is one of the most reliable ways to isolate customer data in a Laravel SaaS product. Instead of storing all tenants in shared tables, each tenant gets a dedicated database while central platform data stays in a shared "control plane" database.

This guide walks through a production-focused approach to build it step by step.

Who should use multi-database tenancy?

Choose multi-database when one or more of these are true:

  • enterprise customers require stronger physical data isolation
  • you need per-tenant backup and restore workflows
  • high-value customers need maintenance or migration windows independent of others
  • risk posture favors reducing cross-tenant blast radius

If you are still pre-PMF and optimizing for speed, single-database tenancy is usually the better first step.

Architecture overview

A practical Laravel multi-database SaaS has two contexts:

ContextPurposeTypical tables
Central databaseApp control plane and account lifecycleusers, tenants, domains, plans, subscriptions, invitations, audit metadata
Tenant databaseTenant-owned business dataprojects, tasks, invoices, domain-specific entities

Think of the central DB as your "tenant router + billing brain", and tenant DBs as isolated data planes.

Step 1: Define your tenant identity and routing model

Before coding, define how requests resolve a tenant:

  • subdomain-based (acme.yourapp.com)
  • custom domain-based (app.acme.com)
  • path-based (usually less preferred for B2B SaaS)

Your tenant resolver should run early in request lifecycle and produce a single trusted tenant context object.

Step 2: Model central entities first

Create a clear central schema:

  • tenants
  • domains (or host mappings)
  • users
  • membership/pivot tables (if users can belong to many tenants)
  • billing entities (plans, subscriptions, provider references)

Recommended columns in tenants:

  • stable internal ID (UUID/ULID)
  • machine-safe slug
  • lifecycle state (provisioning, active, suspended, deleting)
  • metadata (JSON) for low-risk operational config

Step 3: Introduce tenancy infrastructure

Most Laravel teams use tenancy tooling such as stancl/tenancy to handle:

  • tenant identification
  • connection switching
  • tenant bootstrap lifecycle
  • optional per-tenant cache/filesystem/queue isolation

You can build a custom tenancy layer, but package-driven lifecycle hooks reduce edge-case bugs significantly.

Step 4: Configure connection strategy

Use separate connection definitions for central and tenant contexts.

Example concept:

  • central connection for authentication, tenant lookup, billing
  • tenant connection template dynamically pointed at tenant DB

Keep one rule absolute:

  • no tenant business query runs until tenant context is resolved and tenant connection is initialized

Step 5: Build tenant provisioning pipeline

Treat tenant creation as an orchestrated workflow, not a single controller action.

Typical pipeline:

  1. create central tenant record with provisioning status
  2. create tenant database
  3. run tenant migrations
  4. seed minimum tenant data (roles, default settings)
  5. attach owner membership
  6. mark tenant active
  7. emit provisioning-completed event

Make provisioning idempotent

Provisioning jobs can fail midway. Design jobs so retries do not duplicate side effects.

Examples:

  • "create DB if not exists" checks
  • "seed if missing key records" checks
  • state transitions guarded by expected current state

Step 6: Separate central and tenant migrations

Maintain explicit migration boundaries:

  • central migrations in one path/folder
  • tenant migrations in another path/folder

Operationally this enables:

  • independent migration commands
  • safer rollout controls
  • better troubleshooting when a tenant-specific migration fails

Step 7: Build auth and membership flow intentionally

Common production model:

  • user identity exists in central DB
  • users are members of one or multiple tenants
  • active tenant context determines which tenant DB is used

For multi-tenant B2B apps, add roles at tenant/workspace scope (owner, admin, member) and keep authorization policy-based.

Step 8: Billing in a multi-database architecture

Keep billing source of truth in the central database.

Why:

  • plans/subscriptions are account-level platform concerns
  • webhooks are easier to process centrally
  • reconciliation and support tooling stay simpler

Recommended flow:

  1. tenant signs up centrally
  2. tenant DB is provisioned
  3. checkout/session is created (Stripe/Cashier or alternative)
  4. webhook updates central subscription state
  5. tenant access is enabled/disabled via central subscription gates

Do not spread billing truth between central and tenant DBs.

Step 9: Queue, jobs, and scheduled tasks

Queue safety is where many tenancy bugs happen.

Rules:

  • every tenant-scoped job payload must include tenant identifier
  • worker bootstrap must restore tenant context before executing tenant logic
  • central jobs and tenant jobs should be distinguishable by queue names/tags

Useful conventions:

  • queue names like central-default, tenant-high, tenant-low
  • job middleware that fails fast when tenant context is missing
  • logs that include tenant_id for every tenant job

Step 10: Cache, files, and search isolation

Beyond database isolation, isolate other surfaces:

  • cache keys prefixed by tenant ID
  • storage paths bucketed per tenant
  • search indexes scoped by tenant ID

This prevents accidental cross-tenant leakage through non-DB systems.

Step 11: Observability and auditability

For each request/job, include:

  • request ID
  • tenant ID
  • user ID (if authenticated)

Track:

  • tenant-level latency and error rates
  • provisioning failures by step
  • migration status per tenant
  • billing-to-access state mismatches

These signals reduce mean-time-to-diagnosis when issues occur in production.

Step 12: Testing strategy that catches real tenancy bugs

A good test plan includes all three layers:

1) Central tests

  • tenant registration and provisioning start
  • domain routing and tenant identification
  • billing webhook handling

2) Tenant-context tests

  • tenant-scoped CRUD in isolated databases
  • authorization with tenant roles
  • job execution with restored tenant context

3) Cross-tenant safety tests

  • Tenant A cannot read/update/delete Tenant B data
  • cache/files/storage boundaries are enforced
  • resolver rejects unknown/misconfigured domains safely

Add at least one CI suite that runs tenant provisioning and a representative tenant migration set.

Step 13: Deployment and operations checklist

Before production:

  • database user privileges verified for tenant DB create/migrate lifecycle
  • backup policy for both central and tenant databases documented
  • per-tenant restore runbook tested
  • retry-safe provisioning workers deployed
  • webhook reliability and replay handling tested
  • alerting in place for provisioning and billing failures

Ongoing operations

  • monitor tenant DB growth and index health
  • keep migration runtime visible before rolling to all tenants
  • support controlled suspension/reactivation flows
  • standardize incident playbooks by tenant lifecycle state

Common mistakes to avoid

  • choosing multi-database too early for a very early MVP
  • mixing central and tenant tables in one migration stream
  • running tenant jobs without explicit tenant context restoration
  • storing billing truth partially in tenant DB
  • no automated test proving cross-tenant isolation

Example phased rollout plan

Use a staged path instead of "big bang":

  1. internal tenant + test domain
  2. private beta tenants with controlled onboarding
  3. first paid cohort with strong observability
  4. gradual expansion with migration and incident playbooks

This keeps operational risk manageable while architecture matures.

Final recommendation

Multi-database Laravel SaaS architecture is powerful when isolation, control, and enterprise readiness matter. It does introduce meaningful operational complexity, so success depends on disciplined lifecycle design: provisioning pipelines, strict context handling, centralized billing truth, and robust tenant-aware testing.

If those foundations are in place, Laravel can run a multi-database SaaS platform reliably at production scale.

Share this post:

Ready to ship faster?

Build your SaaS with a production-ready foundation

Launch with authentication, billing, tenancy, and team workflows already in place, then focus on the features that make your product unique.

Related posts