Reference

Configuration reference

Every Pgbus.configure option, grouped by concern.

Reading this page#

Set any of these in a Pgbus.configure block. Durations accept an integer number of seconds or an ActiveSupport::Duration. Every option has a default, so you only set what you need. For the knobs most apps touch first, start with Configuration.

Connection#

OptionTypeDefaultDescription
database_urlString, nilnilPostgreSQL URL (auto-detected in Rails).
connection_paramsHash, nilnilExtra connection parameters merged into the pool.
pool_sizeInteger, nilnil (auto)Connection pool size; auto-tuned from thread counts when nil.
pool_timeoutNumeric5Seconds to wait for a pooled connection.
connects_toHash, nilnilRails multi-database config for a dedicated pgbus database.
require_primaryBooleanfalseReject a job connection that lands on a read-only replica (pg_is_in_recovery) at boot — pooler safety against a read/write splitter routing pgmq reads to a standby.
connection_guc_modeSymbol:optionsHow database.yml GUCs (variables:) reach pgbus's connections — :options (libpq startup param) or :session (post-connect SET, for a transaction-mode PgBouncer that rejects the options param). Applies to the pgmq pools and the dedicated LISTEN connections (streamer, worker notify).
native_statementsBooleantrueRun read_batch, archive, delete, send and their batch forms as pgbus's own SQL in named prepared statements instead of pgmq's plpgsql functions, which Postgres plans again on every call. A queue whose table lacks a column it needs stays on the functions. Behind a transaction-mode PgBouncer it needs PgBouncer 1.21+ with max_prepared_statements; without it a process that sees its statements vanish sends the same SQL unprepared and logs a warning once. Connections from a database.yml with prepared_statements: false send it unprepared from the start and log one info line. false: the pgmq functions everywhere.

Queues#

OptionTypeDefaultDescription
queue_prefixString"pgbus"Prefix for every PGMQ queue name.
default_queueString"default"Queue for jobs without an explicit queue.
priority_levelsInteger, nilnilNumber of priority sub-queues (2–10); nil disables.
default_priorityInteger1Priority for jobs without an explicit one.
group_modeSymbol, nilnilGrouped-read ordering mode for a queue. Experimental — exempt from the 1.0 stability promise.
fair_share#call, nilnilCallable receiving the ActiveJob at enqueue; returns a key, [key, weight], or nil. Workers then interleave reads across keys (weighted, work-conserving). Mutually exclusive with group_mode.
event_fair_share#call, nilnilEvent-bus twin of fair_share: callable receiving the Pgbus::Event at publish (routing_key, payload, headers); returns a key, [key, weight], or nil. The key rides in the event envelope and consumers interleave reads across keys within each subscriber queue. Independent of fair_share.
current_attributesSymbol, Array, Hash, nilnilPersist ActiveSupport::CurrentAttributes across enqueue → perform: :auto (every subclass), an Array of classes/names, or a Hash of class => { only: }/{ except: }. Restored around the whole perform_now, and around event handlers (captured at publish into the event envelope).
coalesce_chunk_sizeInteger1000Held jobs after which a Pgbus.coalesce scope, or the one Pgbus.batch opens for its block, sends what it holds before the block ends. A full chunk goes on the next enqueue or at the block's end. Bounds memory for chunks that are sent; jobs that fail stay held until on_failure runs once, at the end. A built batch keeps holding while a transaction is open on the batch's connection, and sends once it closes or the block ends.
coalesce_defaultBooleantrueWhether a Pgbus.coalesce scope holds a job class that declares nothing. true: every bulk-eligible job is held, in a batch's own scope too, unless its class declares pgbus_coalesce false. false: only classes that declare pgbus_coalesce true are held, in a batch's own scope too; every other job is sent at its perform_later. A class that defines pgbus_coalesce? itself (the hook before this setting) answers for itself either way.

Workers#

