tenanted.dev v0.2.2
Guide 01 of 7

Getting Started & Architecture

laravel-tenanted is built around structural isolation by default — every customer gets their own isolated database (SQLite-first, like Basecamp's activerecord-tenanted, or an isolated Postgres schema/database) without custom query wrappers, global scopes, or WHERE tenant_id = ? bugs.

Scope & Philosophy: laravel-tenanted intentionally does not do shared-table row-level tenant_id scoping or Postgres RLS. We believe structural isolation (separate databases or schemas) is the cleanest, safest way to keep customer data separate — especially with SQLite (local or durable on S3/R2 via laravel-litebucket), where database-per-tenant is effectively free. If you specifically want shared-table row-level multi-tenancy, use a separate row-level pattern or package.

Why SQLite Makes Database-per-Tenant Practical

Most developers hear "database-per-tenant" and picture spinning up thousands of Postgres databases, hitting max_connections, and paying for oversized clusters. SQLite flips every one of those tradeoffs:

  • Zero idle cost: An inactive tenant's database is just a file (or S3/R2 prefix) — 0 RAM, 0 background processes, 0 open connections. With laravel-tenanted's LRU pool cap (TENANT_MAX_OPEN=64), 500 active SQLite tenants ran in 43.8 MiB RSS and 65 file descriptors.
  • Sub-millisecond reads, zero network hops: Queries run in-process inside your Rust binary. Smaller per-tenant B-trees stay hot in memory, and one noisy tenant can never bloat indexes or starve another customer's queries.
  • Instant provisioning: Creating a brand-new tenant database and running its schema takes ~1 ms (1,000+ tenants/sec) — no CREATE DATABASE superuser privileges or control-plane API calls.
  • Per-tenant backup, PITR, export & GDPR erasure: Restore a single customer to 10 minutes ago without touching anyone else, hand an enterprise customer a complete dump of their data, or permanently erase a departing tenant by deleting one file (tenant:delete acme --force).
  • Works on stateless clouds too: Ephemeral container disks used to be SQLite's one catch. Pair laravel-tenanted with laravel-litebucket (t.litebucket()) and every tenant's SQLite database lives directly on S3 / Cloudflare R2 / Laravel Cloud Object Storage with per-tenant HKDF AES-256-GCM encryption, zero Postgres server, and zero persistent disk.

Prefer PostgreSQL or MySQL? laravel-tenanted supports structural isolation there too (Postgres schema-per-tenant on a single database via search_path, or logical database-per-tenant on one server) — see the Configuration Reference.

How It Works Under the Hood

In a PHP-FPM app, multi-tenancy packages mutate the process's default database connection because each HTTP request runs in its own isolated PHP process. laravel-rust is a long-lived async Tokio server handling thousands of concurrent requests inside one binary — mutating a process-global default connection would race and leak Tenant A's data into Tenant B's request.

Instead, laravel-tenanted builds directly on four native laravel-rust primitives:

  1. Dynamic Connections (DatabaseManager::add_connection / purge / remove_connection) Each tenant gets a named connection pool (tenant_acme, tenant_globex, ...) registered lazily on first touch and bounded by an LRU cache (max_open_tenants).
  2. Task-Local Connection Routing (DatabaseManager::using_connection) Entering a tenant scope wraps the request/job future in db.using_connection("tenant_acme", ...). Inside that async task — and any child tasks started with laravel::task::spawn — every #[model], create!, db::table(), db::query!(), db::transaction(), Route Model Binding lookup, and DB validation rule automatically routes to tenant_acme. Meanwhile, any model declaring an explicit connection (#[model(connection = "central")]) ignores the default connection override and keeps querying the central database.
  3. Request & Job Context (laravel::context) Entering a tenant scope writes tenant = "acme" into laravel::context (and restores the previous value via an RAII drop guard on exit, error, or cancellation). Every structured log line automatically carries tenant="acme", and every dispatched laravel::queue job automatically serializes that context to the worker.
  4. Fail-Closed Sentinel (TenantConfig::require_tenant()) When enabled, TenantedServiceProvider::boot points the process's default database connection to a sentinel name (no_active_tenant (...)) that is intentionally undefined. Any accidental query against a tenanted model outside a tenant scope fails immediately instead of silently reading or writing the default database.
Text
Incoming Request (acme.myapp.com)
        │
        ▼
  TrustHosts (auto-configured for myapp.com & *.myapp.com)
        │
        ▼
  ResolveTenantMiddleware
    ├── sanitize_tenant_id("acme")  → rejects .., /, \, spaces (400 Bad Request)
    ├── TenantManager::connection() → lazy register + migrate + LRU evict if full
    ├── laravel::context::add("tenant", "acme")
    ├── dispatch TenantEntered event
    └── db.using_connection("tenant_acme", next.run(request))
            │
            ▼
      Your Controller (100% vanilla laravel-rust!)
        ├── Invoice::query()                  → tenant_acme
        ├── create!(Invoice { ..input })      → tenant_acme
        ├── laravel::cache::get("dashboard")  → tenant:acme:dashboard
        ├── SendReceipt.dispatch()            → carries tenant="acme" in Context
        └── BillingPlan::query()              → central DB (#[model(connection = "central")])

Adding laravel-tenanted to an Existing laravel-rust App

1. Add the Dependency

TOML
# Cargo.toml (SQLite default)
[dependencies]
laravel-tenanted = "0.2"

If your app uses PostgreSQL or MySQL and does not need SQLite:

TOML
[dependencies]
laravel-tenanted = { version = "0.2", default-features = false, features = ["postgres"] }

2. Enable Tenancy in 1 Line

Import WithTenancy and call .with_tenancy() right on laravel::Application::configure() — the exact same fluent style as .with_routing(...) and .with_middleware(...):

Rust
use laravel_tenanted::WithTenancy;

laravel::Application::configure()
    .with_tenancy()
    .with_routing(...)
    .run()

Or customize your subdomain / session resolver and tenant tables inline with .with_tenancy_using(|t| ...):

Rust
use laravel_tenanted::WithTenancy;

laravel::Application::configure()
    .with_tenancy_using(|t| {
        t.subdomain("myapp.com")
            .auto_create(false) // reject unknown tenants with 404
            .create_table("invoices", |table| {
                table.id();
                table.string("label").unique();
                table.big_integer("cents");
            });
    })
    .with_routing(...)
    .run()

With .with_tenancy() / .with_tenancy_using(...), laravel-tenanted automatically wires:

  • Database template & pool limits from env vars (defaulting to sqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwc, max_open_tenants = 64, max_connections_per_tenant = 4)
  • Fail-closed mode (require_tenant) enabled by default so accidental queries outside a tenant scope fail loudly instead of leaking data
  • ResolveTenantMiddleware + TrustHosts auto-configured from TENANT_BASE_DOMAIN / APP_URL (ignoring www, api, admin), strictly subdomain-only by default so untrusted X-Tenant-ID headers on apex/ignored subdomains are ignored (call .with_header_fallback("x-tenant-id") or set TENANT_HEADER=x-tenant-id to opt in)
  • Tenant-isolated "tenanted" cache store registered and set as the default cache store (opt out with .keep_default_cache() or .without_tenanted_cache())
  • All 5 tenant:* Artisan commands (tenant:create, tenant:list, tenant:migrate, tenant:evict, tenant:delete)

Environment Variables Recognized Automatically

VariableDefaultPurpose
TENANT_DATABASE_URLsqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwcURL template containing {tenant} (also reads TENANT_DATABASE_URL_TEMPLATE)
TENANT_BASE_DOMAINInferred from APP_URLSubdomain base host (e.g. myapp.com → acme.myapp.com)
TENANT_HEADERx-tenant-idHeader fallback name (set empty to disable)
TENANT_AUTO_CREATEfalse in APP_ENV=production, true locallyfalse rejects unknown tenants with 404
TENANT_REQUIREtrueFail closed on queries outside a tenant scope
TENANT_MAX_OPEN64LRU cap on open tenant pools in RAM
TENANT_MAX_CONNECTIONS4Max connections per open tenant pool
TENANT_CONTEXT_KEYtenantlaravel::context key used for logs, jobs, cache & storage
TENANT_CENTRAL_CONNECTION(unset)Central DB connection name for without_tenant(...)
Manual registration with TenantConfig + TenantedServiceProvider

If you prefer explicit provider wiring (e.g. building TenantConfig dynamically in another module):

Rust
use laravel_tenanted::{TenantConfig, TenantedServiceProvider};

let tenancy = TenantConfig::new("sqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwc")
    .require_tenant()
    .central_connection("central")
    .auto_create(false)
    .max_open_tenants(64)
    .max_connections_per_tenant(4)
    .create_table("invoices", |table| {
        table.id();
        table.string("label").unique();
        table.big_integer("cents");
    });

laravel::Application::configure()
    .with_providers(|providers| {
        providers.add(
            TenantedServiceProvider::new(tenancy)
                .resolve_from_subdomain("myapp.com"),
        );
    })
    .run()

3. Provision Your First Tenant

When auto_create(true) (default locally; defaults to false when APP_ENV=production), the first request to acme.myapp.com creates and migrates storage/tenants/acme/main.sqlite3 automatically.

If auto_create(false) (recommended for production SaaS where tenants sign up through a provisioning flow):

Shell
cargo run -- tenant:create acme

Or programmatically during customer onboarding:

Rust
laravel_tenanted::create("acme").await?;

Security & Tenant ID Validation

Every tenant identifier passes through laravel_tenanted::sanitize_tenant_id before any URL template rendering, file path creation, or connection lookup:

  • Length: 1..=63 characters (DNS subdomain compatible)
  • Characters: ASCII lowercase [a-z0-9_-], starting with alphanumeric
  • Normalized to lowercase ("Acme_01" → "acme_01")
  • Rejects path traversal (../globex, acme/evil, \), whitespace, null bytes, and control characters with TenantedError::InvalidTenantId (400 Bad Request).

Next Steps