Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- **Batch claims.** `DatabaseQueue::dequeue_batch(queue, n)` and
`dequeue_batch_leased(queue, weights, lease, n)` claim up to `n` runnable jobs in one
round trip, with the same guarantees as a single claim: each job's lease is written by
the claiming statement, `attempts` is incremented, paused queues, unfinished
dependencies and disabled recurring jobs are honoured, jobs come back in
`priority DESC, scheduled_at ASC` order, and concurrent claimers never get the same job.
PostgreSQL claims with one `UPDATE ... WHERE id IN (SELECT ... LIMIT n FOR UPDATE SKIP
LOCKED) RETURNING ...`; MySQL with `SELECT ... FOR UPDATE SKIP LOCKED LIMIT n` and one
`UPDATE` in the claim transaction (READ COMMITTED, retried on deadlock); `TestQueue`
matches them. Strict priority fills a batch in strict order; weighted priorities pick a
level by weight per batch, fill from it and top up from other levels. At most
`queue::MAX_DEQUEUE_BATCH_SIZE` (1000) jobs per call.
- **`DatabaseQueue::release_job_run`** hands a claimed job that never ran back to
`Pending`, taking back the claim's attempt, so it can run elsewhere at once.
- **Batch-mode workers.** `Worker::with_batch_size(n)` makes a worker claim up to `n` jobs
per poll (`with_batch_processing_enabled(true)` alone keeps `worker::DEFAULT_BATCH_SIZE`
= 1, so existing workers still claim one job at a time), and
`Worker::with_batch_concurrency(m)` runs up to `m` of them at once (default 1). Each job
is processed exactly as in single-job mode (timeouts, retries, hooks, events, spawning,
result storage, encryption, statistics). Jobs waiting for their turn have their leases
renewed by heartbeats, so the stale job reaper never reclaims them while the worker is
alive. A throttle's `max_concurrent` permit is held per claimed job, and a batch claims
no more jobs than it has rate limit tokens (unused tokens are refunded). On shutdown,
claimed jobs that have not started are released at once. Workers without batch
processing claim one job at a time as before. New getters: `is_batch_processing_enabled`,
`batch_size`, `batch_concurrency`. In a local benchmark, batch claims of 50 were 5-6x
faster than single claims on PostgreSQL and MySQL.

