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#
| Option | Type | Default | Description |
|---|---|---|---|
database_url | String, nil | nil | PostgreSQL URL (auto-detected in Rails). |
connection_params | Hash, nil | nil | Extra connection parameters merged into the pool. |
pool_size | Integer, nil | nil (auto) | Connection pool size; auto-tuned from thread counts when nil. |
pool_timeout | Numeric | 5 | Seconds to wait for a pooled connection. |
connects_to | Hash, nil | nil | Rails multi-database config for a dedicated pgbus database. |
require_primary | Boolean | false | Reject 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_mode | Symbol | :options | How 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_statements | Boolean | true | Run 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#
| Option | Type | Default | Description |
|---|---|---|---|
queue_prefix | String | "pgbus" | Prefix for every PGMQ queue name. |
default_queue | String | "default" | Queue for jobs without an explicit queue. |
priority_levels | Integer, nil | nil | Number of priority sub-queues (2–10); nil disables. |
default_priority | Integer | 1 | Priority for jobs without an explicit one. |
group_mode | Symbol, nil | nil | Grouped-read ordering mode for a queue. Experimental — exempt from the 1.0 stability promise. |
fair_share | #call, nil | nil | Callable 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, nil | nil | Event-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_attributes | Symbol, Array, Hash, nil | nil | Persist 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_size | Integer | 1000 | Held 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_default | Boolean | true | Whether 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#
| Option | Type | Default | Description |
|---|---|---|---|
workers | String / Array | default: 5 | Worker capsule definitions (string DSL or array). A capsule's processes: N forks N identical workers for CPU-bound queues. |
event_consumers | String / Array, nil | nil | Event-consumer process definitions. |
roles | Array, nil | nil (all) | Supervisor role filter — usually set via CLI flags. |
execution_mode | Symbol | :threads | Global execution mode (:threads or :async). |
polling_interval | Numeric | 0.1 | Seconds between polls (LISTEN/NOTIFY is primary). |
prefetch_limit | Integer, nil | nil | Max in-flight messages per worker. |
read_ahead | Integer | 0 | Messages 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_batching | Boolean | false | Archive 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_size | Integer | 100 | Most message ids one completion archive_batch statement carries. |
completed_jobs | Symbol, String | :archive | How 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_commit | Boolean | true | false 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_logs | Boolean | false | Worker 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_timeout | Duration | 30 | How long a read message stays invisible before retry. |
visibility_heartbeat | Boolean | true | Re-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_interval | Duration, nil | nil (visibility_timeout / 3) | Seconds between heartbeat re-arms of a running job's message. |
Worker recycling#
| Option | Type | Default | Description |
|---|---|---|---|
max_jobs_per_worker | Integer, nil | nil | Recycle a worker after N jobs. |
max_memory_mb | Integer, nil | nil | Recycle a worker above N MB RSS. Overridable per capsule (max_memory_mb:), as are max_jobs_per_worker and max_worker_lifetime. |
max_worker_lifetime | Duration, nil | nil | Recycle a worker after N seconds. |
Retries & reliability#
| Option | Type | Default | Description |
|---|---|---|---|
max_retries | Integer | 5 | Failed reads before routing to the dead-letter queue. |
retry_backoff | Numeric | 5 | Base delay (seconds) for exponential retry backoff. |
retry_backoff_max | Numeric | 300 | Cap on the retry delay. |
retry_backoff_jitter | Float | 0.15 | Jitter factor (0–1) added to retry delays. |
circuit_breaker_enabled | Boolean | true | Auto-pause a queue after consecutive failures. |
listen_notify | Boolean | true | Use PGMQ LISTEN/NOTIFY for instant wake-up. |
worker_notify_scope | Symbol | :supervisor | Where 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_scope | Symbol | :master | Where 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_detection | Boolean | true | Detect and reclaim work from crashed workers. |
Dispatcher & maintenance#
| Option | Type | Default | Description |
|---|---|---|---|
dispatch_interval | Numeric | 1.0 | Seconds between dispatcher maintenance ticks. |
archive_retention | Duration, nil | 7.days | How long to keep archived messages; nil disables cleanup. |
batch_retention | Duration, nil | 7.days | How long to keep finished batches; nil disables cleanup. |
batch_sweep_interval | Duration | 5.minutes | How often the dispatcher repairs stalled batches (execution-row sweep). |
batch_stall_threshold | Duration | 5.minutes | How long a pending batch may go without a new execution row, or an unsent row without a message, before the sweep repairs it. |
idempotency_ttl | Duration, nil | 7.days | How long processed-event records are kept for dedup. |
Workflows#
| Option | Type | Default | Description |
|---|---|---|---|
workflow_queue | String | "default" | Queue the Pgbus::Workflow::StepJob messages go to; a class (set_step_job_options) or a step (job_options:) can override it. |
workflow_retention | Duration, nil | 30.days | How long to keep finished and cancelled workflows (with their steps and events); nil disables cleanup. |
workflow_sweep_interval | Duration | 5.minutes | How often the dispatcher repairs stuck workflow steps and emits the workflow gauges. |
workflow_stall_threshold | Duration | 1.hour | Default 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_action | Symbol | :pause | What happens to a stalled step: :pause the workflow, :reattempt the step, or :cancel the workflow. |
workflow_max_payload_size | Integer | 131_072 | Byte cap on a workflow's serialized arguments and on each step's output; larger raises Pgbus::Workflow::PayloadTooLarge. |
workflow_error_backtrace_lines | Integer | 50 | Backtrace lines kept on a failed step row (cleaned through Rails.backtrace_cleaner when Rails is loaded). |
workflow_subject_url | Callable, nil | nil | ->(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_threshold | Duration | 7.days | A 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#
| Option | Type | Default | Description |
|---|---|---|---|
outbox_enabled | Boolean | false | Enable the transactional outbox poller. |
outbox_poll_interval | Numeric | 1.0 | Seconds between outbox poll cycles. |
outbox_batch_size | Integer | 100 | Max entries claimed per outbox cycle. |
outbox_retention | Duration, nil | 1.day | How long to keep published outbox entries. |
Recurring tasks#
| Option | Type | Default | Description |
|---|---|---|---|
recurring_tasks | Hash, nil | nil | Recurring task definitions as a hash. |
recurring_tasks_files | Array, nil | nil | Paths to recurring.yml files. Replaces the deprecated singular recurring_tasks_file. |
recurring_schedule_interval | Numeric | 1.0 | Seconds between scheduler ticks. |
recurring_execution_retention | Duration, nil | 7.days | How long to keep recurring execution history. |
recurring_enabled | Boolean | true | Run the recurring scheduler (set false to disable it entirely). Replaces the deprecated skip_recurring. |
Deploy tasks#
| Option | Type | Default | Description |
|---|---|---|---|
app_revision | String, Callable, nil | nil | The 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_tasks | Hash, nil | nil | Deploy task definitions as a hash (loaded from config/deploy_tasks.yml when nil). |
deploy_tasks_files | Array, nil | nil | Paths to deploy_tasks.yml files, merged in order. |
deploy_tasks_enabled | Boolean | true | Run deploy tasks from the scheduler once the fleet has rolled over to a new revision. |
deploy_task_run_retention | Duration, nil | 90.days | How long to keep deploy task run history (nil keeps it forever). |
Job stats#
| Option | Type | Default | Description |
|---|---|---|---|
stats_enabled | Boolean | true | Record job execution stats for insights. |
stats_retention | Duration, nil | 30.days | How long to keep job stats. |
stats_flush_size | Integer | 100 | Buffered stats per worker before a bulk insert. |
stats_flush_interval | Numeric | 5 | Seconds between periodic stat flushes. |
Dashboard#
| Option | Type | Default | Description |
|---|---|---|---|
web_auth | Callable, nil | nil | Lambda authorizing dashboard access. |
web_actor | Callable, nil | nil | ->(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_class | String | "::ActionController::Base" | Base class for dashboard controllers. |
return_to_app_url | String, nil | nil | URL for the "back to app" button. |
web_refresh_interval | Integer | 5000 | Dashboard auto-refresh interval (ms). |
web_live_updates | Boolean | true | Enable Turbo Frames auto-refresh. |
web_per_page | Integer | 25 | Dashboard pagination size. |
web_queue_metrics_chunk_size | Integer | 100 | Queues 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_sensitive | Boolean | true | Redact sensitive values in dashboard payload views. Replaces the deprecated dashboard_filter_sensitive. |
web_filter_parameters | Array, nil | nil (auto) | Parameter-name patterns to redact; nil auto-detects from Rails. Replaces the deprecated dashboard_filter_parameters. |
metrics_enabled | Boolean | true | Expose Prometheus gauges on the dashboard. |
MCP server#
| Option | Type | Default | Description |
|---|---|---|---|
mcp_write_tools | Boolean | false | Build 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#
| Option | Type | Default | Description |
|---|---|---|---|
metrics_backend | Symbol, Object, nil | nil | Metrics adapter: nil, :prometheus, :statsd, or a Backend. |
statsd_host | String | "127.0.0.1" | StatsD UDP host. |
statsd_port | Integer | 8125 | StatsD UDP port. |
log_format | Symbol | :text | Log formatter (:text or :json). |
error_reporters | Array | [] | Callables invoked on caught exceptions. |
appsignal_enabled | Boolean | true | Enable the AppSignal subscriber + probe (when the gem is present). |
appsignal_probe_enabled | Boolean | true | Enable the minutely AppSignal gauge probe. |
Health & liveness#
| Option | Type | Default | Description |
|---|---|---|---|
health_port | Integer, nil | nil | Port for HTTP liveness/readiness probes; nil disables. |
health_bind | String | "127.0.0.1" | Bind address for the health server. |
health_unclaimed_grace | Numeric | 60 | Seconds 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_threshold | Numeric, nil | 90 | Seconds a checked-in worker or consumer loop may go without progress before the supervisor kills it. nil disables. |
boot_timeout | Numeric, nil | 120 | Seconds 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_timeout | Numeric | 30 | Read timeout for worker fetches. |
drain_timeout | Numeric | 30 | Seconds to wait for in-flight jobs to finish during graceful shutdown before abandoning them. |
immediate_shutdown_grace | Numeric | 2 | On QUIT, seconds a worker or consumer gives running jobs to finish before it kills them; killed jobs' ActiveRecord connections are reclaimed. |
shutdown_timeout | Numeric, nil | drain_timeout + 5 | Seconds 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)#
| Option | Type | Default | Description |
|---|---|---|---|
streams_enabled | Boolean | true | Enable the SSE streams transport. |
streams_default_retention | Numeric | 300 | Default stream retention in seconds. |
streams_retention | Hash | {} | Per-stream retention overrides. |
streams_heartbeat_interval | Numeric | 15 | SSE heartbeat interval (seconds). |
streams_peer_close_interval | Numeric, nil | 1.0 | How 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_connections | Integer | 2000 | Max SSE connections per web-server process. |
streams_idle_timeout | Numeric | 3600 | Close idle SSE connections after N seconds. |
streams_pool_size | Integer | 5 | Dedicated 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_timeout | Numeric | 5 | Seconds to wait for a connection from the dedicated streams pool. |
streams_pool_autoscale | Boolean | false | Self-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_max | Integer, nil | nil | Optional hard ceiling for streams-pool autoscaling. nil lets the dynamic per-process fair share of DB headroom be the effective cap. |
streams_path | String, nil | nil | Custom SSE endpoint path (auto-detected from mount). |
streams_falcon_streaming_body | Boolean | false | Use Falcon-native streaming body instead of hijack. Experimental — exempt from the 1.0 stability promise. |
streams_stats_enabled | Boolean | false | Record stream broadcast/connect/disconnect stats. |
streams_test_mode | Boolean | false | Return a stub SSE response (auto-enabled by the test helpers). |
streams_coalesce_scheduler | Object, nil | nil | What 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_authorize | Callable, nil | nil | Authorize 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_patterns | Array | [] | 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_member | Callable, nil | nil | Custom `->(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_ttl | Numeric, Hash | 60 | Seconds 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_change | Callable, nil | nil | `->(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_queue | String, nil | nil | Dedicated 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#
| Option | Type | Default | Description |
|---|---|---|---|
eager_validation | Boolean | true | Validate configuration eagerly at boot. |
allowed_global_id_models | Array, nil | nil | Allowlist 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_mode | Symbol | :auto | PGMQ schema install mode (:auto, :extension, :embedded). |
doctor_on_boot | Symbol, nil | nil | Run 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. |