Expand description
§Graphile Worker RS
A PostgreSQL-backed job queue for Rust applications, based on Graphile Worker.
Graphile Worker RS lets you run durable background jobs from Rust while keeping PostgreSQL as the queue and coordination backend. It supports typed task handlers, delayed jobs, priorities, queues, retries, cron jobs, graceful shutdown, optional dead-worker recovery, lifecycle hooks, CLI tooling, and an admin UI.
§Documentation
- Guide - task-oriented documentation, examples, configuration, operations, and troubleshooting.
- API reference - generated Rust API docs.
- Examples - runnable repository examples.
§Installation
cargo add graphile_workerTokio, rustls, and SQLx are enabled by default:
[dependencies]
graphile_worker = "0.13"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
serde = { version = "1", features = ["derive"] }For async-std, tokio-postgres, native TLS, or OpenTelemetry compatibility features, see the feature flags guide.
§Quick Start
use graphile_worker::{
IntoTaskHandlerResult, JobSpec, TaskHandler, WorkerContext, WorkerOptions,
};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
struct SendEmail {
to: String,
}
impl TaskHandler for SendEmail {
const IDENTIFIER: &'static str = "send_email";
async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
println!("Sending email to {}", self.to);
Ok::<(), String>(())
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let worker = WorkerOptions::default()
.database_url("postgres://postgres:password@localhost/mydb")
.concurrency(5)
.schema("graphile_worker")
.define_job::<SendEmail>()
.init()
.await?;
worker
.create_utils()
.add_job(
SendEmail {
to: "user@example.com".to_string(),
},
JobSpec::default(),
)
.await?;
worker.run().await?;
Ok(())
}For a complete walkthrough, read Quick Start and First Worker.
§Highlights
- PostgreSQL-backed durable queue with
SKIP LOCKEDjob claiming. - Low-latency wakeups through PostgreSQL
LISTEN/NOTIFY. - Typed Rust task handlers and batch task handlers.
- Delayed jobs, priorities, retry attempts, job keys, and named queues.
- Cron-like recurring jobs through the crontab crates.
- Worker utilities for adding, rescheduling, completing, failing, cleaning up, and recovering jobs.
- Optional local queue for batch-fetching jobs and reducing database round trips.
- Graceful shutdown and optional heartbeat-based dead-worker recovery.
- Lifecycle hooks for logging, metrics, validation, and custom policies.
- CLI and admin UI crates for operational workflows.
§Compatibility
This is a Rust rewrite of Graphile Worker. It is mostly compatible with the Node.js version and can run side by side with it when the shared PostgreSQL schema and job contracts match.
One notable implementation difference: the Node.js version uses one worker id per process, while this Rust implementation uses one worker id per worker instance and processes jobs through the enabled async runtime.
See Compatibility for details.
§Development
Common commands:
just lint
just test-docker
just docs
just docs-serve 3002Before committing, run:
just lint
just test-dockerSee CONTRIBUTING.md for contribution details.
§License
MIT. See LICENSE.md.
§Graphile Worker RS
A PostgreSQL-backed job queue implementation for Rust applications. This crate is a Rust port of the Node.js Graphile Worker library.
§Architecture Overview
Graphile Worker uses PostgreSQL as its backend for job storage and coordination. The system consists of several key components:
- Worker: Processes jobs from the queue using the specified concurrency.
- WorkerUtils: Utility functions for job management (adding, removing, rescheduling, etc.).
- TaskHandler: Trait that defines how specific job types are processed.
- Job Specification: Configures job parameters like priority, retry behavior, and scheduling.
- Migrations: Automatic schema management for the database tables.
§Database Schema
Graphile Worker manages its own database schema (default: graphile_worker).
It automatically handles migrations and uses the following tables:
_private_jobs: Stores job data, state, and execution metadata_private_tasks: Tracks registered task types_private_job_queues: Manages job queue names for serialized job execution_private_workers: Tracks active worker instances
§Module Structure
The crate is organized into the following modules:
Re-exports§
pub use cron::Cron;pub use cron::CronBuilder;pub use builder::CronInput;pub use builder::WorkerBuildError;pub use builder::WorkerOptions;pub use context_ext::WorkerContextExt;pub use local_queue::LocalQueue;pub use local_queue::LocalQueueConfig;pub use local_queue::LocalQueueError;pub use local_queue::LocalQueueSignalSender;pub use local_queue::RefetchDelayConfig;pub use runner::Worker;
Modules§
- builder
- Configuration and initialization of worker instances
- context_
ext - cron
- errors
- Error types used throughout the crate
- local_
queue - LocalQueue for batch-fetching jobs to improve throughput
- recovery
- Dead worker recovery
- row_
mapping - runner
- Core worker implementation for running the job queue
- sql
- SQL query implementations for interacting with the database
- sqlx
- streams
- Job stream management for processing jobs
- worker_
utils - Utility functions for job management Utility functions for adding, managing, and maintaining jobs.
Structs§
- Active
Worker Row - After
JobRun - After
JobRun Context - Before
JobRun - Before
JobRun Context - Before
JobSchedule - Before
JobSchedule Context - Cron
JobScheduled - Cron
JobScheduled Context - Cron
Tick - Cron
Tick Context - Crontab
- A crontab defines a task to be executed at a specific time(s)
- Crontab
Fill - A crontab fill represents how long a crontab should be backfilled For instance the server is down for 1 hour, the task should be backfilled for 1 hour
- Crontab
Timer - A crontab timer is a set of crontab values for each field (minutes, hours, days, months, days of week)
- Database
- DbError
- DbJob
DbJobrepresents a job as stored in the database.- DbJob
Data - Named field carrier for constructing a
DbJob. - DbParams
- DbRow
- DbTransaction
- Hook
Registry - Job
JobextendsDbJobwith an additional task_identifier field.- JobBuilder
- Builder for
Job. - JobComplete
- JobComplete
Context - JobDefinition
- Reusable registration value for a
TaskHandler. - JobFail
- JobFail
Context - JobFetch
- JobFetch
Context - JobInterrupted
- JobInterrupted
Context - JobPermanently
Fail - JobPermanently
Fail Context - JobRecovery
- JobRecovery
Context - JobSpec
- JobSpec
Builder - Builder for
JobSpec. - JobStart
- JobStart
Context - Local
Queue GetJobs Complete - Local
Queue GetJobs Complete Context - Local
Queue Init - Local
Queue Init Context - Local
Queue Refetch Delay Abort - Local
Queue Refetch Delay Abort Context - Local
Queue Refetch Delay Expired - Local
Queue Refetch Delay Expired Context - Local
Queue Refetch Delay Start - Local
Queue Refetch Delay Start Context - Local
Queue Return Jobs - Local
Queue Return Jobs Context - Local
Queue SetMode - Local
Queue SetMode Context - Notification
- RawJob
Spec - Schema
- Shared
Task Details - Sweep
Stale Workers Options - Sweep
Stale Workers Result - Task
Details - Worker
Context - Context provided to task handlers when processing a job.
- Worker
Context Builder - Worker
Init - Worker
Init Context - Worker
Recovered - Worker
Recovered Context - Worker
Recovery Config - Dead worker recovery configuration.
- Worker
Shutdown - Worker
Shutdown Config - Worker shutdown behavior.
- Worker
Shutdown Context - Worker
Start - Worker
Start Context - Worker
Utils - The WorkerUtils struct provides a set of utility methods for managing jobs.
Enums§
- Batch
Task Result - Result returned by a batch task handler.
- Cron
JobKey Mode - Behavior when an existing job with the same job key is found is controlled by this setting
- Crontab
Field - Crontab time fields used for validating typed schedule construction.
- Crontab
Timer Error - Error returned when typed schedule constructors receive invalid values.
- Crontab
Value - A crontab value can be a number, a range, a step or any value It is used to represent a crontab value for a specific field (hour, day, month, etc.) When specifying a specific number, range or step, it should be valid for the field (e.g. 0-59 for minutes, 0-23 for hours, etc.)
- DbCell
- DbValue
- Failure
Reason - Hook
Result - JobKey
Mode - JobRecovery
Result - JobSchedule
Result - JobSpec
Builder Error - Error type for JobSpecBuilder
- Local
Queue Mode - Shutdown
Reason - Task
Handler Outcome - Outcome returned by type-erased task handlers.
Constants§
- INFRASTRUCTURE_
RESILIENT_ FLAG - Job flag indicating the job may run for a long time and should use a longer sweep threshold before being recovered from a seemingly-dead worker.
Traits§
- Batch
Task Handler - Core trait for defining batch task handlers.
- Database
Driver - DbExecutor
- DbExecutor
Arg - Event
- From
DbCell - Hook
Output - Interceptable
- Into
Batch Task Handler Result - Trait for converting batch task return types into a standardized result.
- Into
Task Handler Result - Trait for converting task handler return types into a standardized Result.
- Plugin
- Task
Handler - Core trait for defining task handlers in Graphile Worker.
- Transaction
Driver
Functions§
- escape_
identifier - parse_
crontab - Parse a crontab definition into a Vec of crontab
- run_
task_ from_ worker_ ctx - Internal function to execute a task handler from a worker context.
Type Aliases§
- BoxFuture
- Notification
Stream - Shutdown
Signal - A shareable future that completes when a shutdown signal is received.
- Task
Handler Fn - Type-erased function used by workers to run a task from a
WorkerContext.