tenanted.dev v0.2.2
Guide 07 of 7

Deployment Guide

laravel-tenanted is designed to deploy cleanly across every Rust hosting topology — from a single $5 VPS running SQLite-per-tenant, to Fly.io / Kamal containers with persistent volumes, to stateless Laravel Cloud / Kubernetes pods running PostgreSQL or LiteBucket S3/R2 SQLite.

1. Choosing Your Production Architecture

PlatformRecommended StorageConfig TemplateNotes
Single VPS / Hetzner / KamalLocal SQLite on NVMe + litebucket replicate or Litestream WAL backupsqlite:///data/tenants/{tenant}/main.sqlite3?mode=rwcZero DB server ops, sub-millisecond reads, mount /data volume
Fly.io / Render / RailwayLocal SQLite on persistent volumesqlite:///data/tenants/{tenant}/main.sqlite3?mode=rwcSingle writer region or Fly Replay for multi-region
Laravel Cloud / Managed Postgres (Schema-per-Tenant)PostgreSQL (default-features = false, features = ["postgres"])postgres://user:pass@host/myapp?options=-c%20search_path%3D%22tenant_{tenant}%22One Postgres server & one DB; no CREATEDB needed (or .../tenant_{tenant} for logical DB-per-tenant on one server)
Laravel Cloud / Ephemeral Containers (SQLite)LiteBucket S3/R2 SQLite VFSlaravel-litebucket (t.litebucket())Zero local disk required + per-tenant HKDF AES-256-GCM encryption

2. Environment-Driven Configuration

.with_tenancy() and .with_tenancy_using(...) read your environment variables automatically — no manual std::env::var(...) parsing required — so local dev, staging, and production run the exact same binary:

.env
APP_ENV=production
APP_URL=https://myapp.com
TENANT_BASE_DOMAIN=myapp.com
TENANT_DATABASE_URL=sqlite:///data/tenants/{tenant}/main.sqlite3?mode=rwc
TENANT_MAX_OPEN=64
# TENANT_AUTO_CREATE defaults to false automatically when APP_ENV=production

3. Wildcard Subdomains, Reverse Proxies & TrustHosts

When serving <tenant>.myapp.com:

  1. DNS: Add a wildcard A / AAAA / CNAME record for *.myapp.com pointing to your load balancer or server.
  2. TLS: Issue a wildcard certificate (*.myapp.com + myapp.com) via Caddy, Cloudflare, Fly.io, or Let's Encrypt DNS-01.
  3. Preserve the Host header: Ensure your reverse proxy forwards the original Host header (proxy_set_header Host $host; in Nginx; automatic in Caddy and Kamal Proxy).
  4. TrustHosts: .with_tenancy() / .with_tenancy_using(|t| { t.subdomain("myapp.com"); }) (and TenantedServiceProvider::resolve_from_subdomain) automatically configures laravel-rust's TrustHosts middleware to allow myapp.com and *.myapp.com. If you pass a custom TrustHosts config in .with_middleware(...), remember to include "*.myapp.com".

4. Laravel Cloud Auto-Setup with LiteBucket (Zero Postgres, Zero Persistent Disk)

If you deploy on Laravel Cloud and want database-per-tenant SQLite without paying for a Postgres cluster or mounting a disk:

  1. Attach a Laravel Cloud Object Storage (R2) bucket to your environment. Laravel Cloud automatically injects FILESYSTEM_ENDPOINT, FILESYSTEM_BUCKET, FILESYSTEM_ACCESS_KEY_ID, FILESYSTEM_SECRET_ACCESS_KEY, and FILESYSTEM_REGION. laravel-litebucket discovers all of them automatically — zero S3 credentials to copy-paste.
  2. Set two environment variables in Laravel Cloud:
    .env
    LITEBUCKET_VFS=1
    LITEBUCKET_ENCRYPTION_KEY=pass:your-strong-secret-passphrase
  3. Wire .with_litebucket() + t.litebucket_from_env():
    Rust
    use laravel_litebucket::prelude::*;
    use laravel_tenanted::WithTenancy;
    
    Application::configure()
        .with_litebucket()
        .with_migrations(migrations())
        .with_tenancy_using(|t| {
            t.litebucket_from_env()
                .central_connection("central")
                .auto_create(false);
        })
  4. Use strict durability for central auth/org tables in src/config/database.rs:
    Rust
    let central_url = if std::env::var("LITEBUCKET_VFS").as_deref() == Ok("1") {
        laravel_litebucket::database_url_strict("central/main")
    } else {
        "sqlite://storage/database/central.sqlite3?mode=rwc".to_owned()
    };

When Laravel Cloud stops, hibernates, or redeploys your container, the fresh cold pod boots in ~1 second from zero local disk and hydrates both central/main and every tenants/<slug>/main database directly from your R2 bucket with per-tenant HKDF AES-256-GCM encryption. See the Configuration Reference and litebucket.dev for full details.

5. Docker Deployment (Multi-Stage Rust Binary + Persistent Volume)

A complete working Dockerfile and fly.toml live in examples/deployable-saas/. The core pattern:

Dockerfile
FROM rust:1.99-bookworm AS builder
WORKDIR /app
COPY . .
RUN cargo build --release

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates curl && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=builder /app/target/release/my-saas /usr/local/bin/my-saas
RUN mkdir -p /data/tenants

ENV APP_ENV=production
ENV APP_URL=https://myapp.com
ENV TENANT_BASE_DOMAIN=myapp.com
ENV TENANT_DATABASE_URL="sqlite:///data/tenants/{tenant}/main.sqlite3?mode=rwc"

EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=3s CMD curl -fsS http://127.0.0.1:8000/health || exit 1
CMD ["my-saas", "serve", "--host", "0.0.0.0", "--port", "8000"]

Run with a persistent volume mounted at /data:

Shell
docker build -t my-saas .
docker run -d --name my-saas \
  -p 8000:8000 \
  -v my-saas-data:/data \
  -e TENANT_BASE_DOMAIN=myapp.com \
  my-saas

6. Production Checklist

  • Keep fail-closed mode enabled — .with_tenancy() enables require_tenant by default (or call TenantConfig::require_tenant() if registering manually), guaranteeing no controller, job, or command can accidentally query a tenanted model outside a tenant scope.
  • Keep .auto_create(false) in production — .with_tenancy() sets auto_create(false) automatically when APP_ENV=production, preventing random bots hitting spam1234.myapp.com from creating thousands of empty tenant databases on disk! Provision customers explicitly during onboarding via laravel_tenanted::create(&slug).await? or tenant:create <slug>.
  • Size max_open_tenants — Each open SQLite pool keeps a handful of file descriptors (max_connections_per_tenant) and SQLite page cache in RAM. 64–256 works smoothly on 512 MB–2 GB containers; raise ulimit -n if you run higher.
  • Run eager migrations on deploy — Execute my-saas tenant:migrate --all as a release/pre-start hook so every tenant schema is upgraded before traffic hits.
  • Isolate your cache — .with_tenancy() automatically registers the in-memory "tenanted" default cache store (tenant:{id}:*). For multi-instance deployments sharing Redis, wrap it with laravel_tenanted::cache_store("redis")? (or TenantedCacheStore::new(redis_store)).
  • Backups & offboarding:
    • For local SQLite, back up /data/tenants/ continuously (e.g. litebucket replicate --tenants-dir /data/tenants --per-tenant-key or Litestream) — every tenant is an independent .sqlite3 file you can restore or export individually!
    • For GDPR / customer offboarding, run my-saas tenant:delete <tenant> --force (or wire TenantConfig::on_delete to DROP DATABASE / litebucket shred).