Migrate

Upgrading pgbus

The standard upgrade procedure, plus what changes on each hop.

Overview#

Every pgbus upgrade — patch, minor, or major — follows the same six-step procedure: update the gem, review and apply the migration generator, migrate the database, check the vendored PGMQ schema, deploy, then verify with pgbus doctor. The steps below are generic; per-version sections list only what's different for that hop.

Work through the sections oldest first if you're behind by more than one release — each section assumes the previous one is done.

The standard upgrade procedure#

Every version, every hop.

  1. Update the gem
bundle update pgbus
  1. Review the upgrade plan — pgbus:update inspects your live database and reports exactly which migrations are missing; --dry-run prints the plan without creating any files.
rails generate pgbus:update --dry-run
  1. Apply it — drop --dry-run to create the migration files. The generator auto-detects a separate database from Pgbus.configuration.connects_to or by scanning your initializer / config/application.rb — you don't need to pass --database=pgbus yourself unless auto-detection can't find it.
rails generate pgbus:update
  1. Migrate the database — use the :pgbus variant if you run pgbus on a separate database.
rails db:migrate            # single database
rails db:migrate:pgbus      # separate-database install
  1. Check the vendored PGMQ schema — pgbus:update only handles pgbus's own tables; PGMQ's internal schema (the pgmq.* functions and types) is versioned separately and upgraded on its own generator.
rake pgbus:pgmq:status

If it reports an update available, generate and run the upgrade migration:

rails generate pgbus:upgrade_pgmq
rails db:migrate
  1. Deploy, then verify:
bundle exec pgbus doctor

doctor runs seven checks — configuration validity, database connectivity, PGMQ schema version, queue existence, LISTEN/NOTIFY liveness, process liveness, and the GlobalID allowlist (a security warning when allowed_global_id_models is nil in production) — and exits non-zero on any failure, so it's safe to wire into a deploy gate or a post-deploy CI job.

Rolling deploys are safe. Pgbus's heartbeat and process metadata fields are additive-only across versions, so an old-version worker and a new-version worker can coexist during a rolling deploy without corrupting each other's heartbeat rows. Restart your supervisors after the web tier has migrated, so no process reads a schema column that doesn't exist yet.

0.9.x → 0.9.8#

Two behavior changes, one PGMQ schema bump.

Breaking: queue names must be alphanumeric + underscores

Queue names containing dashes (my-app-queue) now raise ArgumentError at boot. This closes a SQL-injection surface — PGMQ queue identifiers are interpolated into table names and can't be parameterized — but it means a dashed queue name that worked on 0.9.7 will crash on 0.9.8.

Rename any dashed queue names to underscored form before upgrading (my-app-queue → my_app_queue), in both your Pgbus.configure block and any code that references the queue name directly. There is no automatic migration for this — a queue is just a Postgres table name, so renaming means creating the new queue and draining the old one.

Breaking: configuration is now validated eagerly at boot

Pgbus.configure now calls Configuration#validate! automatically after your block runs. An invalid value — visibility_timeout = 0, for example — now raises ArgumentError at boot instead of surfacing later, far from the misconfiguration, the first time a worker touches that setting.

If you rely on a config that is transiently invalid between multiple sequential configure blocks, opt out with:

config/initializers/pgbus.rb
Pgbus.configure do |c|
  c.eager_validation = false
end

PGMQ vendored schema: 1.11.0 → 1.11.1

This hop moves the vendored PGMQ schema forward one patch version — a concrete example of step 5 in the standard procedure above. Run rake pgbus:pgmq:status after updating the gem; it will report installed 1.11.0, vendored 1.11.1 and tell you to run:

rails generate pgbus:upgrade_pgmq
rails db:migrate

New in 0.9.8 (all opt-in)

None of the following change existing behavior — each is a new, off-by-default capability:

FeatureWhat it adds
Observabilitymetrics_backend — Prometheus/StatsD metrics without hand-writing subscribers.
Running workershealth_port / HTTP /livez and /readyz endpoints for orchestrators.
pgbus dlqCLI dead-letter management (list/show/retry/purge) without the dashboard.
pgbus doctorThe single preflight command this guide uses to verify every upgrade.

0.11.x → 0.12.0#

One PGMQ schema bump — no pgbus behavior changes.

PGMQ vendored schema: 1.11.1 → 1.12.0

