Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Ship a Progressive Web App and deploy to production

Every project generated by slabs new app starts ready to install as a Progressive Web App (PWA) and ready to ship as a single container binary. This guide covers production boot validation, health and metrics endpoints, container builds with cargo-chef and Litestream, deployment templates for Kamal 2, Fly.io, and Linux VPS hosts, expand-and-contract migrations, and fast rollbacks.

Pre-flight checks and fail-closed SLABS_ENV

Run all local checks before building a release image:

slabs doctor
slabs check --no-docs
slabs css

Set SLABS_ENV=production (or staging) in your deployment secret store. AppConfig::validate() runs inside SlabsApp::boot and refuses to bind a socket if required security settings fail:

  • SLABS_SECRET_KEY must be at least 32 random bytes (generate one with openssl rand -hex 32) and cannot match the development placeholder.
  • SLABS_COOKIE_SECURE defaults to true in staging and production. When enabled, the session cookie name becomes __Host-slabs_session and responses include Strict-Transport-Security: max-age=31536000; includeSubDomains.
  • Development endpoints (/_slabs/manifest, /_slabs/openapi.json, and /_slabs/mail) are not mounted outside development and test.
  • SLABS_TRUST_PROXY defaults to false. Set it to true only behind a trusted reverse proxy (kamal-proxy, Fly Proxy, or Caddy) so client_ip reads proxy headers safely.
  • SLABS_CORS_ORIGINS defaults to empty (no cross-origin CORS headers). Set a comma-separated allowlist only when another browser origin needs API access.
  • SLABS_METRICS_TOKEN protects GET /_slabs/metrics. In staging and production, /_slabs/metrics returns 404 unless SLABS_METRICS_TOKEN is set, and requires Authorization: Bearer <token> verified in constant time.

Health probes, graceful shutdown, and metrics

Slabs mounts three operational endpoints automatically:

RoutePurposeBehavior
GET /health/liveLiveness probeReturns 200 OK JSON {"status": "ok"}.
GET /health/readyReadiness probe for load balancersRuns SELECT 1 on ctx.db.reader(). Returns 503 Service Unavailable while draining after SIGTERM or when the database check fails.
GET /_slabs/metricsOperational metricsReturns Prometheus text (or JSON with Accept: application/json) covering HTTP counts, average latency, job queue stats, and active realtime topics. Protected by SLABS_METRICS_TOKEN in staging and production.

When a container receives SIGINT or SIGTERM, SlabsApp::serve marks the readiness flag as draining (so /health/ready immediately returns 503), finishes in-flight HTTP requests, stops background job workers and schedules, and runs PRAGMA wal_checkpoint(TRUNCATE) on file-backed SQLite databases before exit. Running a truncating WAL checkpoint at the end of the drain flushes every committed frame back into the main .db file cleanly before the next container mounts the volume.

Generate deployment configs with slabs deploy init

Generate starter configuration for your target platform and database engine (--db sqlite default, or --db postgres):

# Kamal 2 (writes config/deploy.yml)
slabs deploy init --target kamal --db sqlite
slabs deploy init --target kamal --db postgres

# Fly.io (writes fly.toml)
slabs deploy init --target fly --db sqlite
slabs deploy init --target fly --db postgres

# Bare Linux VPS (writes deploy/Caddyfile and a hardened systemd unit)
slabs deploy init --target vps --db sqlite
slabs deploy init --target vps --db postgres

Each template configures SLABS_ENV=production, SLABS_TRUST_PROXY=true, /health/ready health checks, and a 20-second SIGTERM drain window, while matching the rollout concurrency to --db:

  • With --db sqlite on Kamal 2, the generated config/deploy.yml sets boot.limit: 1 and drain_timeout: 20. kamal-proxy buffers incoming requests briefly while the old container drains in-flight traffic, checkpoints SQLite with PRAGMA wal_checkpoint(TRUNCATE), and exits before the new container mounts the volume and passes /health/ready. That keeps single-writer SQLite deploys free of dropped requests and lock contention.
  • With --db postgres, multiple app containers can share the database concurrently, so the generated Kamal 2 and Fly.io configs use multi-replica rolling deploys where new instances pass /health/ready before old instances drain.

Build the cargo-chef and Litestream Dockerfile

slabs new app writes a multi-stage Dockerfile, .dockerignore, docker-entrypoint.sh, and litestream.yml:

  • Stage 1 and 2 use cargo-chef to cache compiled Rust dependencies separately from your source code and build with cargo build --release --locked.
  • The runtime stage runs on debian:bookworm-slim as the non-root slabs user (UID 10001), mounts /app/assets read-only, and bundles pinned Litestream v0.3.13.
  • Container defaults set SLABS_ENV=production, SLABS_BIND=0.0.0.0:3000, DATABASE_URL=sqlite:///data/<name>.db?mode=rwc, SLABS_STORAGE_DIR=/data/storage, SLABS_ASSETS_DIR=/app/assets, and SLABS_LOG_FORMAT=json.
  • The HEALTHCHECK probes GET http://127.0.0.1:3000/health/ready.

Always tag container images with an immutable git commit SHA instead of :latest:

SHA=$(git rev-parse --short HEAD)
slabs css
docker build -t registry.example.com/myapp:${SHA} .
docker push registry.example.com/myapp:${SHA}

