Batches
Enqueue a group of jobs and run a callback when the whole batch completes.
Start a batch#
A batch tracks a group of related jobs and fires a callback when they have all finished. Pgbus.batch opens one, yields a builder, and starts the batch when the block returns:
batch = Pgbus.batch(description: "Import users", properties: { initiated_by: current_user.id }) do |b|
b.on_complete ImportFinishedJob
b.on_success ImportSucceededJob
b.on_failure ImportFailedJob
b.add(*users.map { |user| ImportUserJob.new(user.id) })
endb.add takes job instances, or arrays of them, and sends them in one bulk enqueue. Each instance keeps its own options, so ImportUserJob.new(id).set(wait: 5.minutes, queue: :low) works. b.add { ... } with a block also works, and any perform_later inside the Pgbus.batch block joins the batch as well.
The batch row exists before the block runs and stays building (in a pgbus process) or pending until the block returns, so a job that finishes while the block is still adding jobs cannot finish the batch early (a pending one only until the stalled-batch sweep starts it). Callbacks can be set at any point in the block, but set them first: if the block raises after an add, the jobs already added still run, and the batch finishes later (through the dispatcher sweep) with only the callbacks set by then. A pending block that goes config.batch_stall_threshold (default 5 minutes) without adding a job is treated as stalled and started by that sweep, so keep slow work outside the block. A batch opened in a pgbus process, once pgbus:add_batch_executions and pgbus:add_batch_owner have run (pgbus:update adds both), is building instead, which the sweep leaves alone while that process heartbeats. Membership follows the block's own thread or fiber: b.add raises anywhere else, and a plain perform_later from a thread or fiber the block spawns does not join the batch, so the batch can finish before that job runs. Enqueue from the block itself.
A batch can be opened inside a database transaction, for example to store batch.batch_id on the rows the transaction writes. Jobs with enqueue_after_transaction_commit are sent once the transaction commits, and they still join the batch: b.add, batch.add and perform_later record the batch on the job instance, each job counts itself in at commit, and only then does the batch start processing. If the transaction rolls back, no job is sent, no callback fires and, when pgbus shares the application's database, the batch row is rolled back with everything else. With a separate pgbus database (config.connects_to) the batch row is written on its own connection and commits on its own: a rollback leaves a pending batch with no jobs, which the stalled-batch sweep later starts and finishes empty, firing its callbacks. Inside a transaction, add jobs that defer: a job without enqueue_after_transaction_commit is sent at once, and unless pgbus sends on the caller's own connection a worker can run it before the transaction commits the batch, so the batch waits for the stalled-execution sweep to account for it. Enqueue a job instance once: an instance is one member (one job_id, one execution row). A second enqueue of it is unsupported: deferred, it runs outside the batch; sent at once inside the block, it is counted again against the one row and the batch can be left waiting. A bare ActiveJob.perform_all_later inside the block does not record the batch on its jobs, so use b.add there. A batch.add inside a transaction raises Pgbus::Batch::AlreadyFinished when the transaction commits if the batch finished in the meantime. A member job that adds siblings from its own perform is safe, because its own run keeps the batch open.
Pgbus.batch returns the Pgbus::Batch handle. Usually it is started; when on_conflict: :discard or :log finds the uniqueness_key held, the block never runs and the handle answers discarded?. Its keywords are the ones Pgbus::Batch.new takes (description:, properties:, uniqueness_key:, on_conflict:, and the callbacks). Pgbus::Batch.start is the same method.
A callback is an ActiveJob class or a configured instance, never a block: it is stored on the batch row and enqueued by whichever process finishes the batch. The builder only works inside its block. To add jobs later, call batch.add on the batch Pgbus.batch returned.
Start a batch from a job#
Inside a job, batch with a block is Pgbus.batch. It opens a new batch, independent of any batch the running job belongs to:
class ImportJob < ApplicationJob
def perform(source_id)
source = Source.find(source_id)
batch(description: "Import #{source_id}") do |b|
b.on_complete ImportFinishedJob
b.add(*source.rows.map { |row| ImportRowJob.new(row.id) })
end
end
endWithout a block, batch reads the batch the job belongs to, or the batch a callback job reports on.
Open batches#
A batch stays open until it finishes. A job running inside it reaches its own batch through batch and can add siblings with batch.add. total_jobs grows and the callbacks wait for the new jobs too:
class ExtractJob < ApplicationJob
def perform
batch.add(*extract.map { |row| TransformJob.new(row.id) })
end
endMembership stays explicit: only jobs passed to add, or enqueued inside a batch block, join the batch. A job that merely runs as part of a batch can enqueue unrelated work without extending it.
Pgbus::Batch.find(batch_id) returns the same handle from anywhere — with description, properties, status, total_jobs, completed_jobs, failed_jobs, pending_jobs, progress_percentage and finished?. Adding to a batch that has already finished raises Pgbus::Batch::AlreadyFinished — at perform_later, before the job is sent, even if the handle you hold is stale.
Pgbus::Batch.find used to return the raw attributes Hash. Read the values off the handle, or query Pgbus::BatchEntry directly for a row.Callbacks#
| Callback | Fired when |
|---|---|
on_complete | The batch finished (no outstanding execution rows remain), including after a dispatcher sweep repair. (`on_finish` is a deprecated alias, removed in 2.0.) |
on_success | The batch finished with zero failed jobs. |
on_failure | The batch finished with at least one dead-lettered job. |
Each name works as a builder method (b.on_complete MyJob) and as a Pgbus::Batch.new keyword (on_complete: MyJob). on_finish still works in both places and logs a deprecation warning once per process. The batch row keeps its on_finish_class and on_finish_job columns until 2.0, so batches created before the rename still fire.
A callback job receives the batch properties hash as its argument:
class BatchFinishedJob < ApplicationJob
def perform(properties)
user = User.find(properties["initiated_by"])
ImportMailer.complete(user).deliver_later
end
endConfigured callback jobs#
A callback can be a configured ActiveJob instance instead of a bare class, so it runs on the queue — and with the delay — you choose:
Pgbus.batch do |b|
b.on_complete BatchFinishedJob.new.set(queue: :critical, wait: 5.minutes)
b.add(*jobs)
end.set options resolve when the batch is created, and the serialized job is stored on the batch row. At fire time it is enqueued on its configured queue with callback_batch_id pointing at the finished batch, so the callback reads the batch through batch rather than through a properties argument:
class BatchFinishedJob < ApplicationJob
def perform(*)
Rails.logger.info "#{batch.completed_jobs}/#{batch.total_jobs} done"
User.find(batch.properties["initiated_by"])
end
endA callback is never a member of the batch it reports on — its own batch_id is nil, so enqueueing it can never keep the batch open.
rails generate pgbus:add_batch_callback_jobs (or pgbus:update) for the jsonb callback columns. Bare callback classes keep the perform_later(properties) signature, deprecated at 1.0.Pgbus::Batch.new and enqueue#
Pgbus.batch is built on Pgbus::Batch.new plus #enqueue, which stay available. Callbacks are keywords, and every job enqueued inside the enqueue block joins the batch:
batch = Pgbus::Batch.new(on_complete: ImportFinishedJob, description: "Import users")
batch.enqueue do
users.each { |user| ImportUserJob.perform_later(user.id) }
endA second enqueue (or add) on the same handle adds to the batch while it is unfinished.
How batches work#
- The top of the
Pgbus.batchblock (or the firstenqueue) takes the uniqueness key, if there is one, and creates a row inpgbus_batcheswithstatus: "pending".Batch.newalone writes nothing. - Each job enqueued in the block is tagged with the batch id and, in one transaction before the message is sent, increments
total_jobsand inserts itspgbus_batch_executionsrow (identity is the ActiveJobjob_id). The increment is guarded on an unfinished batch — that guard is what raisesAlreadyFinished. Aperform_all_latercounts once per batch and send group: one increment and one multi-row insert per batch per queue, priority and delay (rounded up to whole seconds), onesend_batchand one backfill per group. A batch opened in a pgbus process (one with apgbus_processesheartbeat) is createdbuildingwith that process as its owner, and its block's bulk-eligibleperform_latercalls are held and counted the same way everyconfig.coalesce_chunk_sizejobs; uniqueness, concurrency, retry and opted-out calls (pgbus_coalesce false, or nopgbus_coalesce trueunderconfig.coalesce_default = false) are sent at once. Whilebuildingthe sweep ignores it and it cannot finish; the block's end counts the last chunk and moves it topendingin one transaction. If the owner stops heartbeating, the sweep reaps the build:processing, with the abandoned build counted as one failed job. A held member that cannot be sent counts as a failed job and goes toPgbus.batch(on_enqueue_failure:)(:raiseby default). - As each job is archived or dead-lettered, the executor deletes that execution row and bumps
completed_jobs/failed_jobs.total_jobs == outstanding rows + completed + failedholds at every commit point. A job that re-enqueues itself withretry_onkeeps its single row across every attempt — the batch waits for the terminal outcome, soon_successcannot fire while a retry is pending andon_failurefires if the retries exhaust. - The batch finishes when no execution rows remain and the counters add up (single-winner update). A dispatcher sweep repairs crash windows — a worker that dies between archive and row-delete, an enqueue that dies between insert and send, a
pendingbatch whose block never returned. An unsent row is only un-counted once the sweep has checked the queue and DLQ for its message; a batch is only "stalled" afterconfig.batch_stall_threshold(default 5 minutes) without a new execution row. - The dispatcher cleans up finished batches older than
config.batch_retention(default 7 days).
rails generate pgbus:add_batch_executions (or pgbus:update). Fresh pgbus:install already includes the executions table.