This hop moves the vendored PGMQ schema forward one minor version — another instance of step 5 in the standard procedure above. The upstream delta is additive: one new function, pgmq.read_grouped_head_with_poll (a polling wrapper over read_grouped_head that waits up to max_poll_seconds for grouped messages to arrive); everything else is comments and whitespace, so no function pgbus calls changes shape. Run rake pgbus:pgmq:status after updating the gem; it will report installed 1.11.1, vendored 1.12.0 and tell you to run:

rails generate pgbus:upgrade_pgmq
rails db:migrate            # single database
rails db:migrate:pgbus      # separate-database install

0.16.x → 0.17.0#

PGMQ 1.13.0, and upgrades now carry upstream's table fixups.

PGMQ vendored schema: 1.12.0 → 1.13.0

Another instance of step 5 in the standard procedure. The upstream delta is entirely partitioned-queue work plus one metrics attribute:

  • pgmq.create_partitioned gains a fourth argument, premake (default 4), and its three-argument form is dropped so calls resolve to one function. pgmq-ruby passes three arguments, which now bind to the new signature with the default premake — nothing to change.
  • New partitioned queues use msg_id … GENERATED BY DEFAULT AS IDENTITY instead of GENERATED ALWAYS, so pg_partman's partition_data_* tooling can move rows out of the default partition. Ordinary queues are unchanged.
  • pgmq.metrics_result gains default_partition_length, reported by pgmq.metrics(). It is NULL for non-partitioned queues.

No function pgbus calls through Pgbus::Client changes shape, and pgbus does not create partitioned queues (only partitioned archives, whose msg_id is a plain column). Run rake pgbus:pgmq:status after updating the gem; it will report installed 1.12.0, vendored 1.13.0 and tell you to run:

rails generate pgbus:upgrade_pgmq
rails db:migrate            # single database
rails db:migrate:pgbus      # separate-database install

Upgrades now carry upstream's table fixups

The generated migration drops every PGMQ function and composite type and re-runs the target version's schema. That reproduces every function and type change, but it can never touch an existing table — so an upstream hop that alters one used to be silently skipped.

The migration now has a fourth step: it reads the version recorded in pgbus_pgmq_schema_versions and applies the fixup shipped for every version between that and the target. This hop's fixup is upstream's own guarded block moving existing partitioned queues' msg_id to GENERATED BY DEFAULT. It selects on pgmq.meta.is_partitioned, so on an install with no partitioned queues — which is every pgbus-managed database unless you created them through PGMQ directly — it is a no-op.

Fixups are idempotent, so an install whose version was never recorded gets all of them safely, and re-running a migration cannot corrupt anything.

0.21.x → next release#

PGMQ 1.13.1, a security release upstream asks everyone to take.

PGMQ vendored schema: 1.13.0 → 1.13.1

Another instance of step 5 in the standard procedure. Upstream ships two security fixes and one NOTIFY fix:

  • Every PGMQ function pins search_path = pg_catalog, pg_temp and schema-qualifies its built-ins, so a role that can create objects in a schema on another role's path (public, say) can no longer shadow a built-in and run code with that role's privileges.
  • pg_monitor can no longer read message payloads. It used to get SELECT on every table in the pgmq schema. It now gets SELECT on pgmq.meta, SELECT (vt, enqueued_at) on each queue table and SELECT on each queue's msg_id sequence: what pgmq.metrics(), pgmq.metrics_all() and pgmq.list_queues() need, nothing else. A monitoring role that read queue or archive tables through pg_monitor loses that access.
  • Insert notifications fire for a queue whose name is not all lowercase. The trigger now gets the queue name as an argument; it used to rebuild it from the lowercased table name, which matched no throttle row, so a pgbus queue with an uppercase letter in its name never woke a worker through NOTIFY and fell back to polling.

No function pgbus calls through Pgbus::Client changes shape. Run rake pgbus:pgmq:status after updating the gem; it prints Vendored version: 1.13.1 and Installed version: 1.13.0, then Update available! Run: rails generate pgbus:upgrade_pgmq. Run:

rails generate pgbus:upgrade_pgmq
rails db:migrate            # single database
rails db:migrate:pgbus      # separate-database install

The migration's fixup step does on existing tables what re-creating the functions cannot:

  • removes the default privileges and the whole-table SELECT grants pg_monitor had in the pgmq schema, and grants the metrics columns and sequence on every existing queue;
  • rebinds a queue's enqueued_at (and the archive's archived_at, the tables' created_at/bound_at/last_notified_at) default to pg_catalog.now() or pg_catalog.to_timestamp(0) when it resolved to a function of that name outside pg_catalog. A default bound to any other non-catalog function stops the migration with an error naming the column, so you can inspect it. So does a default the migrating role is not allowed to alter: run the migration as the role that owns the pgmq tables, or as a superuser.