Replicate SQLite WAL continuously with Litestream

Because file-backed SQLite runs in WAL mode, Litestream streams WAL frames continuously to S3, Cloudflare R2, Tigris, or MinIO with zero application code changes. slabs new app writes litestream.yml:

dbs:
  - path: /data/myapp.db
    replicas:
      - type: s3
        bucket: ${LITESTREAM_BUCKET}
        path: myapp/db
        endpoint: ${LITESTREAM_ENDPOINT}
        region: ${LITESTREAM_REGION:-auto}

Set these environment variables in your host or secret manager:

VariableExamplePurpose
LITESTREAM_BUCKETmyapp-backupsTarget S3 or R2 bucket name.
LITESTREAM_ENDPOINThttps://<account>.r2.cloudflarestorage.comS3-compatible endpoint URL.
LITESTREAM_REGIONautoSigning region (defaults to auto for Cloudflare R2).
LITESTREAM_ACCESS_KEY_ID...Bucket write access key ID.
LITESTREAM_SECRET_ACCESS_KEY...Bucket write secret key.

docker-entrypoint.sh restores the latest snapshot on an empty volume and runs your binary under Litestream:

#!/usr/bin/env sh
set -eu

litestream restore -if-db-not-exists -if-replica-exists -config /app/litestream.yml /data/myapp.db
exec litestream replicate -config /app/litestream.yml -exec "/usr/local/bin/myapp"

Choose the right rollout strategy for SQLite vs PostgreSQL

  • PostgreSQL (--db postgres) supports multi-replica rolling or blue-green deploys. New replicas boot, pass GET /health/ready, receive traffic, and old replicas drain for 20 seconds on SIGTERM.
  • Single-volume SQLite with Litestream (--db sqlite) allows only one writer process to mount /data/<app>.db at a time. Never run two active containers against the same SQLite volume:
    • On Kamal 2, keep boot.limit: 1 and drain_timeout: 20. kamal-proxy buffers incoming requests while the old container drains on SIGTERM and runs PRAGMA wal_checkpoint(TRUNCATE), then hands traffic to the new container as soon as it passes /health/ready with zero dropped requests.
    • On Fly.io, keep [deploy] strategy = "immediate" with kill_signal = "SIGTERM", kill_timeout = "20s", and the /health/ready check.
    • On a bare VPS with Caddy and systemd, place each release at /opt/<app>/releases/<sha>/<app>, swap /opt/<app>/current with ln -sfn, and run systemctl restart <app> with TimeoutStopSec=20s and health_uri /health/ready.

Expand-and-contract migrations and fast rollbacks

Keep every schema change backward-compatible with the previous release binary so a rollback never crashes on missing columns:

  1. Expand first. Add new tables, nullable columns, or columns with defaults in release N.
  2. Switch reads and writes to the new schema in release N or N+1.
  3. Contract later. Drop unused columns or tables only after the old image is no longer a rollback candidate.

Take a pre-deploy backup before migrating (sqlite3 /data/<app>.db "VACUUM INTO '/data/backup-pre-deploy.db'" or verify litestream snapshots /data/<app>.db). If /health/ready fails or errors spike after a deploy, roll back immediately to the previous git SHA:

# Kamal 2
kamal rollback <previous-sha>

# Fly.io
fly releases list
fly releases rollback <version>

# Bare VPS (systemd)
ln -sfn /opt/<app>/releases/<previous-sha> /opt/<app>/current
systemctl restart <app>

If bad writes corrupted SQLite data, stop the service first, then restore from Litestream (litestream restore -timestamp <RFC3339> -o /data/<app>.db /data/<app>.db) or copy /data/backup-pre-deploy.db back into place before restarting.

Progressive Web App slabs and hardened service worker

Every new Slabs app ships two discovered PWA slabs and an SVG app icon:

FileRoutePurpose
slabs/pwa/manifest.rsGET /manifest.webmanifestServes the Web App Manifest (application/manifest+json; charset=utf-8) with display: "standalone", theme colors, and the content-hashed icon.svg URL from ctx.assets.url("icon.svg").
slabs/pwa/service_worker.rsGET /service-worker.jsServes the service worker (application/javascript; charset=utf-8) with Cache-Control: no-cache and Service-Worker-Allowed: /.
assets/icon.svg/assets/<hash>/icon.svgMonochrome Rust Orange icon referenced by the manifest. Replacing the file busts browser caches through its content hash.

html::document wires <link rel="manifest" href="/manifest.webmanifest"> in <head> and registers /service-worker.js on window load. In v0.5.0, the generated service worker enforces same-origin checks before caching responses or calling clients.openWindow, uses stale-while-revalidate for /_slabs/vendor/, uses cache-first for content-hashed /assets/, uses network-first with a 503 offline page for navigations, and wraps event.data.json() in try/catch.

Seed databases idempotently with slabs db seed

slabs new app creates a starter seeds.sql file. Write idempotent SQL (INSERT OR IGNORE on SQLite, ON CONFLICT DO NOTHING on PostgreSQL) and run slabs db seed after migrating:

slabs db migrate --database-url sqlite://myapp.db?mode=rwc
slabs db seed --database-url sqlite://myapp.db?mode=rwc

Pass --file <path> to execute a custom fixture file instead of seeds.sql.