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_KEYmust be at least 32 random bytes (generate one withopenssl rand -hex 32) and cannot match the development placeholder.SLABS_COOKIE_SECUREdefaults totrueinstagingandproduction. When enabled, the session cookie name becomes__Host-slabs_sessionand responses includeStrict-Transport-Security: max-age=31536000; includeSubDomains.- Development endpoints (
/_slabs/manifest,/_slabs/openapi.json, and/_slabs/mail) are not mounted outsidedevelopmentandtest. SLABS_TRUST_PROXYdefaults tofalse. Set it totrueonly behind a trusted reverse proxy (kamal-proxy, Fly Proxy, or Caddy) soclient_ipreads proxy headers safely.SLABS_CORS_ORIGINSdefaults to empty (no cross-origin CORS headers). Set a comma-separated allowlist only when another browser origin needs API access.SLABS_METRICS_TOKENprotectsGET /_slabs/metrics. Instagingandproduction,/_slabs/metricsreturns404unlessSLABS_METRICS_TOKENis set, and requiresAuthorization: Bearer <token>verified in constant time.
Health probes, graceful shutdown, and metrics
Slabs mounts three operational endpoints automatically:
| Route | Purpose | Behavior |
|---|---|---|
GET /health/live | Liveness probe | Returns 200 OK JSON {"status": "ok"}. |
GET /health/ready | Readiness probe for load balancers | Runs SELECT 1 on ctx.db.reader(). Returns 503 Service Unavailable while draining after SIGTERM or when the database check fails. |
GET /_slabs/metrics | Operational metrics | Returns 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 sqliteon Kamal 2, the generatedconfig/deploy.ymlsetsboot.limit: 1anddrain_timeout: 20.kamal-proxybuffers incoming requests briefly while the old container drains in-flight traffic, checkpoints SQLite withPRAGMA 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-replicarollingdeploys where new instances pass/health/readybefore 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-chefto cache compiled Rust dependencies separately from your source code and build withcargo build --release --locked. - The runtime stage runs on
debian:bookworm-slimas the non-rootslabsuser (UID10001), mounts/app/assetsread-only, and bundles pinned Litestreamv0.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, andSLABS_LOG_FORMAT=json. - The
HEALTHCHECKprobesGET 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:
| Variable | Example | Purpose |
|---|---|---|
LITESTREAM_BUCKET | myapp-backups | Target S3 or R2 bucket name. |
LITESTREAM_ENDPOINT | https://<account>.r2.cloudflarestorage.com | S3-compatible endpoint URL. |
LITESTREAM_REGION | auto | Signing 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-replicarollingor blue-green deploys. New replicas boot, passGET /health/ready, receive traffic, and old replicas drain for 20 seconds onSIGTERM. - Single-volume SQLite with Litestream (
--db sqlite) allows only one writer process to mount/data/<app>.dbat a time. Never run two active containers against the same SQLite volume:- On Kamal 2, keep
boot.limit: 1anddrain_timeout: 20.kamal-proxybuffers incoming requests while the old container drains onSIGTERMand runsPRAGMA wal_checkpoint(TRUNCATE), then hands traffic to the new container as soon as it passes/health/readywith zero dropped requests. - On Fly.io, keep
[deploy] strategy = "immediate"withkill_signal = "SIGTERM",kill_timeout = "20s", and the/health/readycheck. - On a bare VPS with Caddy and
systemd, place each release at/opt/<app>/releases/<sha>/<app>, swap/opt/<app>/currentwithln -sfn, and runsystemctl restart <app>withTimeoutStopSec=20sandhealth_uri /health/ready.
- On Kamal 2, keep
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:
- Expand first. Add new tables, nullable columns, or columns with defaults in release N.
- Switch reads and writes to the new schema in release N or N+1.
- 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:
| File | Route | Purpose |
|---|---|---|
slabs/pwa/manifest.rs | GET /manifest.webmanifest | Serves 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.rs | GET /service-worker.js | Serves the service worker (application/javascript; charset=utf-8) with Cache-Control: no-cache and Service-Worker-Allowed: /. |
assets/icon.svg | /assets/<hash>/icon.svg | Monochrome 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.