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

The Slabs doctrine

Slabs rests on one observation. The abstractions that help a human browse an MVC codebase in an IDE are the same abstractions that stall parallel AI agents and trigger git merge conflicts.

When ten contributors add ten endpoints to a typical web app, every one of them edits routes.rs, models/mod.rs, services/mod.rs, and shared DTO files. Each contributor guesses which callbacks fire on save(), hunts across six directories to trace one HTTP request, and spends more time untangling conflicts than shipping code.

Slabs takes the opposite path. Eight rules govern the framework so every endpoint stays local, every write stays explicit, and twenty contributors can ship in parallel without touching each other’s files.

1. One use case is one self-contained slab

Every HTTP endpoint lives in its own file at slabs/<feature>/<action>.rs, such as slabs/cards/create_card.rs. Every background job lives in its own file at jobs/<name>.rs.

One file holds the entire vertical slice of a single Transaction Script:

  • Route declaration (pub fn slab() -> SlabDef)
  • Request Input and response Output structs
  • Line-1 authentication, authorization, and rate-limit guards
  • Input validation
  • Raw SQL queries and explicit transaction boundary
  • Transactional side effects (enqueue_in_tx, dispatch_in_tx, audit.record_in_tx)
  • Co-located #[cfg(test)] mod tests

Slabs forbids models/, controllers/, repositories/, and services/ directories. Repeating a five-line struct or a three-line SELECT in two slabs costs almost nothing and keeps both files independent. Coupling twenty endpoints through a shared helper trait saves ten lines once and produces merge conflicts forever.

When an agent opens slabs/cards/create_card.rs, it reads 100% of the code that runs when POST /api/boards/{board_id}/cards arrives.

2. Compile-time discovery replaces central registries

Slabs has no routes.rs and no manual job registry.