OptionTypeDefaultDescription
workersString / Arraydefault: 5Worker capsule definitions (string DSL or array). A capsule's processes: N forks N identical workers for CPU-bound queues.
event_consumersString / Array, nilnilEvent-consumer process definitions.
rolesArray, nilnil (all)Supervisor role filter — usually set via CLI flags.
execution_modeSymbol:threadsGlobal execution mode (:threads or :async).
polling_intervalNumeric0.1Seconds between polls (LISTEN/NOTIFY is primary).
prefetch_limitInteger, nilnilMax in-flight messages per worker.
read_aheadInteger0Messages a worker or event consumer claims beyond its free threads and holds (heartbeated) until a thread frees, so one read feeds many jobs when Postgres is on another host. 0 is off. Overridable per capsule and per event_consumers entry (read_ahead:); prefetch_limit still caps the total.
completion_batchingBooleanfalseArchive the jobs a worker finishes close together with one archive_batch per flush instead of one pgmq.archive per job (no timer: a lone job is archived at once). Threads only; rejected with execution_mode :async. On a hard crash the jobs waiting in the current flush re-run after visibility_timeout.
completion_batch_sizeInteger100Most message ids one completion archive_batch statement carries.
completed_jobsSymbol, String:archiveHow a successful job's message leaves its queue. :archive moves it to the queue's a_ table (pgmq.archive: DELETE + INSERT), which archive_retention compacts. :delete removes it (pgmq.delete, the DELETE alone; delete_batch with completion_batching): newly completed ActiveJob messages create no a_ rows or archive index entries and leave no completed-job history in the archive; rows archived before the switch stay until archive_retention compacts them. Without an archive, Batch::Sweep cannot tell a deleted batch job from one whose message vanished another way (a purged queue) and counts both as completed. ActiveJob only: EventBus handler queues keep archiving (event replay reads their archive); failures and dead letters are unchanged.
completion_synchronous_commitBooleantruefalse commits a job's completion (archive, delete, archive_batch, delete_batch from the executor and the completer) with SET LOCAL synchronous_commit TO off, in one libpq pipeline (BEGIN, SET LOCAL, the prepared statement, COMMIT, one sync), so the job stops waiting for its WAL flush. A Postgres server crash (not a client crash, not a planned switchover), or a failover to a standby that has not yet received that WAL (synchronous replication stops waiting for the standby too), within about three times wal_writer_delay can lose completions committed in that window; each lost one redelivers its job after visibility_timeout, which runs again. Sends, retries, dead-letter moves, the EventBus consumer's archive and dashboard actions keep full durability, and a completion inside a caller's transaction is left to it. Native statements on pgbus's own connections only (no effect with native_statements = false or on ActiveRecord's shared connection, a connection_params Proc; pgbus doctor warns). Needs libpq 14+ and pg 1.5+. Untested behind PgBouncer in transaction mode.
quiet_active_job_logsBooleanfalseWorker processes unsubscribe ActiveJob's log subscriber from perform_start.active_job and perform.active_job, so the per-job "Performing …" / "Performed …" info lines stop. The same perform listener writes ActiveJob's "Error performing …" line, which goes too: an exception that escapes ActiveJob's handlers is still logged by pgbus's ErrorReporter (class and message) and kept in pgbus_failed_events with its backtrace; one retry_on catches still logs ActiveJob's "Retrying …" line (and "Stopped retrying …" when it gives up); a job a before_perform callback halted logs nothing. Enqueued, Retrying, Stopped retrying and Discarded still log, and the web process is untouched. Does nothing without ActiveJob.
visibility_timeoutDuration30How long a read message stays invisible before retry.
visibility_heartbeatBooleantrueRe-arm a running job's visibility timeout on a heartbeat so a job that outlives it is not redelivered (and eventually dead-lettered) mid-run; the timeout then only fires for a process that is gone. false restores plain PGMQ semantics.
visibility_heartbeat_intervalDuration, nilnil (visibility_timeout / 3)Seconds between heartbeat re-arms of a running job's message.

Worker recycling#

OptionTypeDefaultDescription
max_jobs_per_workerInteger, nilnilRecycle a worker after N jobs.
max_memory_mbInteger, nilnilRecycle a worker above N MB RSS. Overridable per capsule (max_memory_mb:), as are max_jobs_per_worker and max_worker_lifetime.
max_worker_lifetimeDuration, nilnilRecycle a worker after N seconds.

Retries & reliability#

OptionTypeDefaultDescription
max_retriesInteger5Failed reads before routing to the dead-letter queue.
retry_backoffNumeric5Base delay (seconds) for exponential retry backoff.
retry_backoff_maxNumeric300Cap on the retry delay.
retry_backoff_jitterFloat0.15Jitter factor (0–1) added to retry delays.
circuit_breaker_enabledBooleantrueAuto-pause a queue after consecutive failures.
listen_notifyBooleantrueUse PGMQ LISTEN/NOTIFY for instant wake-up.
worker_notify_scopeSymbol:supervisorWhere the LISTEN connection lives: :supervisor shares ONE direct connection per host (forks woken over pipes); :fork keeps one dedicated connection per worker/consumer fork.
streams_listen_scopeSymbol:masterWhere the streams LISTEN connection lives: :master shares ONE connection per web host (Puma workers connect to a master hub, with automatic per-worker fallback); :process keeps one per web process.
zombie_detectionBooleantrueDetect and reclaim work from crashed workers.

Dispatcher & maintenance#

OptionTypeDefaultDescription
dispatch_intervalNumeric1.0Seconds between dispatcher maintenance ticks.
archive_retentionDuration, nil7.daysHow long to keep archived messages; nil disables cleanup.
batch_retentionDuration, nil7.daysHow long to keep finished batches; nil disables cleanup.
batch_sweep_intervalDuration5.minutesHow often the dispatcher repairs stalled batches (execution-row sweep).
batch_stall_thresholdDuration5.minutesHow long a pending batch may go without a new execution row, or an unsent row without a message, before the sweep repairs it.
idempotency_ttlDuration, nil7.daysHow long processed-event records are kept for dedup.

Workflows#

OptionTypeDefaultDescription
workflow_queueString"default"Queue the Pgbus::Workflow::StepJob messages go to; a class (set_step_job_options) or a step (job_options:) can override it.
workflow_retentionDuration, nil30.daysHow long to keep finished and cancelled workflows (with their steps and events); nil disables cleanup.
workflow_sweep_intervalDuration5.minutesHow often the dispatcher repairs stuck workflow steps and emits the workflow gauges.
workflow_stall_thresholdDuration1.hourDefault deadline for an in_progress step (a step's own timeout: overrides it), and how long a scheduled step may be overdue and unsent before the sweep sends it again.
workflow_stall_actionSymbol:pauseWhat happens to a stalled step: :pause the workflow, :reattempt the step, or :cancel the workflow.
workflow_max_payload_sizeInteger131_072Byte cap on a workflow's serialized arguments and on each step's output; larger raises Pgbus::Workflow::PayloadTooLarge.
workflow_error_backtrace_linesInteger50Backtrace lines kept on a failed step row (cleaned through Rails.backtrace_cleaner when Rails is loaded).
workflow_subject_urlCallable, nilnil->(subject_type, subject_id) { URL or nil }: where the Workflows dashboard links a run's subject. Only an http(s) URL or a path starting with a single / is linked; anything else, or a lambda that raises, shows as text.
workflow_waiting_visibility_thresholdDuration7.daysA step waiting this long for a signal or its batch, without a deadline (no wait_timeout:, or a per-run one that set none or cleared it after a :notify notice), counts as stuck (the waiting_overdue reason in the pgbus_workflows_stuck gauge).

Outbox#

OptionTypeDefaultDescription
outbox_enabledBooleanfalseEnable the transactional outbox poller.
outbox_poll_intervalNumeric1.0Seconds between outbox poll cycles.
outbox_batch_sizeInteger100Max entries claimed per outbox cycle.
outbox_retentionDuration, nil1.dayHow long to keep published outbox entries.

Recurring tasks#

OptionTypeDefaultDescription
recurring_tasksHash, nilnilRecurring task definitions as a hash.
recurring_tasks_filesArray, nilnilPaths to recurring.yml files. Replaces the deprecated singular recurring_tasks_file.
recurring_schedule_intervalNumeric1.0Seconds between scheduler ticks.
recurring_execution_retentionDuration, nil7.daysHow long to keep recurring execution history.
recurring_enabledBooleantrueRun the recurring scheduler (set false to disable it entirely). Replaces the deprecated skip_recurring.

Deploy tasks#

OptionTypeDefaultDescription
app_revisionString, Callable, nilnilThe app revision every pgbus process reports in its heartbeat. Falls back to PGBUS_REVISION, DASH_VERSION, KAMAL_VERSION, then the REVISION file at Rails.root.
deploy_tasksHash, nilnilDeploy task definitions as a hash (loaded from config/deploy_tasks.yml when nil).
deploy_tasks_filesArray, nilnilPaths to deploy_tasks.yml files, merged in order.
deploy_tasks_enabledBooleantrueRun deploy tasks from the scheduler once the fleet has rolled over to a new revision.
deploy_task_run_retentionDuration, nil90.daysHow long to keep deploy task run history (nil keeps it forever).

Job stats#

OptionTypeDefaultDescription
stats_enabledBooleantrueRecord job execution stats for insights.
stats_retentionDuration, nil30.daysHow long to keep job stats.
stats_flush_sizeInteger100Buffered stats per worker before a bulk insert.
stats_flush_intervalNumeric5Seconds between periodic stat flushes.

Dashboard#

OptionTypeDefaultDescription
web_authCallable, nilnilLambda authorizing dashboard access.
web_actorCallable, nilnil->(request) { name or nil }: who a dashboard action on a workflow is recorded as on its audit trail ("dashboard:<name>"; nil records "dashboard").
base_controller_classString"::ActionController::Base"Base class for dashboard controllers.
return_to_app_urlString, nilnilURL for the "back to app" button.
web_refresh_intervalInteger5000Dashboard auto-refresh interval (ms).
web_live_updatesBooleantrueEnable Turbo Frames auto-refresh.
web_per_pageInteger25Dashboard pagination size.
web_queue_metrics_chunk_sizeInteger100Queues per statement when the dashboard, the MCP server and the metrics probes read every queue's metrics. Each chunk runs in its own savepoint: a chunk that fails or hits statement_timeout marks only its queues metrics_unavailable. After three chunks that time out (a cancelled statement, a lock wait, a deadlock), the remaining queues are marked unavailable without being read.
web_filter_sensitiveBooleantrueRedact sensitive values in dashboard payload views. Replaces the deprecated dashboard_filter_sensitive.
web_filter_parametersArray, nilnil (auto)Parameter-name patterns to redact; nil auto-detects from Rails. Replaces the deprecated dashboard_filter_parameters.
metrics_enabledBooleantrueExpose Prometheus gauges on the dashboard.

MCP server#

OptionTypeDefaultDescription
mcp_write_toolsBooleanfalseBuild the MCP server's workflow write tools (pgbus_workflow_resume, _cancel, _skip_step, _resume_at, _run_now, _signal); off, they do not exist. Each call needs a reason and lands on the run's audit trail as actor "mcp" ("mcp:<client name>" when the transport knows the client). Enable only on an authenticated endpoint.

Metrics & logging#

OptionTypeDefaultDescription
metrics_backendSymbol, Object, nilnilMetrics adapter: nil, :prometheus, :statsd, or a Backend.
statsd_hostString"127.0.0.1"StatsD UDP host.
statsd_portInteger8125StatsD UDP port.
log_formatSymbol:textLog formatter (:text or :json).
error_reportersArray[]Callables invoked on caught exceptions.
appsignal_enabledBooleantrueEnable the AppSignal subscriber + probe (when the gem is present).
appsignal_probe_enabledBooleantrueEnable the minutely AppSignal gauge probe.

Health & liveness#

OptionTypeDefaultDescription
health_portInteger, nilnilPort for HTTP liveness/readiness probes; nil disables.
health_bindString"127.0.0.1"Bind address for the health server.
health_unclaimed_graceNumeric60Seconds a visible, never-read message must have been claimable before the health verdict (/readyz, pgbus_health) reports it as never claimed while workers are alive (STALLED). 0 counts any such message.
stall_thresholdNumeric, nil90Seconds a checked-in worker or consumer loop may go without progress before the supervisor kills it. nil disables.
boot_timeoutNumeric, nil120Seconds a forked child may take to check in (a process row, or a liveness byte) before the supervisor asks it for a thread dump (TTIN), SIGKILLs it and forks it again. nil disables.
read_timeoutNumeric30Read timeout for worker fetches.
drain_timeoutNumeric30Seconds to wait for in-flight jobs to finish during graceful shutdown before abandoning them.
immediate_shutdown_graceNumeric2On QUIT, seconds a worker or consumer gives running jobs to finish before it kills them; killed jobs' ActiveRecord connections are reclaimed.
shutdown_timeoutNumeric, nildrain_timeout + 5Seconds the supervisor waits for children after TERM before SIGKILL. nil derives drain_timeout + 5; an orchestrator's stop grace period (Kamal stop_timeout, K8s terminationGracePeriodSeconds) must exceed it.

Streams (SSE)#

OptionTypeDefaultDescription
streams_enabledBooleantrueEnable the SSE streams transport.
streams_default_retentionNumeric300Default stream retention in seconds.
streams_retentionHash{}Per-stream retention overrides.
streams_heartbeat_intervalNumeric15SSE heartbeat interval (seconds).
streams_peer_close_intervalNumeric, nil1.0How long a new SSE connection waits to join the peer-close watch (seconds). A client that closes a watched socket is disconnected at once, so its presence seat leaves without waiting for a heartbeat. nil turns the watcher off.
streams_max_connectionsInteger2000Max SSE connections per web-server process.
streams_idle_timeoutNumeric3600Close idle SSE connections after N seconds.
streams_pool_sizeInteger5Dedicated DB pool for durable-stream publish + replay, isolated from the job pool so a saturated worker pool can't delay broadcasts. Ignored on the shared-ActiveRecord connection path.
streams_pool_timeoutNumeric5Seconds to wait for a connection from the dedicated streams pool.
streams_pool_autoscaleBooleanfalseSelf-tuning: a periodic maintenance check (on the streamer's idle LISTEN connection — no extra connection) grows the streams pool into a fair share of live Postgres connection headroom under saturation, shrinks back to streams_pool_size when idle, and emergency-shrinks if the DB runs low on connections. Opt-in; no-op on the shared-ActiveRecord path.
streams_pool_maxInteger, nilnilOptional hard ceiling for streams-pool autoscaling. nil lets the dynamic per-process fair share of DB headroom be the effective cap.
streams_pathString, nilnilCustom SSE endpoint path (auto-detected from mount).
streams_falcon_streaming_bodyBooleanfalseUse Falcon-native streaming body instead of hijack. Experimental — exempt from the 1.0 stability promise.
streams_stats_enabledBooleanfalseRecord stream broadcast/connect/disconnect stats.
streams_test_modeBooleanfalseReturn a stub SSE response (auto-enabled by the test helpers).
streams_coalesce_schedulerObject, nilnilWhat runs a `coalesce:` broadcast's flush: any object with `schedule(delay_seconds) { ... }`. nil is the coalescer's timer (a background thread). Read when a window's flush is scheduled. When it is nil, `Pgbus::Testing.fake!`/`.inline!` select `Pgbus::Streams::Coalescer::InlineScheduler`, which flushes on the submitting thread, and `disabled!` restores nil; a scheduler you set yourself is left alone. A value without `#schedule` fails `validate!`.
streams_authorizeCallable, nilnilAuthorize hook for the stream endpoint (the engine mount, and any `StreamApp` built without its own `authorize:`): `->(env, stream_name) { user = current_user_from(env); user if user && may_read?(user, stream_name) }`, the same contract as `StreamApp.new(authorize:)`. A falsy return answers 403, `true` authorizes with no context, any other value (e.g. the current user) becomes the connection context that `visible_to:` filters and connection-driven presence read. nil authorizes every connection with no context. An app-mounted `StreamApp.new(authorize:)` keeps its own hook. Authorize per stream: a signed name proves pgbus minted it, not that this user may read it. A non-callable value fails `validate!`; with `eager_validation = false` every stream request fails closed with a 500 instead.
streams_presence_patternsArray[]Streams (exact string or Regexp) that get connection-driven presence: auto-join on connect, auto-leave on disconnect, heartbeat touch. Experimental — exempt from the 1.0 stability promise.
streams_presence_memberCallable, nilnilCustom `->(context) { { id:, metadata: } }` extractor for connection-driven presence; nil uses the built-in Hash/#id extractor. Experimental — exempt from the 1.0 stability promise.
streams_presence_ttlNumeric, Hash60Seconds a presence seat may stay silent before the streamer heartbeat expires it: one number, or a Hash of pattern (String/Regexp) => seconds with an optional `:default`. Seat tables only. Experimental.
streams_presence_on_changeCallable, nilnil`->(stream_name, change) { }` called after each seat join, leave and expiry with `{ type: :join | :leave, connection_id:, seat:, member_id: }`; errors are logged and swallowed. Experimental.
streams_broadcast_queueString, nilnilDedicated queue for turbo-rails' async broadcast jobs. nil leaves them on the default queue (a broadcasts_to render+broadcast can wait behind long-running jobs). Set a queue name and back it with a worker capsule to isolate broadcast latency.

Validation#

OptionTypeDefaultDescription
eager_validationBooleantrueValidate configuration eagerly at boot.
allowed_global_id_modelsArray, nilnilAllowlist of Class/Module models permitted as GlobalID job arguments and EventBus payloads. nil = allow-all (default). [] = deny-all. Apps using ActiveStorage attachments should include ActiveStorage::Blob (and related models) so Rails' analyze/purge/transform jobs still deserialize.
pgmq_schema_modeSymbol:autoPGMQ schema install mode (:auto, :extension, :embedded).
doctor_on_bootSymbol, nilnilRun doctor preflight checks inside the booting supervisor (one Rails boot instead of `pgbus doctor` + `pgbus start`). nil/false = off. :report logs the report and always boots; :strict refuses to boot on a fatal check (bad config or an absent PGMQ schema) — transient-shaped failures (Queues/Database) never abort. Set via the --doctor / --doctor-strict start flags too.