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
Inputand responseOutputstructs - 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/orjobs/start with_(such as_layout.rs), andslabs-buildskips them automatically. - Multiple slabs can register different HTTP verbs on the same path, and
slabs-httpmerges them into one Axum 0.8MethodRouter.
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.sqlis 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::queryorsqlx::query_as. When you want compile-time SQL checks, runslabs db prepareand usesqlx::query!. - File-backed SQLite opens two pools in WAL mode.
ctx.db.reader()holds 16 read-only connections for concurrentSELECTtraffic, andctx.db.writer()holds 1 writer connection. - Multi-step writes open
let mut tx = ctx.db.begin().await?;, which executesBEGIN IMMEDIATEon the writer pool so concurrent transactions never hit aSQLITE_BUSY_SNAPSHOTwrite-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::PgDband the sameslabs db migrateandslabs db dump-schemaworkflow.
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 1to shared editable tables in your migration. - Update with
UPDATE ... SET ..., version = version + 1 WHERE id = ? AND version = ?. - Check
rows_affected() == 0and returnErr(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?(orrequire_admin,require_auth,require_write_auth), checks resource ownership againstsession.user_id, and callsctx.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 insideBEGIN IMMEDIATEtransactions. - 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 entersslabs_jobs. If a worker crashes,slabs_jobsretries with exponential backoff and moves exhausted jobs to"dead". - Any operator or agent can inspect every in-flight workflow with one
SELECTagainst application tables andslabs_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 enforcemissing_docs,missing_debug_implementations,unreachable_pub,rust_2018_idioms, andclippy::pedantic. Maud compiles HTML templates at build time and escapes interpolated strings automatically. AppEnv(Development,Test,Staging,Production, set viaSLABS_ENV) blocks unsafe settings before the server binds a socket. Instagingandproduction,SLABS_SECRET_KEYmust 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 checkruns six steps in one command. It checks formatting acrosssrc/,slabs/, andjobs/, runs the[security]static scanner (flagging interpolated SQL insqlx::query*, unannotatedPreEscaped(,unsafeblocks or missingunsafe_code = "forbid", hardcoded secrets,.unwrap()or.expect(inslabs/andjobs/, and slabs without co-located tests), runs Clippy with-D warnings, builds Rustdoc with-D warnings, runs doctests, and runs parallel tests. Use--changedor--slab <feature>/<action>for targeted sub-second loops,--explainor--strict-explainto catch unintended SQLite full-tableSCANs,slabs manifest --diffto flag removed routes and[SECURITY]auth guard downgrades in PRs, andslabs dev --ephemeralfor collision-free parallel verification.slabs doctorchecks the Rust toolchain,unsafe_code = "forbid",schema.sql,.dockerignore,SLABS_ENVandSLABS_SECRET_KEYrules, 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 runexecutes 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 andhtml::document(...)render typed HTML5 in Rust. Untrusted Markdown passes throughhtml::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 usepopover, page transitions use@view-transition { navigation: auto; }, and live updates stream over Server-Sent Events and WebSockets (slabs-realtimewithPresencetracking). slabs cssandslabs devrun the standalonetailwindcssv4 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 appgenerates a multi-stagecargo-chefDockerfile(cargo build --release --locked), a.dockerignore, a non-rootslabsuser (UID10001), read-only/app/assets,docker-entrypoint.sh, and pinned Litestreamv0.3.13continuous SQLite WAL replication to S3-compatible storage.GET /health/liveconfirms the process is alive,GET /health/readyverifies database connectivity and returns503while draining,GET /_slabs/metricsexposes operational counters behindSLABS_METRICS_TOKEN,SLABS_LOG_FORMAT=jsonemits structured logs, andSIGINTandSIGTERMdrain active HTTP requests, stop background workers, and runPRAGMA wal_checkpoint(TRUNCATE)on SQLite cleanly.slabs deploy init --target kamal|fly|vps --db sqlite|postgreswrites ready-to-edit configs for Kamal 2, Fly.io, and bare Linux VPS hosts running Caddy and hardenedsystemdunits.- PostgreSQL supports multi-replica rolling deploys. Single-volume SQLite runs one writer at a time (
boot.limit = 1withkamal-proxybuffering on Kamal 2, orstrategy = "immediate"on Fly.io) with a 20-secondSIGTERMdrain. - 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 asystemdsymlink) and finishes in seconds.