Write an atomic transaction with a background job
Use this guide when an HTTP endpoint must update one or more domain tables and schedule background work (email, webhooks, or audit logs) so both commit together or both roll back together.
Open a BEGIN IMMEDIATE transaction
Call ctx.db.begin().await? at the start of the write section. begin() opens a BEGIN IMMEDIATE transaction on the single-connection SQLite writer pool. Pass &mut *tx to sqlx::query and &mut tx to ctx.jobs.enqueue_in_tx.
#![allow(unused)]
fn main() {
// slabs/orders/place_order.rs
use axum::{extract::State, http::StatusCode, Json};
use axum_extra::extract::CookieJar;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_json::json;
use slabs::prelude::*;
pub fn slab() -> SlabDef {
SlabDef::post("/api/orders", handle)
.name("orders.place_order")
.summary("Create an order and enqueue a confirmation email atomically")
}
#[derive(Debug, Deserialize)]
pub struct Input {
pub sku: String,
pub quantity: i64,
}
#[derive(Debug, Serialize)]
pub struct Output {
pub order_id: String,
}
async fn handle(
State(ctx): State<AppCtx>,
jar: CookieJar,
Json(input): Json<Input>,
) -> SlabResult<(StatusCode, Json<Output>)> {
let session = ctx.auth.require_session(&jar).await?;
if input.quantity <= 0 {
return Err(SlabError::validation("quantity", "must be greater than zero"));
}
let order_id = id::new("ord");
let now = Utc::now().to_rfc3339();
let mut tx = ctx.db.begin().await?;
sqlx::query(
"INSERT INTO orders (id, user_id, sku, quantity, created_at)
VALUES (?, ?, ?, ?, ?)",
)
.bind(&order_id)
.bind(&session.user_id)
.bind(input.sku.trim())
.bind(input.quantity)
.bind(&now)
.execute(&mut *tx)
.await?;
ctx.jobs
.enqueue_in_tx(
&mut tx,
"send_order_receipt",
json!({ "order_id": order_id, "user_id": session.user_id }),
)
.await?;
tx.commit().await?;
Ok((StatusCode::CREATED, Json(Output { order_id })))
}
}
If any query fails before tx.commit().await?, SQLite rolls back both the orders insert and the slabs_jobs insert.
Guard shared edits with an Optimistic Offline Lock
When two users open the same editable record (such as a card, document, or project setting) and submit updates from separate HTTP requests, a plain UPDATE ... WHERE id = ? silently overwrites the first save. Prevent lost updates with an opt-in SQL Optimistic Offline Lock.
Add a version column to shared editable tables in your migration:
ALTER TABLE cards ADD COLUMN version INTEGER NOT NULL DEFAULT 1;
Include the client’s version in the request payload, increment it atomically inside WHERE id = ? AND version = ?, and return SlabError::conflict (409 Conflict) when rows_affected() == 0:
#![allow(unused)]
fn main() {
let mut tx = ctx.db.begin().await?;
let res = sqlx::query(
"UPDATE cards
SET title = ?, body = ?, updated_at = ?, version = version + 1
WHERE id = ? AND version = ?",
)
.bind(input.title.trim())
.bind(&input.body)
.bind(&now)
.bind(&card_id)
.bind(input.version)
.execute(&mut *tx)
.await?;
if res.rows_affected() == 0 {
return Err(SlabError::conflict(
"Card was modified by another request. Reload and retry.",
));
}
tx.commit().await?;
}
If you need to distinguish a deleted record (404 Not Found) from a stale version (409 Conflict), run a quick SELECT 1 FROM cards WHERE id = ? inside the same rows_affected() == 0 branch before choosing between SlabError::not_found and SlabError::conflict.
When not to use an Optimistic Offline Lock
Keep version checks opt-in and only on shared editable records. Skip them for:
- Append-only rows such as chat messages, events, audit logs, and ledger entries that are inserted once and never edited in place.
- Hot counters such as view counts, vote totals, or stock decrements, where an atomic
UPDATE ... SET count = count + 1 WHERE id = ?avoids unnecessary conflict retries. - CRDT real-time collaborative documents where concurrent edits merge at the character or operation level instead of rejecting whole-row saves.
Customize queue name, retries, or delay
Use enqueue_with_options_in_tx when a job needs a named queue, a custom max_attempts, or a delay in seconds:
#![allow(unused)]
fn main() {
ctx.jobs
.enqueue_with_options_in_tx(
&mut tx,
"send_order_receipt",
"mail",
json!({ "order_id": order_id }),
8, // max_attempts (default is 5)
30, // delay_seconds before eligible to run
)
.await?;
}
Failed jobs retry with exponential backoff (2^attempts seconds, capped at 1024 seconds). Once attempts >= max_attempts, the worker marks the job status as "dead".
Dispatch outbound webhooks in the same transaction
Call ctx.webhooks.dispatch_in_tx before committing when an action notifies external webhook subscribers:
#![allow(unused)]
fn main() {
ctx.webhooks
.dispatch_in_tx(
&mut tx,
&account_id,
"order.placed",
&json!({ "order_id": order_id }),
)
.await?;
}
dispatch_in_tx inserts HMAC-SHA256 signed rows into slabs_webhook_deliveries and enqueues "slabs.deliver_webhook" jobs on the "webhooks" queue inside the same transaction. During live HTTP delivery (SLABS_WEBHOOKS_LIVE=true), slabs-webhooks uses a custom SSRF-safe DNS resolver that blocks loopback, private, link-local, metadata, and IPv4-mapped IPv6 addresses at connect time, disables HTTP redirects, enforces a 10-second timeout, and caps response reads at 2 KiB.
Write the matching background job
Create jobs/send_order_receipt.rs. slabs-build discovers every .rs file in jobs/ at compile time and registers it with JobRegistry.
#![allow(unused)]
fn main() {
// jobs/send_order_receipt.rs
use serde_json::Value;
use slabs::prelude::*;
pub fn job() -> JobDef {
JobDef::new("send_order_receipt", run)
.queue("default")
.max_attempts(5)
.summary("Send an order receipt email")
}
async fn run(ctx: AppCtx, payload: Value) -> SlabResult<()> {
let order_id = payload
.get("order_id")
.and_then(|v| v.as_str())
.ok_or_else(|| SlabError::bad_request("missing order_id"))?;
let user_id = payload
.get("user_id")
.and_then(|v| v.as_str())
.ok_or_else(|| SlabError::bad_request("missing user_id"))?;
let (email,): (String,) = sqlx::query_as("SELECT email FROM users WHERE id = ?")
.bind(user_id)
.fetch_one(ctx.db.reader())
.await?;
ctx.mail
.send(Email {
from: String::new(),
to: email,
subject: format!("Order {order_id} confirmed"),
text_body: format!("Your order {order_id} is confirmed."),
html_body: None,
})
.await?;
Ok(())
}
}
Never call ctx.mail.send(...) inside an open database transaction. Mailer::send performs network I/O when Resend or SMTP is configured and writes to slabs_mail_outbox outside your transaction. Always enqueue a job inside tx and send email from the job handler.
Attach a recurring schedule
To enqueue a job on a fixed interval while the server runs, attach ScheduleDef::every in src/lib.rs:
#![allow(unused)]
fn main() {
use serde_json::json;
use slabs::{ScheduleDef, SlabsApp};
use std::time::Duration;
let app = SlabsApp::boot(config, &MIGRATOR, collect_slabs(), collect_jobs()).await?;
let app = app.with_schedules(vec![
ScheduleDef::every(Duration::from_secs(3600), "cleanup_expired", json!({})),
]);
}
Drain jobs synchronously in tests
In your co-located #[tokio::test], call app.drain_jobs().await to execute every ready queued job right away, or call app.run_job_now("job_name", payload).await to invoke one handler directly:
#![allow(unused)]
fn main() {
let processed = app.drain_jobs().await;
assert_eq!(processed, 1);
let emails = app.sent_emails().await;
assert_eq!(emails.len(), 1);
assert!(emails[0].subject.contains("confirmed"));
}
Validate multiple input fields at once
When an endpoint accepts several fields, collect all errors in one pass with Validate::new(). Calling .finish()? returns Ok(()) when every check passes or Err(SlabError::ValidationErrors(...)) (HTTP 422 Unprocessable Entity):
#![allow(unused)]
fn main() {
let mut v = Validate::new();
v.required("sku", &input.sku)
.max_len("sku", &input.sku, 64)
.email("receipt_email", &input.receipt_email)
.one_of("priority", &input.priority, &["standard", "rush"])
.check("quantity", input.quantity > 0, "must be greater than zero");
v.finish()?;
}
Validate supports required, min_len, max_len, email, url, one_of, check, push, is_empty, errors, and finish. When validation fails, Slabs responds with HTTP 422 and sorted field keys:
{
"error": "validation_error",
"fields": {
"quantity": ["must be greater than zero"],
"sku": ["is required"]
}
}
Paginate lists with keyset cursors
Avoid OFFSET scans and extra COUNT(*) queries by pairing Pagination with CursorPage::from_rows. Extract Query(page): Query<Pagination>, fetch page.fetch_limit(default, max) rows (clamped_limit + 1), and pass the Vec to CursorPage::from_rows:
#![allow(unused)]
fn main() {
use axum::{extract::{Query, State}, Json};
use serde::Serialize;
use slabs::prelude::*;
#[derive(Debug, Serialize, sqlx::FromRow)]
struct OrderRow {
id: String,
sku: String,
created_at: String,
}
async fn handle(
State(ctx): State<AppCtx>,
Query(page): Query<Pagination>,
) -> SlabResult<Json<CursorPage<OrderRow>>> {
let limit = usize::try_from(page.clamped_limit(20, 100)).unwrap_or(20);
let fetch_limit = page.fetch_limit(20, 100);
let rows: Vec<OrderRow> = if let Some(cursor) = &page.cursor {
sqlx::query_as(
"SELECT id, sku, created_at FROM orders
WHERE id < ?
ORDER BY id DESC
LIMIT ?",
)
.bind(cursor)
.bind(fetch_limit)
.fetch_all(ctx.db.reader())
.await?
} else {
sqlx::query_as(
"SELECT id, sku, created_at FROM orders
ORDER BY id DESC
LIMIT ?",
)
.bind(fetch_limit)
.fetch_all(ctx.db.reader())
.await?
};
let result = CursorPage::from_rows(rows, limit, |row| row.id.clone());
Ok(Json(result))
}
}
CursorPage::from_rows truncates rows to limit, sets has_more to true when the extra row existed, and sets next_cursor from the last retained row (or None on the final page).
Record transactional audit logs
Call ctx.audit.record_in_tx inside an open transaction to write an immutable entry into slabs_audit_log atomically with your domain update. If the transaction rolls back, the audit row rolls back too.
#![allow(unused)]
fn main() {
let mut tx = ctx.db.begin().await?;
sqlx::query("UPDATE rooms SET archived_at = ? WHERE id = ?")
.bind(&now)
.bind(&room_id)
.execute(&mut *tx)
.await?;
ctx.audit
.record_in_tx(
&mut tx,
Some(&session.user_id),
"room.archived",
"room",
&room_id,
&json!({ "reason": input.reason }),
)
.await?;
tx.commit().await?;
}
record_in_tx returns the generated aud_<ulid> ID. Read audit history on the read pool with ctx.audit.list_for_target("room", &room_id, 50).await? or ctx.audit.list_recent(50).await?. Both return Vec<AuditEntry>.
Verify inbound webhooks and block replays
When your app receives webhooks from external providers (such as Stripe, GitHub, or another Slabs app), verify the raw request bytes before parsing JSON, check the timestamp window, and claim an idempotency key inside the same database transaction as your domain update:
#![allow(unused)]
fn main() {
use axum::{
body::Bytes,
extract::State,
http::{HeaderMap, StatusCode},
};
use slabs::{prelude::*, webhooks::Webhooks};
async fn handle(
State(ctx): State<AppCtx>,
headers: HeaderMap,
body: Bytes,
) -> SlabResult<StatusCode> {
let secret = std::env::var("PROVIDER_WEBHOOK_SECRET")
.map_err(|_| SlabError::internal("missing PROVIDER_WEBHOOK_SECRET"))?;
let sig = headers
.get("x-provider-signature")
.and_then(|v| v.to_str().ok())
.ok_or_else(|| SlabError::unauthorized("missing signature"))?;
if !Webhooks::verify_incoming_hmac_sha256(&secret, &body, sig, "sha256=") {
return Err(SlabError::unauthorized("invalid webhook signature"));
}
let ts: i64 = headers
.get("x-provider-timestamp")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse().ok())
.ok_or_else(|| SlabError::unauthorized("missing timestamp"))?;
if !Webhooks::verify_timestamp_window(ts, 300) {
return Err(SlabError::unauthorized("stale webhook timestamp"));
}
let event: serde_json::Value = serde_json::from_slice(&body)
.map_err(|_| SlabError::bad_request("invalid JSON payload"))?;
let event_id = event["id"]
.as_str()
.ok_or_else(|| SlabError::bad_request("missing event id"))?;
let mut tx = ctx.db.begin().await?;
let claimed = ctx
.webhooks
.claim_idempotency_in_tx(&mut tx, "provider", event_id)
.await?;
if !claimed {
tx.commit().await?;
return Ok(StatusCode::OK);
}
// Apply domain updates and enqueue jobs inside `tx`...
tx.commit().await?;
Ok(StatusCode::OK)
}
}
Pass "" as the prefix argument to verify_incoming_hmac_sha256 when a provider sends a raw hex digest without "sha256=". claim_idempotency_in_tx runs INSERT OR IGNORE INTO slabs_idempotency_keys on tx. It returns Ok(true) on the first claim and Ok(false) on replays. If tx rolls back before commit, the key is released so the provider can retry cleanly.