asyncq-postgres 0.2.2

PostgreSQL backend for asyncq — background jobs without Redis, transactional enqueue with SKIP LOCKED
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# asyncq

[![Crates.io](https://img.shields.io/crates/v/asyncq.svg)](https://crates.io/crates/asyncq)
[![Documentation](https://docs.rs/asyncq/badge.svg)](https://docs.rs/asyncq)
[![CI](https://github.com/biplabku/asyncq/actions/workflows/ci.yml/badge.svg)](https://github.com/biplabku/asyncq/actions/workflows/ci.yml)
[![License](https://img.shields.io/crates/l/asyncq.svg)](LICENSE-MIT)

**Type-safe background jobs for Rust.** Define once with `#[derive(Job)]`, run anywhere.

```toml
[dependencies]
asyncq = "0.2"
asyncq-redis = "0.2"   # Redis backend (recommended for production)
# asyncq-postgres = "0.2"  # PostgreSQL backend — no Redis needed
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
```

> **Note:** `#[derive(Job)]` comes from `asyncq` directly — you do not need to add `asyncq-derive` as a separate dependency.

## Why asyncq?

Most Rust job queues copy the Tower/Service pattern — you write boilerplate for every job type. asyncq takes a different approach: **derive macros with compile-time validation**.

```rust
// asyncq — define your job, implement perform, done
#[derive(Job, Serialize, Deserialize)]
#[job(queue = "emails", retries = 3)]
struct WelcomeEmail { to: String }

impl Perform for WelcomeEmail {
    async fn perform(self, ctx: JobContext) -> JobResult {
        send_email(&self.to).await
    }
}
```

Compare to apalis (Tower-based):
```rust
// apalis — define job, define service, define layer, wire builder
struct WelcomeEmail { to: String }
async fn send_email(job: WelcomeEmail, ctx: JobContext) -> Result<(), Error> { ... }

WorkerBuilder::new("email-worker")
    .layer(RetryLayer::new(DefaultRetryPolicy))
    .layer(TimeoutLayer::new(Duration::from_secs(30)))
    .source(storage.clone())
    .build_fn(send_email)
```

**asyncq moves configuration to the type level** — retries, timeouts, and queue names are part of the job definition, not runtime wiring. Typos become compile errors.

## Quick start

```rust
use asyncq::{Job, Perform, JobContext, JobResult, Queue, Worker};
use asyncq_redis::RedisBackend;
use serde::{Serialize, Deserialize};

#[derive(Job, Serialize, Deserialize)]
#[job(queue = "emails", retries = 3)]
struct WelcomeEmail { to: String }

impl Perform for WelcomeEmail {
    async fn perform(self, _ctx: JobContext) -> JobResult {
        println!("Sending to {}", self.to);
        Ok(())
    }
}

#[tokio::main]
async fn main() {
    let backend = RedisBackend::new("redis://127.0.0.1/").await.unwrap();
    let queue = Queue::new(backend);

    // Enqueue from anywhere
    queue.enqueue(WelcomeEmail { to: "user@example.com".into() }).await.unwrap();

    // Process
    Worker::new(queue)
        .register::<WelcomeEmail>()
        .concurrency(10)
        .run()
        .await;
}
```

## Features

### State injection

Pass app state once at startup. Access via `ctx.state::<T>()` — same pattern as axum.

```rust
let pool = Arc::new(PgPool::connect("postgres://...").await?);
let queue = Queue::new(backend).with_state(Arc::clone(&pool));

impl Perform for ProcessOrder {
    async fn perform(self, ctx: JobContext) -> JobResult {
        let pool = ctx.state::<Arc<PgPool>>().expect("pool");
        sqlx::query!("UPDATE orders SET status = 'processed' WHERE id = $1", self.id)
            .execute(pool.as_ref()).await?;
        Ok(())
    }
}
```

### Scheduling

```rust
queue.enqueue(job).await?;                                    // now
queue.enqueue_in(job, Duration::from_secs(3600)).await?;      // 1 hour
queue.enqueue_at(job, Utc::now() + Duration::days(1)).await?; // tomorrow
```

### Cron scheduling

Run jobs on a recurring schedule:

```rust
use asyncq::Scheduler;

#[derive(Job, Serialize, Deserialize, Default)]
#[job(queue = "reports")]
struct DailyReport;

let scheduler = Scheduler::new(queue.clone())
    .register::<DailyReport>("0 0 9 * * *")      // every day at 9am
    .register::<WeeklyDigest>("0 0 0 * * Sun");  // every Sunday at midnight

// Run alongside your worker
tokio::select! {
    _ = scheduler.run() => {}
    _ = worker.run() => {}
}
```

Cron format: `second minute hour day-of-month month day-of-week`

### Error handling

```rust
impl Perform for ProcessPayment {
    async fn perform(self, ctx: JobContext) -> JobResult {
        match charge_card(&self.token).await {
            Ok(_) => Ok(()),
            Err(e) if e.is_retryable() => Err(JobError::retry(e)),   // retry with backoff
            Err(e) => Err(JobError::discard(e)),                     // skip to DLQ
        }
    }
}
```

Backoff is exponential: `30s × 2^attempt`, capped at 1 hour.

### Job attributes

```rust
#[derive(Job, Serialize, Deserialize)]
#[job(
    queue = "payments",    // required
    retries = 5,           // default: 10
    timeout_secs = 30,     // optional
    kind = "ProcessPay",   // optional: custom type identifier
)]
struct ProcessPayment { amount_cents: u64 }
```

### Worker options

```rust
Worker::new(queue)
    .register::<WelcomeEmail>()
    .register::<ProcessPayment>()
    .concurrency(20)                          // concurrent jobs
    .queues(["critical", "default", "low"])   // priority order
    .stuck_timeout(Duration::from_secs(120))  // requeue stuck jobs
    .run()
    .await;
```

### Graceful shutdown

```rust
worker.run_graceful(async {
    tokio::signal::ctrl_c().await.ok();
}).await;
```

### Dead-letter queue

```rust
let dead = queue.dead_jobs("payments", 50, 0).await?;
queue.retry_dead(dead[0].id).await?;           // retry one
queue.retry_all_dead("payments").await?;       // retry all
```

### Queue stats

```rust
let stats = queue.stats("emails").await?;
println!("pending={} running={} dead={}", stats.pending, stats.running, stats.dead);
```

## Tested under faults

asyncq is tested with [queue-chaos](https://github.com/biplabku/queue-chaos), a fault-injection harness that runs a
steady stream of jobs while it kills workers, pauses them past their lease, restarts the broker, and cuts the network
between workers and the broker. A checker then reads the event log and counts jobs that were lost or that ran on
two workers at the same time.

The harness found five bugs in earlier versions, all fixed:

- **0.2.0:** workers didn't heartbeat, so long jobs were reaped and re-run while still running; the Redis reaper
  wasn't exclusive, so two workers could run the same job; reaped jobs never reached the dead-letter queue; a
  stale worker that resumed could ack or nack a job someone else had already re-claimed.
- **0.2.1:** Redis state transitions (claim, reap, ack/nack, delayed promotion) ran as several commands, so a worker
  killed in between could strand a job. Each transition is now a single Lua script.

Results (full tables, settings and raw data in
[FINDINGS.md](https://github.com/biplabku/queue-chaos/blob/main/FINDINGS.md)):

| Test | Version | Lost | Ran concurrently |
|---|---|---|---|
| Worker killed every 0.2 s, 24,000 jobs, Redis | 0.2.0 | 22 | 0 |
| Worker killed every 0.2 s, 24,000 jobs, Redis | 0.2.1 | 0 | 0 |
| Network partitions of 5 s and 15 s, Redis and Postgres | 0.2.1 | 0 | 0 |
| Kill, pause and broker restart, Redis and Postgres | 0.2.0 | 0 | 0 |
| Kill, pause and broker restart, Redis | 0.1.9 (control) | 0 | up to 1.1% of jobs |

asyncq is at-least-once: a job can run again if its worker dies after finishing it but before the ack, or if a
paused worker comes back after its lease expired. Make handlers idempotent.

## Architecture

`asyncq` itself defines the job model (`Job`, `Perform`, `Worker`, `Queue<B>`)
and is generic over a storage `Backend`. A backend crate (Redis or Postgres)
implements that trait to give you durable storage; an integration crate
(axum or actix-web) mounts an admin API on top of the same `Queue<B>` your
worker uses. Enqueue and worker processes both talk to the same backend, so
they can be the same binary or split across services.

```mermaid
flowchart LR
    subgraph App["Your application"]
        Producer["Producer<br/>queue.enqueue(job)"]
        WorkerNode["Worker<br/>register + run()"]
    end

    subgraph Core["asyncq (core)"]
        QueueT["Queue&lt;B&gt;<br/>generic over Backend"]
        JobTrait["Job / Perform / JobContext"]
    end

    subgraph Store["Storage backend (pick one)"]
        Redis["asyncq-redis<br/>ZSET + LIST"]
        Postgres["asyncq-postgres<br/>SKIP LOCKED"]
    end

    subgraph Admin["Framework integration (optional)"]
        Axum["asyncq-axum<br/>admin_with_queues()"]
        Actix["asyncq-actix<br/>admin_with_queues()"]
    end

    Producer -->|enqueue / enqueue_in / enqueue_at| QueueT
    QueueT -->|claim / ack / nack| Redis
    QueueT -->|claim / ack / nack| Postgres
    Redis -->|pending jobs| WorkerNode
    Postgres -->|pending jobs| WorkerNode
    WorkerNode -->|perform| JobTrait

    QueueT -. stats / dlq / retry .-> Axum
    QueueT -. stats / dlq / retry .-> Actix
```

Enqueue writes a job record into the backend; the worker polls (or blocks on)
the same backend to claim jobs, executes `Perform::perform`, and acks or
retries/dead-letters on failure. The admin crates read and mutate that same
`Queue<B>` over HTTP — they don't add a second source of truth.

## Backends and integrations

| Crate | Use case |
|-------|----------|
| [`asyncq-redis`]https://crates.io/crates/asyncq-redis | Production Redis backend — fast, battle-tested |
| [`asyncq-postgres`]https://crates.io/crates/asyncq-postgres | PostgreSQL — no Redis needed, transactional outbox |
| [`asyncq-axum`]https://crates.io/crates/asyncq-axum | Axum admin API + live Prometheus metrics |
| [`asyncq-actix`]https://crates.io/crates/asyncq-actix | Actix-web admin API + live Prometheus metrics |

### PostgreSQL + transactional outbox

Enqueue jobs in the same transaction as your business logic — if the transaction rolls back, so does the job.

```rust
use asyncq_postgres::PostgresBackend;

let backend = PostgresBackend::new("postgres://...").await?;
backend.migrate().await?;  // creates asyncq_jobs table

let mut tx = pool.begin().await?;
sqlx::query("INSERT INTO orders ...").execute(&mut *tx).await?;
backend.enqueue_in_tx("SendReceipt", "emails", payload, 3, Utc::now(), &mut tx).await?;
tx.commit().await?;  // job visible only after commit
```

### Admin API (asyncq-axum / asyncq-actix)

Mount admin endpoints to inspect and manage your queues in production.

**Axum:**
```rust
use asyncq_axum::admin_with_queues;
use axum::Router;

let app = Router::new()
    .nest("/admin", admin_with_queues(queue.clone(), vec!["emails".into(), "payments".into()]));
```

**Actix-web:**
```rust
use asyncq_actix::admin_with_queues;
use actix_web::{web, App};

App::new()
    .service(
        web::scope("/admin")
            .configure(admin_with_queues(queue.clone(), vec!["emails".into(), "payments".into()]))
    );
```

| Endpoint | Description |
|----------|-------------|
| `GET /queues/:name` | Queue stats (pending, running, dead) |
| `GET /queues/:name/dlq` | Dead jobs (paginated: `?limit=50&offset=0`) |
| `POST /queues/:name/dlq/retry-all` | Requeue all dead jobs |
| `DELETE /queues/:name/dlq/:id` | Retry one dead job by ID |
| `GET /metrics` | Live Prometheus gauges per queue |

**Prometheus output** (with `admin_with_queues`):
```
asyncq_jobs_pending{queue="emails"} 3
asyncq_jobs_running{queue="emails"} 1
asyncq_jobs_dead{queue="emails"} 0
asyncq_jobs_completed{queue="emails"} 142
```

## Testing

Use `InMemoryBackend` — no Redis required:

```rust
#[tokio::test]
async fn test_my_job() {
    let backend = InMemoryBackend::new().with_immediate_retries();
    let queue = Queue::new(backend.clone());

    queue.enqueue(MyJob { .. }).await.unwrap();
    Worker::new(queue).register::<MyJob>().run_once().await.unwrap();

    assert_eq!(backend.completed_count("default").await, 1);
}
```

`run_once()` processes all pending jobs and returns — no Ctrl-C needed.

## Feature flags

`asyncq` ships with the `scheduler` feature enabled by default. To opt out of the `cron` dependency (e.g., serverless environments where you never use `Scheduler`):

```toml
asyncq = { version = "0.2", default-features = false }
```

## Roadmap

- [x] **Cron scheduling** — `Scheduler::register::<Job>("0 0 9 * * *")`
- [x] **Actix-web integration** — `asyncq-actix` admin API + Prometheus metrics
- [x] **Live Prometheus metrics** — `admin_with_queues` exposes per-queue gauges
- [ ] **Unique jobs** — deduplicate by payload hash
- [ ] **Middleware** — before/after hooks
- [ ] **Rate limiting** — per-queue throttling
- [ ] **Job chains** — `JobA.then(JobB).then(JobC)`

## Changelog

### 0.2.2
- Docs only: fault-injection results in the README

### 0.2.1
- Redis: every job state transition (claim, reap, ack/nack, delayed promotion) is now one atomic Lua script. A
  worker killed mid-transition could strand a job; under a kill every 0.2 s, 0.2.0 lost 22 of 24,000 jobs, 0.2.1 lost 0
- Claim polls instead of `BRPOP`

### 0.2.0
- Workers heartbeat while a job runs, so long jobs are no longer reaped and re-run mid-flight
- Redis reaper is exclusive; two workers can no longer run the same job
- Reaped jobs that run out of attempts go to the dead-letter queue (Redis also no longer decrements the attempt)
- Add `Backend::ack_claim` / `nack_claim`, fenced by attempt, so a stale worker can't ack or nack a re-claimed job.
  Default impls keep third-party backends compiling

### 0.1.7 – 0.1.9
- Fix completed job count in the Redis backend
- Fix `pg_type` race when `migrate()` runs concurrently (Postgres)
- Add `asyncq-postgres` examples (basic and transactional outbox)
- Fix docs.rs links on sub-crates, add LICENSE

### 0.1.6
- Add `asyncq-actix` — actix-web admin API with the same endpoints as `asyncq-axum`
- Add `admin_with_queues` to both axum and actix integrations — live Prometheus gauges per queue
- Make `cron` dependency optional via `scheduler` feature (default on, zero breakage)
- Improve keywords across all crates for better crates.io discovery
- Fix `asyncq-postgres` description to highlight "no Redis needed"

### 0.1.5
- Admin REST API via `asyncq-axum` — stats, DLQ, retry, metrics endpoints
- PostgreSQL backend with `SELECT FOR UPDATE SKIP LOCKED`
- `enqueue_in_tx` — transactional outbox for PostgreSQL

### 0.1.4
- Cron scheduling via `Scheduler` — `register::<Job>("0 0 9 * * *")`
- `enqueue_in`, `enqueue_at` — delayed and scheduled jobs
- Redis ZSET-based delayed job promotion

### 0.1.0
- Initial release: `#[derive(Job)]` API, Redis backend, `InMemoryBackend` for tests
- `Worker::run_once` for infrastructure-free testing
- State injection via `Queue::with_state` + `ctx.state::<T>()`
- DLQ with `retry_dead` / `retry_all_dead`

## License

MIT OR Apache-2.0