A three-line build.rs calls slabs_build::discover(). At build time, slabs-build walks slabs/<feature>/*.rs and jobs/*.rs and writes $OUT_DIR/discovered_slabs.rs. src/lib.rs includes that generated file once with slabs::discover_slabs!() and passes collect_slabs() and collect_jobs() to SlabsApp::boot(...).

  • Creating a new endpoint touches zero existing files.
  • Deleting an endpoint removes one file cleanly, with no dead route entries or orphaned helpers left behind.
  • Helper modules inside slabs/ or jobs/ start with _ (such as _layout.rs), and slabs-build skips them automatically.
  • Multiple slabs can register different HTTP verbs on the same path, and slabs-http merges them into one Axum 0.8 MethodRouter.

Twenty parallel agents can open twenty pull requests adding twenty slabs and merge all twenty with zero conflicts.

3. Raw SQL is the clearest query language for agents

ORMs invent a second query language with lazy-loading traps, N+1 queries, hidden JOIN rewrites, and version-specific macro quirks. SQL has been stable for forty years and every model knows it fluently.

Slabs keeps database access direct:

  • schema.sql is the single-file ground truth for every table, column, constraint, and index in the application. Reading one file shows the complete data model.
  • Every query uses parameterized SQL through sqlx::query or sqlx::query_as. When you want compile-time SQL checks, run slabs db prepare and use sqlx::query!.
  • File-backed SQLite opens two pools in WAL mode. ctx.db.reader() holds 16 read-only connections for concurrent SELECT traffic, and ctx.db.writer() holds 1 writer connection.
  • Multi-step writes open let mut tx = ctx.db.begin().await?;, which executes BEGIN IMMEDIATE on the writer pool so concurrent transactions never hit a SQLITE_BUSY_SNAPSHOT write-upgrade deadlock.
  • Full-text search uses SQLite FTS5 sanitized through slabs::db::fts5_query.
  • Applications that outgrow single-node SQLite move to PostgreSQL through slabs_db::PgDb and the same slabs db migrate and slabs db dump-schema workflow.

Opt-in Optimistic Offline Lock for shared records

When multiple users edit the same record concurrently across separate HTTP requests, Slabs uses an explicit, opt-in SQL Optimistic Offline Lock rather than ORM magic or hidden row-version hooks:

  • Add version INTEGER NOT NULL DEFAULT 1 to shared editable tables in your migration.
  • Update with UPDATE ... SET ..., version = version + 1 WHERE id = ? AND version = ?.
  • Check rows_affected() == 0 and return Err(SlabError::conflict("...")) (409 Conflict) so the caller reloads the latest version instead of silently overwriting another user’s edit.

Keep this convention opt-in. Do not put version locks on append-only rows (messages, events, audit logs), hot counters (use atomic SET count = count + 1), or CRDT real-time collaborative documents where concurrent edits merge at the operation level.

4. Explicit code beats hidden callbacks and replay magic

Hidden model callbacks (before_save, after_commit) trigger side effects far from the code that ran the write. Implicit durable-workflow replay engines go further. They demand deterministic replay across code versions, break in-flight executions when someone reorders a branch or updates a crate, trap ordinary clock or HTTP calls inside wrapper APIs, and bury live business state inside opaque event logs.

Slabs rejects both hidden model callbacks and implicit workflow replay engines.

  • Every protected handler calls ctx.auth.require_session(&jar).await? (or require_admin, require_auth, require_write_auth), checks resource ownership against session.user_id, and calls ctx.rate_limit.check(...) directly on line 1.
  • Multi-step workflows store their current state in a normal SQL column (status = 'pending' | 'charged' | 'shipped' | 'failed') updated inside BEGIN IMMEDIATE transactions.
  • When step 1 finishes, it updates the row state and calls ctx.jobs.enqueue_in_tx(&mut tx, "step_2", payload).await? inside the same SQL transaction. If the transaction rolls back, the job never enters slabs_jobs. If a worker crashes, slabs_jobs retries with exponential backoff and moves exhausted jobs to "dead".
  • Any operator or agent can inspect every in-flight workflow with one SELECT against application tables and slabs_jobs. Deploying new code never corrupts an opaque replay log.

5. Make invalid states fail at compile time or boot time

Security and correctness belong in automated checks, not in tribal memory.

  • Every crate and generated app sets unsafe_code = "forbid". Core crates enforce missing_docs, missing_debug_implementations, unreachable_pub, rust_2018_idioms, and clippy::pedantic. Maud compiles HTML templates at build time and escapes interpolated strings automatically.
  • AppEnv (Development, Test, Staging, Production, set via SLABS_ENV) blocks unsafe settings before the server binds a socket. In staging and production, SLABS_SECRET_KEY must be at least 32 random bytes and cannot match the development placeholder. Cross-origin CORS (SLABS_CORS_ORIGINS) and proxy header trust (SLABS_TRUST_PROXY) stay off unless explicitly configured.
  • slabs check runs six steps in one command. It checks formatting across src/, slabs/, and jobs/, runs the [security] static scanner (flagging interpolated SQL in sqlx::query*, unannotated PreEscaped(, unsafe blocks or missing unsafe_code = "forbid", hardcoded secrets, .unwrap() or .expect( in slabs/ and jobs/, and slabs without co-located tests), runs Clippy with -D warnings, builds Rustdoc with -D warnings, runs doctests, and runs parallel tests. Use --changed or --slab <feature>/<action> for targeted sub-second loops, --explain or --strict-explain to catch unintended SQLite full-table SCANs, slabs manifest --diff to flag removed routes and [SECURITY] auth guard downgrades in PRs, and slabs dev --ephemeral for collision-free parallel verification.
  • slabs doctor checks the Rust toolchain, unsafe_code = "forbid", schema.sql, .dockerignore, SLABS_ENV and SLABS_SECRET_KEY rules, and the security scan summary before you deploy.

6. Every slab tests itself in isolation

Tests live in #[cfg(test)] mod tests at the bottom of the slab file they verify.

Calling crate::test_app().await (gated behind #[cfg(test)] in src/lib.rs) boots a complete application backed by an isolated in-memory SQLite database (sqlite::memory:) with all system and application migrations applied and a fresh temporary storage directory.

  • Tests share zero mutable database state.
  • cargo nextest run executes hundreds of slab tests in parallel across every CPU core in a few seconds.
  • When an agent edits slabs/cards/create_card.rs, the test suite for that endpoint is already open in the same file.

7. Standard web platform over JavaScript build chains

Most web applications do not need a 500-megabyte node_modules tree, a bundler, a client-side router, and a JSON serialization layer duplicating server state.

Slabs renders HTML on the server and ships zero Node.js or npm tooling:

  • maud! templates and html::document(...) render typed HTML5 in Rust. Untrusted Markdown passes through html::render_markdown(&text), which strips raw HTML tags and unsafe URL schemes so user input cannot inject scripts or HTMX attributes.
  • /_slabs/vendor/ embeds MIT-licensed browser libraries directly in the binary, including Basecoat UI, HTMX 2, HTMX SSE, Idiomorph (hx-ext="morph"), and Alpine.js 3.
  • Modals use native <dialog>, menus use popover, page transitions use @view-transition { navigation: auto; }, and live updates stream over Server-Sent Events and WebSockets (slabs-realtime with Presence tracking).
  • slabs css and slabs dev run the standalone tailwindcss v4 binary against @source "../slabs" with zero npm packages.

8. Single binary, boring infrastructure, zero-downtime deploys, and fast rollbacks

A Slabs application compiles to one native binary. Static assets are content-hashed under /assets/{hash}/{*path}, and SQL migrations compile into the binary through sqlx::migrate!("./migrations").

  • slabs new app generates a multi-stage cargo-chef Dockerfile (cargo build --release --locked), a .dockerignore, a non-root slabs user (UID 10001), read-only /app/assets, docker-entrypoint.sh, and pinned Litestream v0.3.13 continuous SQLite WAL replication to S3-compatible storage.
  • GET /health/live confirms the process is alive, GET /health/ready verifies database connectivity and returns 503 while draining, GET /_slabs/metrics exposes operational counters behind SLABS_METRICS_TOKEN, SLABS_LOG_FORMAT=json emits structured logs, and SIGINT and SIGTERM drain active HTTP requests, stop background workers, and run PRAGMA wal_checkpoint(TRUNCATE) on SQLite cleanly.
  • slabs deploy init --target kamal|fly|vps --db sqlite|postgres writes ready-to-edit configs for Kamal 2, Fly.io, and bare Linux VPS hosts running Caddy and hardened systemd units.
  • PostgreSQL supports multi-replica rolling deploys. Single-volume SQLite runs one writer at a time (boot.limit = 1 with kamal-proxy buffering on Kamal 2, or strategy = "immediate" on Fly.io) with a 20-second SIGTERM drain.
  • Pair expand-and-contract migrations with immutable git-SHA image tags so rolling back takes one command (kamal rollback <sha>, fly releases rollback, or flipping a systemd symlink) and finishes in seconds.