apalis-diesel-postgres
PostgreSQL storage backend for Apalis
implemented with Diesel and r2d2.
The crate's headline feature is a transactional enqueue API —
PostgresStorage::push_with_conn — that
lets you insert a job in the same PgConnection transaction as your business
data. If the business transaction commits, the job is enqueued; if it rolls
back, no job is enqueued and no LISTEN/NOTIFY is delivered. That removes the
classic "resource written, job missing" split-brain without a separate outbox
table.
The crate accepts any diesel::r2d2::Pool<ConnectionManager<PgConnection>> —
you keep using the pool you already wire up — and ships everything else apalis
needs: migrations, polling/notify-driven dequeue, locking, ack, retries,
orphan re-enqueue, admin queries, and MakeShared for many-queue setups.
Status
Targets the Apalis 1.0 release candidate: apalis-core 1.0.0-rc.9,
apalis-sql 1.0.0-rc.9, apalis-codec 0.1.0-rc.9, diesel 2.3. Schema
compatible with Apalis SQL storage (apalis.jobs, apalis.workers).
Installation
[]
= { = "0.2", = ["tokio"] }
= { = "2.3", = ["postgres", "r2d2", "chrono", "serde_json"] }
= { = "1", = ["derive"] }
Runtime features (pick one):
tokio(default) — Diesel work runs ontokio::task::spawn_blocking.ntex— Diesel work runs onntex_rt::spawn_blocking.- no feature — Diesel work runs on the calling thread (compile-time compatibility only; can stall an async executor under load).
If both tokio and ntex are enabled, tokio wins. Treat --all-features
as a compatibility check, not a runtime shape.
Quick start
Build a pool, run the migrations once at startup, create a storage. The worker side (poll/lock/ack) follows the regular apalis APIs — see the Running an apalis worker section below for a full end-to-end wiring.
# async
To enqueue tasks from a request handler atomically with business data, see
the outbox section. To run the
example end-to-end against a real database, see
examples/outbox.rs:
DATABASE_URL=postgres://127.0.0.1:5432/apalis_diesel_postgres \
Running an apalis worker
Add apalis to your Cargo.toml; it re-exports WorkerBuilder, Worker,
Data and the BoxDynError alias used by handlers. PostgresStorage<T>
satisfies apalis's Backend + Send + Sync requirement, so it slots straight
into WorkerBuilder::backend(...).
# use *;
# use ;
#
#
# async
# async
Calling push_with_conn from inside a handler
The outbox pattern isn't limited to HTTP handlers — the same transactional
guarantees apply when one job needs to enqueue a follow-up job atomically
with its own database writes. Inject the follow-up queue's storage via
Data<...>, hop onto the blocking pool, and share a &mut PgConnection
between the business write and push_with_conn:
# use *;
# use ;
# use Connection;
#
#
#
#
async
Wire the follow-up storage into the worker via .data(...):
# use *;
# use PostgresStorage;
#
#
#
#
# async #
#
End-to-end runnable example: examples/worker.rs.
DATABASE_URL=postgres://127.0.0.1:5432/apalis_diesel_postgres \
Transactional enqueue (outbox pattern)
When a request handler must persist a resource (an order, a user, a file upload) and enqueue a follow-up job (send confirmation email, kick off processing), the two writes have to either both happen or both not happen. If they live in different transactions, you get the classic split-brain:
- Resource written, job missing → silent loss of work.
- Job written, resource rolled back → consumer wakes up, fails to find the row, retries forever.
PostgresStorage::push_with_conn lets you insert the apalis task on the
same &mut PgConnection your handler is already using, so the task
INSERT is part of your business transaction. If the transaction commits, the
job is enqueued; if it rolls back, no job is enqueued and no NOTIFY is
delivered. There is no manual outbox table to drain.
# use ;
# use ;
# use ;
#
#
# async
Key points:
backend_poolis your service's pool, separate from the pool you hand toPostgresStorage. See Connection pool isolation.- The whole block runs inside
tokio::task::spawn_blocking—push_with_connis synchronous and would otherwise stall the runtime. NOTIFYfires when the outer transaction commits, so listeners only observe committed work.
push_task_with_conn — full control
push_with_conn(args) is the ergonomic path: auto Ulid, default scheduling.
For idempotency_key, priority, run_at (delayed run), max_attempts,
custom metadata, or a pre-allocated task_id, build a [PgTask<Args>]
and call push_task_with_conn:
# use ;
# use PgConnection;
# use ;
#
#
#
Constraints
- Synchronous — wrap in
tokio::task::spawn_blockingfrom async code so the whole transaction stays on one blocking task. - Don't reuse this connection for unrelated apalis operations (fetch/ack/heartbeat) — those live on the apalis pool.
- Idempotency conflict rolls back only the apalis batch via SAVEPOINT;
the outer transaction stays alive. Decide whether to commit your business
writes or roll the whole transaction back from
Err(InvalidArgument). - No outer transaction → Diesel auto-commits the INSERT; the call still works, but you lose the outbox guarantee.
Connection pool isolation
Do not share the apalis pool with your HTTP request handlers or other
unrelated workloads. Apalis holds long-lived connections (fetcher
polling/LISTEN, lifecycle keep-alive, listener thread). If the application
exhausts the pool under load, the fetcher and heartbeat stall; lifecycle
marks the worker dead and re-enqueues its in-flight tasks, which produces
more load on the same pool — a cascading failure that is hard to recover
from while it is happening.
Run two separate r2d2 pools against the same PostgreSQL database — one
for your web service, one for apalis — and size them independently:
use ;
// Web/backend pool — sized for request concurrency.
let backend_pool = build_pool_with?;
// Apalis pool — sized for worker concurrency + lifecycle + listeners.
// Rough rule: worker_concurrency + 2 + listeners.
let apalis_pool = build_pool_with?;
let storage = new_with_config;
// Use `backend_pool.get()` + `storage.push_with_conn(conn, args)` from
// request handlers to enqueue inside business transactions.
# Ok::
Recommendations:
- Set a short
connection_timeout(1–3 s) on both pools so a starved pool fails loudly instead of hanging request handlers. - Set
statement_timeouton the session via your connection setup if workloads need it. - Monitor pool saturation via
pool.state()(connections,idle_connections) on both pools.
Storage modes
use ;
use ;
type PgPool = ;
new_with_notify and SharedPostgresStorage use LISTEN "apalis::job::insert" to wake workers on insert. Polling stays as a
fallback. Each notify-mode storage pins one extra pooled connection while
the listener is alive — size the apalis pool accordingly.
Examples
examples/outbox.rs — runnable, demonstrates commit /
rollback / idempotency-conflict behaviour against a real database:
DATABASE_URL=postgres://127.0.0.1:5432/apalis_diesel_postgres \
Runtime errors
The backend annotates common database failures with operation context so worker logs point at the failed lifecycle step:
- Missing migrations:
database error while fetching queued jobs: …, with a hint to callapalis_diesel_postgres::setup(&pool).await. - Pool acquisition failures mention
DATABASE_URL, PostgreSQL reachability, and pool capacity. - Lock failures for non-lockable jobs:
task not found while locking task, with the task id and queue. Usually means the job is delayed, completed, already locked, or in another queue. - Acknowledgement races:
stale acknowledgementwhen the stored lock no longer matches the worker/attempt/lock timestamp being ack'd. - Heartbeat failures for missing worker rows:
worker not registered, instead of a generic update-count mismatch. - Codec failures:
failed to decode task payload or result with the configured codec— payload was written with a different codec or is corrupt. - Notification listener failures surface as stream errors. Polling still
fetches jobs;
LISTEN/NOTIFYwakeups stop until the notify stream is recreated.
Public types
use ;
Type aliases:
PgPool = Pool<ConnectionManager<PgConnection>>PgContext = SqlContext<PgPool>PgTask<Args> = Task<Args, PgContext, Ulid>PgTaskId = TaskId<Ulid>CompactType = Vec<u8>
Local development
The shell exports DATABASE_URL=postgres://127.0.0.1:5432/apalis_diesel_postgres
and stores data in ./.pgdata. Editor config for Zed is generated automatically;
opt in to MCP config with APALIS_DIESEL_POSTGRES_WRITE_MCP=1 nix develop.
For the full pre-PR check list (cargo fmt, multiple cargo check/cargo test matrices, doc warnings), see CONTRIBUTING.md. The
quick smoke path is:
DATABASE_URL=postgres://127.0.0.1:5432/apalis_diesel_postgres \
APALIS_DIESEL_POSTGRES_REQUIRE_DATABASE=1 \