## [2.0.1] - 2026-10-10

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ A high-performance, database-driven job queue for Rust with comprehensive featur
- **Job prioritization**: Five priority levels with weighted and strict scheduling algorithms
- **Result storage**: Database and in-memory (per-process, bounded) result storage with TTL and automatic cleanup ([Job Results](docs/job-types.md#job-results))
- **Worker autoscaling**: Dynamic worker pool scaling based on queue depth and configurable thresholds
- **Batch operations**: High-performance bulk job enqueuing with optimized worker processing
- **Batch operations**: Bulk job enqueuing in one transaction, and batch claims: workers can claim many jobs per round trip (`Worker::with_batch_size`), each with its own lease
- **Cron scheduling**: Full cron expression support with timezone awareness
- **Rate limiting**: Token bucket rate limiting with configurable burst limits
- **Monitoring**: Prometheus metrics and advanced alerting (enabled by default)
Expand Down
92 changes: 88 additions & 4 deletions docs/batch-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Batch operations provide:
- **Atomic enqueue**: a batch is stored completely or not at all
- **Progress tracking**: `get_batch_status` reports pending, completed and failed counts
- **Flexible failure handling**: choose what happens when a job of the batch fails
- **Worker statistics**: workers can keep per-batch processing statistics
- **Batch claims**: workers can claim many jobs per round trip and keep per-batch processing statistics

A batch holds up to 10,000 jobs, all on the **same queue**.

Expand Down Expand Up @@ -258,9 +258,13 @@ for (job_id, error) in &result.job_errors {

## Worker Batch Processing

### Enable Batch Processing
### Batch Claims

Enabling batch processing on a worker makes it keep statistics for jobs that belong to a batch:
A worker in batch mode claims up to `batch_size` jobs per poll in one round trip instead
of one job per round trip, then runs them `batch_concurrency` at a time (one at a time by
default). `with_batch_size(n)` enables batch mode; `with_batch_processing_enabled(true)`
alone keeps the default batch size of 1, so it claims one job per poll as before and only
adds batch statistics:

```rust,no_run
# #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue;
Expand All @@ -276,15 +280,95 @@ let handler: JobHandler = Arc::new(|job: Job| {
})
});

// Claim up to 50 jobs per poll and run up to 8 of them at once.
let worker = Worker::new(queue, "batch_queue".to_string(), handler)
.with_batch_processing_enabled(true)
.with_batch_size(50)
.with_batch_concurrency(8)
.with_poll_interval(Duration::from_millis(100));
assert!(worker.is_batch_processing_enabled());
# Ok(())
# }
```

Every claimed job gets the same guarantees as a job claimed on its own:

- **One statement per claim.** PostgreSQL claims the batch with a single
`UPDATE ... WHERE id IN (SELECT ... ORDER BY priority DESC, scheduled_at ASC LIMIT n FOR UPDATE SKIP LOCKED) RETURNING ...`;
MySQL locks the rows with `SELECT ... FOR UPDATE SKIP LOCKED LIMIT n` and claims them
with one `UPDATE` in the same READ COMMITTED transaction (retried on deadlock).
Concurrent workers never claim the same job.
- **Same eligibility.** Paused queues, unfinished dependencies and disabled recurring jobs
are honoured, and each job's `attempts` is incremented.
- **A lease per job, from the claim.** Each job's lease is written by the claiming
statement. While a job waits for its turn in the batch, the worker renews its lease
with heartbeats every third of the lease duration, as it does for running jobs, so the
stale job reaper never reclaims a held job while its worker is alive, however long the
jobs ahead of it take. (Sizing the lease to cover the whole batch would not work: the
worker cannot know how long the jobs ahead will run.)
- **Per-job processing.** Timeouts, retries, hooks, events, spawning, result storage,
encrypted payloads and statistics work exactly as for single jobs.
- **Throttle and rate limit.** With `ThrottleConfig::max_concurrent`, every claimed job
holds a permit until it finishes, so a worker claims no more jobs than there are free
permits. With a rate limit, a batch claims no more jobs than there are tokens, and
tokens for jobs it did not get are handed back.
- **Shutdown.** Claimed jobs that have not started are released back to `Pending` at once
(`DatabaseQueue::release_job_run`, which also takes back the claim's attempt), so other
workers can run them right away. Running jobs get the shutdown grace period.

#### Priorities

Without priority weights, or with `PriorityWeights::strict()`, a batch is filled in strict
priority order: highest priority first, then oldest. With weighted priorities, a priority
level is picked by weight (as a single weighted claim picks one) and the batch is filled
with that level's oldest jobs; if the level runs out first, another level is picked by
weight among the remaining ones to fill the rest. Over many batches each level gets
batches in proportion to its weight, and no batch comes back short while other levels
have runnable jobs.

#### Choosing a batch size

Batch claims save database round trips, so they help most when jobs are short. A worker
holds the jobs it claimed until it gets to them, so idle workers cannot take them: keep
`batch_size` small relative to the queue depth when jobs are slow, or raise
`batch_concurrency` so held jobs start sooner. In a local benchmark (PostgreSQL 16 and
MySQL 8 on the same machine, no-op handler, 2,000 jobs) claiming in batches of 50 was
about 5-6x faster than claiming one job at a time, and a single batch-mode worker with
batch size 50 and concurrency 10 processed 3-4x more jobs per second than a single-job
worker. Run `HAMMERWORK_BENCH=1 cargo test --all-features --test batch_dequeue_tests -- --include-ignored --nocapture throughput`
to measure your own setup.

### Claiming Batches Directly

The queue API claims batches too, for custom consumers:

```rust,no_run
# #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue;
# #[allow(unused_variables, unused_mut, dead_code, unreachable_code)]
# async fn doc(queue: std::sync::Arc<hammerwork::JobQueue<sqlx::Postgres>>, handler: hammerwork::worker::JobHandler, jobs: Vec<hammerwork::Job>, worker: hammerwork::Worker<sqlx::Postgres>, batch_id: hammerwork::BatchId) -> std::result::Result<(), Box<dyn std::error::Error>> {
use hammerwork::{JobOutcome, queue::DatabaseQueue};
use std::time::Duration;

// Up to 20 jobs, strict priority order, each leased for 2 minutes.
let jobs = queue
.dequeue_batch_leased("emails", None, Duration::from_secs(120), 20)
.await?;
for job in jobs {
let run = job.clone();
let job = queue.decrypt_job(job).await?; // a no-op for unencrypted jobs
// ... run it, renewing its lease with `heartbeat_job` while it runs or waits ...
queue.finish_job_run(&run, JobOutcome::Completed).await?;
}
# Ok(())
# }
```

Jobs you claimed but will not run go back with `queue.release_job_run(&job)`.

### Access Batch Statistics

Workers with batch processing enabled also keep statistics for jobs that belong to a
`JobBatch`:

```rust,no_run
# #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue;
# #[allow(unused_variables, unused_mut, dead_code, unreachable_code)]
Expand Down
39 changes: 39 additions & 0 deletions docs/worker-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,45 @@ let worker = Worker::new(queue, "high_volume".to_string(), handler)
# }
```

### Batch Claims

For many short jobs, a worker can claim several jobs per database round trip. With
`with_batch_size(n)` the worker claims up to `n` jobs per poll in one statement and runs
them `with_batch_concurrency(m)` at a time (default 1, so the worker still runs one handler
at a time unless you raise it):

```rust,no_run
# #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue;
# #[allow(unused_variables, unused_mut, dead_code, unreachable_code)]
# async fn doc(queue: std::sync::Arc<hammerwork::JobQueue<sqlx::Postgres>>, handler: hammerwork::worker::JobHandler, payload: serde_json::Value, job: hammerwork::Job) -> std::result::Result<(), Box<dyn std::error::Error>> {
use hammerwork::{ThrottleConfig, Worker};
use std::time::Duration;

let worker = Worker::new(queue, "notifications".to_string(), handler)
.with_batch_size(20) // Claim up to 20 jobs per poll
.with_batch_concurrency(5) // Run up to 5 of them at once
.with_lease_duration(Duration::from_secs(60))
.with_throttle_config(ThrottleConfig::new().max_concurrent(50));
assert_eq!(worker.batch_size(), 20);
# Ok(())
# }
```

- Each claimed job holds its own lease from the moment it is claimed. Jobs waiting for
their turn have their leases renewed every third of the lease duration, like running
jobs, so a short lease is safe even for large batches of slow jobs.
- With a throttle, each claimed job holds one `max_concurrent` permit until it finishes:
a worker never claims more jobs than there are free permits. With a rate limit, a batch
claims no more jobs than there are tokens, and unused tokens are handed back.
- On shutdown, jobs that were claimed but not started go straight back to `Pending` (their
attempt is not counted); running jobs get the shutdown grace period.
- Weighted priorities pick one level by weight per batch and fill the batch from it
(topping up from other levels); strict priority fills in strict order. See
[Batch Operations](batch-operations.md#worker-batch-processing).

A worker holds the jobs it claimed until it gets to them, so other workers cannot take
them meanwhile. Prefer small batches for slow jobs, or raise the batch concurrency.

### Resource-Intensive Jobs

```rust,no_run
Expand Down
3 changes: 2 additions & 1 deletion examples/worker_batch_example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,8 @@ async fn batch_worker_demo(

// Create worker with batch processing enabled
let worker = Worker::new(queue.clone(), "batch_processing_queue".to_string(), handler)
.with_batch_processing_enabled(true) // Enable batch processing features
.with_batch_size(10) // Claim up to 10 jobs per poll (enables batch processing)
.with_batch_concurrency(4) // and run up to 4 of them at once
.with_poll_interval(Duration::from_millis(100))
.with_max_retries(3)
.with_stats_collector(stats_collector.clone())
Expand Down
Loading
Loading