DocsOperations
Background jobs
Run typed Rust functions after the response, with compile-checked calls, retries, timeouts, and an optional durable store in your own database.
A job is work that runs after the response: sending a receipt, updating a search index, calling an integration. It is an ordinary async function with an attribute. By default the queue is bounded and in memory. Give it a store and accepted jobs live in the application's database, where they survive a crash.
Write a job
The generator adds the function to src/jobs.rs, declares the module, and makes sure workers start. A parameter with no type is a String.
cargo rahti generate job send_receipt --params order_id:i64use rahti::job;
use rahti::jobs::JobError;
#[job(attempts = 5, timeout_secs = 20)]
pub async fn send_receipt(order_id: i64) -> Result<(), JobError> {
let order = load_order(order_id)
.await
.map_err(|error| JobError::retry(error.to_string()))?;
let Some(order) = order else {
return Err(JobError::discard(format!("order {order_id} no longer exists")));
};
deliver_receipt(&order)
.await
.map_err(|error| JobError::retry(error.to_string()))
}Jobs live in src/jobs.rs or in files under src/jobs/. #[job] refuses to compile anywhere else, because the build reads those files into the manifest and a job outside them would run invisibly. A job takes owned parameters that serialize, and returns nothing, Result<(), JobError>, or rahti::Result<()>. Generics, self, borrowed parameters and returned values are compile errors that name the form to write.
| #[job(…)] option | Default | Meaning |
|---|---|---|
| name = "billing.receipt" | the function's name | The stored name: 1 to 64 ASCII letters, numbers, -, _ or . |
| attempts = 5 | the queue's, 3 | Total attempts, including the first. |
| timeout_secs = 20 | the queue's, 30 | The limit on one attempt. |
| backoff_ms = 250 | the queue's, 250 | The delay after the first failure, doubling each time. |
| max_backoff_ms = 30000 | the queue's, 30000 | The largest delay. |
Enqueue a job
The attribute gives the function's name a second meaning. The name still calls the function, so a test runs send_receipt(7).await directly, and send_receipt:: reaches the queue.
let order = save_order(input).await?;
crate::jobs::send_receipt::enqueue(order.id)
.await
.map_err(|error| rahti::Error::internal(error.to_string()))?;A misspelled job, a missing argument and a wrong type are compile errors on that line, not a string that fails when a worker reads it.
| Call | Result |
|---|---|
| send_receipt::enqueue(id) | A JobId. A memory queue waits for capacity. |
| send_receipt::enqueue_unique("key", id) | Some(JobId), or None while a pending or running job holds the key. |
| send_receipt::request(id) | A NewJob value, for a store to insert in a transaction. |
| send_receipt::payload(id) | The stored arguments, for a schedule. |
| send_receipt::NAME | The stored name. |
Enqueue after the authoritative transaction commits, because a fast worker can otherwise observe state that later rolls back. Pass an id and load the rest in the handler: parameters are not encrypted, so they never carry sessions, credentials, tokens, or unnecessary personal information.
Start the workers
A new project already calls rahti::jobs::Jobs::new().install() in initialize_application. It starts workers for every #[job] linked into the binary and makes that the queue enqueue reaches. With no jobs it starts nothing, and a static export starts nothing because rendering must not run side effects. Configure it in code, because this is application policy.
// src/lib.rs, in initialize_application, after the database.
rahti::jobs::Jobs::new()
.workers(4)
.capacity(1_024)
.attempts(3)
.backoff(Duration::from_millis(250), Duration::from_secs(30))
.attempt_timeout(Duration::from_secs(20))
.shutdown_grace(Duration::from_secs(30))
.install();Defaults are one worker, capacity 1,024 in memory and 10,000 in a store, three attempts, 250 ms initial exponential backoff capped at 30 seconds, a 30-second attempt timeout, and a 30-second shutdown grace. A #[job] option overrides the attempt policy for that job.
Durable jobs
In a project with a database, one command keeps jobs there. Rahti itself depends on no ORM: the adapter, the entity and the migration are written into your application, and they are yours.
cargo rahti generate job-store| File | Purpose |
|---|---|
| src/job_store.rs | SeaJobStore, the adapter, and enqueue_in. |
| src/models/job.rs | The job table's entity. |
| src/migrations/m…_create_job.rs | The migration that creates it. |
Apply the migration, then add a test that holds the adapter to the store contract. It needs an empty job table and fails on the first broken rule.
#[tokio::test]
async fn the_job_store_keeps_the_contract() {
setup().await;
rahti::jobs::conformance(&crate::job_store::SeaJobStore).await;
}| With a store | What changes |
|---|---|
| A crash | Loses nothing. A job is committed before enqueue returns. |
| Several processes | Share one queue. On SQLite that means one machine; Postgres and MySQL are designed for several. |
| A dead worker | Its five-minute lease expires, another worker claims the job, and the interrupted attempt counts. |
| A retry | Survives a restart, because backoff is a stored due time. |
| A failure | Stays, with its last error, until store.purge deletes it. Successful jobs are deleted. |
| Shutdown | Does not drain. Pending jobs stay stored, and running jobs that outlast the grace return to pending without spending an attempt. |
| A full queue | enqueue returns Full rather than waiting, because the bound belongs to a shared table. |
In the same transaction
A job and the write it follows can commit together, so nothing can leave one without the other, including a crash between them. A rollback removes the job with the row, and workers find a committed one on their next poll.
use sea_orm::TransactionTrait;
let transaction = crate::db::db().begin().await?;
let order = save_order(&transaction, input).await?;
crate::job_store::enqueue_in(
&transaction,
crate::jobs::send_receipt::request(order.id)?,
)
.await?;
transaction.commit().await?;Retry and idempotency
| Handler result | Outcome |
|---|---|
| Ok(()) | The job completed. |
| JobError::retry | Retry with capped exponential backoff. |
| rahti::Error | Retry with capped exponential backoff. |
| JobError::discard | Stop immediately for permanent input or policy failure. |
| panic or timeout | Isolate the attempt and retry within the configured limit. |
A stored payload that no longer reads as the function's parameters is discarded, because it can never succeed. An added Option parameter reads as None, so it accepts jobs stored before it existed.
Shutdown
The scaffold calls jobs::finish_shutdown().await after HTTP shutdown. Workers reject new jobs and finish what they hold, and a memory queue also drains what is queued, up to the grace deadline.
Seeing what jobs are doing
During development, cargo rahti status and the MCP server_status tool report handlers, counters, stored counts, and the newest failures with their errors. The MCP list_jobs tool and jobs in .rahti/manifest.json give every job's parameters, policy, source location, and the exact call that enqueues it. Metrics and events report queue, retry, timeout, panic, failure and abandoned work without logging payloads.