The NOTIFY repair the migration already runs re-creates every queue's trigger with the queue name attached.

A grant the migrating role does not own cannot be revoked. The migration then raises a WARNING starting with pgmq: instead of failing, and still records 1.13.1, so pg_monitor can keep reading payloads on that object. PostgreSQL sends the warning to the client connection: Rails hands it to its logger only when config.active_record.db_warnings_action is set (to :log, say); otherwise it goes to the migrating process's stderr. Look for one after migrating and run the statement it prints as the object's owner or a superuser.

An :extension install gets the same changes from ALTER EXTENSION pgmq UPDATE TO '1.13.1' once the server has 1.13.1 packaged, not from this migration.

:while_executing now honours on_conflict:

ensures_uniqueness strategy: :while_executing accepted on_conflict: and never read it: a copy read while another copy held the key was skipped and redelivered, whatever the policy. Now the policy decides (issue #629):

  • on_conflict: :discard drops the copy. It is completed without running. A job that relied on the trailing run — "a run that starts after the current one sees the latest state" — got it by accident and loses it. Move such a job to strategy: :until_executing, which gives that guarantee by design (add limits_concurrency to: 1, on_conflict: :block if two runs must not overlap):
app/jobs/rollup_job.rb
# Before: the trailing run came from the skip-and-redeliver path.
ensures_uniqueness strategy: :while_executing,
                   key: ->(parent_id) { "rollup-#{parent_id}" }, on_conflict: :discard

# After: a debounce, with the trailing run by design.
ensures_uniqueness strategy: :until_executing,
                   key: ->(parent_id) { "rollup-#{parent_id}" }, on_conflict: :discard
  • :reject (the default) and :log keep the redelivery, now backed off from visibility_timeout instead of on the flat timeout, so a long holder no longer dead-letters every queued copy within max_retries × visibility_timeout. A copy that is skipped past max_retries still dead-letters; when none of its attempts failed and the key's row is not its own crashed attempt's, the reason is uniqueness_conflict instead of an empty max_retries_exceeded. :log logs each skip at warn.
  • A recurring :while_executing task is protected. The scheduler now carries its key, so the next run waits for a run that outlasts its interval (or, under :discard, is dropped) instead of overlapping it.

Messages already queued when you deploy carry no policy and keep the old redelivery (as :reject, with the backoff). A skip or a discard no longer counts as a success for the circuit breaker.

Queue names are lower case

PGMQ spells every queue table in lower case but records each spelling in pgmq.meta, so Orders and orders shared pgmq.q_pgbus_orders while the dashboard listed two queues. pgbus now spells every queue name in lower case (queue_name("Orders") == "pgbus_orders", and a queue_prefix of "MyApp" becomes "myapp"). No table moves: PGMQ already kept each queue in its lower-case table, and its messages stay where they are.

An install with a queue that has an upper-case letter in its name (a mixed-case name in queues: or queue_as, or a GlobalID stream such as pgbus_stream_from Current.user) keeps working after the deploy, but lists that queue twice until its rows are folded. pgbus doctor names them under "Queue name case", and pgbus:update lists the migration that folds them. Run it after every process runs the new version: an older process that restarts recreates its mixed-case row, and the migration runs once. A row that comes back after it is folded by rake pgbus:queues:fold_case, which runs the same fold.

rails generate pgbus:fold_queue_name_case
rails db:migrate            # single database
rails db:migrate:pgbus      # separate-database install

It renames each of pgbus's mixed-case pgmq.meta rows (those named after queue_prefix; another PGMQ user of the schema keeps its spelling) to the lower-case spelling, moves its NOTIFY throttle and topic bindings, re-arms its insert trigger under the new name, and lower-cases pgbus_stream_queues, pgbus_queue_states, pgbus_uniqueness_keys.queue_name and pgbus_failed_events.source_queue. Where both spellings exist, it deletes only the extra pgmq.meta row. It never drops a table.

Rows that collide once lower-cased are merged, keeping one: pgbus_stream_queues and pgbus_queue_states keep one row per queue (a paused state wins), and a message that failed under two spellings of its source queue keeps one failed-event row, the lower-case one or else the newest, so the older error of that message is deleted.

Until the fold runs, the dashboard lists such a queue under both spellings. Dropping the mixed-case entry (from the dashboard, or the orphan stream sweep) removes only its pgmq.meta row; the table, its messages and their uniqueness locks stay with the lower-case queue. Dropping the lower-case entry drops the queue, and both rows with it. Purging either entry purges the one shared table: both list the same messages.

Until the last old process stops, an old web process LISTENs on the mixed-case channel, so its SSE clients miss broadcasts until they reconnect; an old worker falls back to polling; and a uniqueness lock an old process takes under the mixed-case name after the fold ran is not released by a new process, so its key stays held until the orphan-lock reaper (every five minutes) frees it once the job is gone. A lock taken before the fold is lower-cased with it, and a new process releases it as usual. Two stream names that differ only in case now share one queue, as their table already did.

0.9.8 → 1.0.0#

The 1.0 API freeze: error hierarchy, config renames, and dead-surface removal.

The 1.0.0 commitment

1.0.0 marks pgbus's semver commitment: after 1.0.0, a breaking change to any documented public API bumps the major version. The 0.x series has made breaking changes in minor releases (see the 0.9.8 section above); 1.0.0 is where that stops. Everything below is surface the two API-freeze issues identified as needing to change before that commitment takes effect — either because it's a genuine correctness fix (the error hierarchy) or because it's free to rename now and expensive to rename after (config keys, dead code).

Breaking: unified error hierarchy (#282)

Every operational error pgbus raises now descends from Pgbus::Error, so rescue Pgbus::Error catches them all. Four call sites that previously raised bare stdlib errors changed:

Raised beforeRaises nowWhere
ArgumentErrorPgbus::ConfigurationErrorConfiguration#validate! and its setters
RuntimeErrorPgbus::ExecutionPoolErrorAsyncPool
RuntimeErrorPgbus::EnqueueErrorActiveJob adapter (perform_all_later msg_id mismatch)
ArgumentErrorPgbus::SerializationErrorSerializer#locate_global_id

Three error classes that bypassed Pgbus::Error entirely (PgmqSchema::VersionNotFoundError, Streams::SignedName::InvalidSignedName and MissingSecret) are now re-parented underneath it. Three classes that reject a malformed argument shape — CapsuleDSL::ParseError, Streams::Cursor::InvalidCursor, Streams::StreamNameTooLong — deliberately stay ArgumentError subclasses, since that's what ArgumentError means. The policy ("argument-shape errors are ArgumentError, operational errors are Pgbus::Error") is documented at the top of lib/pgbus.rb.

The one breaking change for existing code: if you rescue ArgumentError around Pgbus.configure or a boot-time config read, that rescue no longer catches config errors — Configuration#validate! and its setters now raise Pgbus::ConfigurationError, which is not an ArgumentError. Switch to:

config/initializers/pgbus.rb
begin
  Pgbus.configure { |c| c.visibility_timeout = 0 }
rescue Pgbus::Error => e   # was: rescue ArgumentError
  Rails.logger.error("pgbus config invalid: #{e.message}")
  raise
end

Error messages are unchanged, so any rescue ... => e that only reads e.message keeps working. Only the rescued class changed.

Config renames and dead-surface removal (#283)

Renames ship as a deprecated alias in 1.0.0 — the old name still works but logs a warning once — with removal in a future 2.0. Nothing breaks at 1.0.0 except surface confirmed to have zero real-world callers (verified in the API-freeze audit):

Old1.0.0Path
skip_recurringRenamed to recurring_enabled (positive polarity — true means run).Old name aliases (inverting the boolean) and warns once; removed in 2.0.
dashboard_filter_parametersRenamed to web_filter_parameters (unify on the web_ prefix).Old name aliases and warns once; removed in 2.0.
dashboard_filter_sensitiveRenamed to web_filter_sensitive.Old name aliases and warns once; removed in 2.0.
recurring_tasks_fileDeprecated in favor of recurring_tasks_files (plural).Setting both now warns once (the singular was silently ignored before); a lone singular still works.
lock_ttl:Removed from ensures_uniqueness — validated but never read by anything.Passing it raises ArgumentError naming the removal and this page.
pgbus:add_job_locksGenerator removed; Pgbus::JobLock model removed (zero references).No replacement — new installs use pgbus:add_uniqueness_keys; pgbus:migrate_job_locks still retires the legacy table.
with_pgbus_durableRemoved (internal streams helper, zero callers).Use with_pgbus_broadcast_opts(durable:).
Pgbus::Batch.new(on_discard:)Removed, with Batch#on_discard (deprecated since the on_failure: rename).Use on_failure: / #on_failure; passing on_discard: raises ArgumentError (unknown keyword).
on_finish:Still a deprecated alias of on_complete: (keyword, Batch#on_finish, b.on_finish); the on_finish_* columns stay.Warns once; removed in 2.0.
reconnect_via_resetRemoved — the streamer's conn.reset reconnect fallback (only test wiring reached it).connection_factory is now required on Streamer::Listener and always injected; reconnect always rebuilds a fresh connection.

Uniqueness: key: is now effectively required for argument-taking :until_executed jobs. Before, ensures_uniqueness strategy: :until_executed with no key: fell back to the job class name as the key. For a job that takes per-record arguments — ImportOrderJob.perform_later(order_id) — that collapsed every order into one per-class singleton (order 1 and order 2 shared a lock, so the second was silently discarded) with no warning. Now such a job raises ArgumentError at enqueue naming the collapse. Fix it by giving the key the arguments:

# Before (silently collapsed all orders into one):
ensures_uniqueness strategy: :until_executed

# After:
ensures_uniqueness strategy: :until_executed, key: ->(order_id) { "import-order-#{order_id}" }

A no-argument :until_executed job (e.g. a recurring CleanupJob that must not overlap itself) still uses the class-name default and does not raise — that case has one logical instance, so there is nothing to collapse. :until_executing (the debounce strategy added after 1.0.0) takes its lock at enqueue too, so it has the same guard: without a key:, an argument-taking :until_executing job raises the same ArgumentError. :while_executing is unaffected.

New in 1.0.0:

  • Pgbus.publish / Pgbus.publish_later — top-level shortcuts for Pgbus::EventBus::Publisher.publish / .publish_later, symmetric with Pgbus.stream. The long form still works.
  • config.drain_timeout (default 30s) replaces the hardcoded Worker::DRAIN_TIMEOUT constant — raise it if your jobs legitimately run longer than the graceful-shutdown window.
  • pgbus doctor now warns when allowed_global_id_models is nil (allow-all) in production. The default is unchanged for upgrade continuity, but set an explicit allowlist — it is security-relevant.

log_format= no longer overwrites a custom logger's formatter. streams_presence_*, group_mode, and streams_falcon_streaming_body are marked experimental and are exempt from the 1.0 stability promise.

1.0.x → next release#

PGMQ 1.13.2: pgmq.create() no longer waits on an existing queue's writers.

PGMQ vendored schema: 1.13.1 → 1.13.2

Another instance of step 5 in the standard procedure. Upstream changes two functions, pgmq.create_non_partitioned (what pgmq.create calls) and pgmq.create_unlogged:

  • pgmq.create() on an existing queue no longer waits for that queue's open transactions. It ran CREATE INDEX IF NOT EXISTS on the queue and archive tables, and CREATE INDEX takes a SHARE lock before it checks whether the index exists. A process ensuring its queues at boot therefore waited for every open transaction that had sent to one of them, and every send after it queued up behind the wait. The index is now created only when to_regclass(), which takes no lock, finds it missing.
  • pg_monitor's grants are issued only when it lacks them, so pgmq.create() on an existing queue no longer rewrites catalog rows.

The fix covers pgmq.create() only. Other DDL a pgbus process runs when it ensures a queue at startup still takes a table lock and still waits for that queue's open writers. Among them: re-arming a NOTIFY trigger that is missing or carries another throttle, a stream queue's trigger (re-armed on every cold start), the FIFO index under group_mode, and the fair-share index under fair_share. Under the default configuration, a job queue whose trigger is already in place no longer waits.

No table changes, so the migration carries no fixup for this hop: it drops and re-creates the functions as on every upgrade. Run rake pgbus:pgmq:status after updating the gem; it prints Vendored version: 1.13.2 and Installed version: 1.13.1, then Update available! Run: rails generate pgbus:upgrade_pgmq. Run:

rails generate pgbus:upgrade_pgmq
rails db:migrate            # single database
rails db:migrate:pgbus      # separate-database install

An install still on 1.13.0 or older gets every fixup on the way, 1.13.1's included; read the 0.21.x section above first. An :extension install gets 1.13.2 from ALTER EXTENSION pgmq UPDATE TO '1.13.2' once the server has 1.13.2 packaged, not from this migration.