Performance & tuning
Start with the throughput checklist, then tune autovacuum for the high-churn queue tables, size archive retention, and watch the health metrics.
Throughput checklist#
Every knob that moves jobs/s, with its measured effect and what it costs.
More processes first, then fewer and cheaper Postgres statements per job, then the knobs for a database on another host, then Ruby CPU, then the Postgres side. Each item gives the setting and its default, what it measured in docs/performance.md, and what it costs. Those are no-op jobs on one 12-core M-series laptop with Postgres on the same machine; "proxied" adds 1 ms per round trip through toxiproxy, the shape of a database on another host. A real job's own work dilutes every number, so measure your own shape with rake bench:fleet and rake bench:worker_profile before and after. Every pgbus option it names is in the configuration reference; RUBY_YJIT_ENABLE, config.yjit and config.active_job.logger belong to Ruby and Rails.
- More processes.
processes:per capsule (default 1). Measured: locally (YJIT, 12 threads) 7 790–7 986 jobs/s for one process and 14 277–17 879 for four; two give 1.5–2.2× and four 1.8–2.6× the same round's one, and eight (6-thread workers) run below four. Proxied, four run 3.9–4.6× one. Costs: every process brings its own pgmq pool, ActiveRecord connections and memory (peak connections 16 for one 12-thread process, 58–62 for four); locally Postgres is what bends. More cores · Threads vs processes. - Prepared statements.
native_statements(defaulttrue): leave it on. Measured: median Postgres time per job falls about 70 % at one process and 34–42 % at four; median jobs/s +11 % (one process) and +20 % (four) with YJIT, unchanged without a JIT. Costs: behind a transaction-mode PgBouncer it needs PgBouncer 1.21+ withmax_prepared_statements. Turning it off also gives up the check that a re-run archive or delete which finds its ids gone may have committed: the function path keeps pgmq-ruby's plain reconnect retry. Prepared statements. - Batched completion.
completion_batching(defaultfalse;completion_batch_size100), threads only. Measured: at four local processes jobs/s +17–35 %, Postgres time per job 0.26–0.34 → 0.06–0.07 ms, statements per job ~1.23 → ~0.4; two processes gained nothing. One process: up to a third slower. Withread_aheadacross a network: 10–30 % slower. Costs: a hard crash re-runs the jobs of the current flush, not one job. Turn it on for several processes on one Postgres when the fleet bench's waits showLWLock:WALWriteon top. Batch the archives. - Delete instead of archive.
completed_jobs = :delete(default:archive). Measured: batched delete at four local processes is the fastest shape measured, +11–13 % jobs/s over batched archive by median (19 830 → 22 000 with YJIT). Unbatched, Postgres time per job falls in five of six rows (0.058 → 0.022 ms at one YJIT process) and jobs/s rises 10–35 % in four of six rows by median, with overlapping ranges. Costs: no completed-job history in thea_tables (with job stats on, Insights still counts every success).Batch::Sweepcounts a stale batch job whose message is in neither the queue nor the DLQ as completed, so a purged queue's batch jobs count as completed too. ActiveJob only. Archive retention. - Asynchronous completion commit.
completion_synchronous_commit = false(defaulttrue), native statements on pgbus's own connections only. Measured: on a shared local machine the WAL-flush wait (LWLock:WALWrite) fell from 12–23 % of sampled waits to 2 % at four processes, and Postgres time per job fell in five of six rows (0.417 → 0.331 ms at four YJIT processes, 0.223 → 0.138 batched with delete); jobs/s stayed inside the run-to-run noise (median 9 550 → 10 620 at four YJIT processes, 10 692 → 15 302 batched with delete, overlapping ranges). The single call did not get slower. Costs: withcompletion_synchronous_commit = false, a completion is acknowledged before its WAL record reaches disk. 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, within about three timeswal_writer_delay(default 200 ms) can lose completions committed in that window. Each lost completion redelivers its job after the visibility timeout, so the job runs again. Under synchronous replication it also stops waiting for the standby for that transaction, which is what lets a failover lose it. Sends, retries and dead-letter moves keep full durability. A durable write after the completion (a concurrency signal, a batch counter) flushes it too; the job's own ActiveRecord writes run before it and do not. Not for jobs that cannot run twice after a database crash or failover. Untested behind PgBouncer in transaction mode: use session mode or leave it on.docs/performance.md. - Read-ahead, for a database on another host.
read_ahead = threads(default 0), per capsule and per event consumer too. Measured: proxied, 1.4–1.9× jobs/s for workers and event consumers; locally within noise. Costs: buffered messages count as in flight againstprefetch_limit; on drain, recycle or shutdown they go back withread_ctalready counted; the hold needsvisibility_heartbeat(defaulttrue). Read-ahead. - The pool, sized with read-ahead.
pool_size(defaultnil: sized from the thread counts). Measured: withread_ahead12, job threads spent 14–15 % of their time waiting to check out a pgmq connection from the default pool (~7 for 12 threads), up from 2–3 %. Costs: connections. Budgetresolved_pool_size + streams_pool_sizeper process againstmax_connections. Job bursts. - LISTEN/NOTIFY.
listen_notify(defaulttrue): keep it on; polling everypolling_intervalis the fallback. Measured: not as a throughput lever; a wake-up's p50 latency is 1.66ms through the supervisor's shared listener. Costs: one direct LISTEN connection per host under the defaultworker_notify_scope: :supervisor. - YJIT.
RUBY_YJIT_ENABLE=1, orconfig.yjiton Rails 7.2+; pgbus never turns a JIT on, andpgbus doctorreports which one runs. Measured: ~14–20 % locally (the single-worker profile); nothing measurable proxied. Costs: the memory of YJIT's compiled code (not measured here). - ActiveJob's per-job log lines. At
info, ActiveJob formats and writesPerforming …andPerformed …for every job.config.quiet_active_job_logs = true(defaultfalse) drops those two lines in worker processes only: it unsubscribes ActiveJob's log subscriber fromperform_startandperform.Enqueued,Retrying,Stopped retryingandDiscardedstill log, and the web process andRails.loggerare untouched. To quiet every ActiveJob line instead, give ActiveJob its own logger atwarninconfig/environments/production.rb:config.active_job.logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new($stdout, level: :warn)). NotActiveJob::Base.logger.level = :warn: by default that logger isRails.logger, and the line silences the whole app. Measured: the two lines are 5 % (YJIT) and 9–10 % (no JIT) of a worker's on-CPU time; without a JIT the knob and thewarnlogger each buy +6–10 % jobs/s, equal within noise, and with YJIT neither moves jobs/s measurably. Costs: no per-job lines in the log. The knob also drops ActiveJob'sError performing …line, which the sameperformlistener writes: an exception that escapes ActiveJob's handlers is still logged by pgbus (class and message aterror) and kept inpgbus_failed_eventswith its backtrace, oneretry_oncatches still logs ActiveJob'sRetrying …line, and a job abefore_performcallback halted logs nothing. Thewarnlogger keeps theerrorlines but also silencesEnqueuedandRetryingin every process, keeps the job tags only when wrapped inTaggedLogging, and writes where you point it, not whereRails.loggergoes. - Job stats.
stats_enabled(defaulttrue): keep it on. Measured: in the mocked executor bench, execute 65.8k / 66.4k i/s and execute + stat recording 60.1k / 59.4k i/s (39.9k / 40.5k before #604). The real worker's stats flush (one multi-row INSERT per flush once the latency migration has run, two before it: the six-column attempt and the base-column retry; at the defaultstats_flush_sizeof 100, measured on 100-row flushes) costs 1–2.3 µs of Ruby CPU per job, down from 9–20 µs withinsert_all(12–15 % of a no-op job's on-CPU time before #622). Flushes triggered bystats_flush_intervalcarry fewer rows and cost more per job. Costs: turning it off empties Insights, which undercompleted_jobs = :deleteis the only record of a success. - Already in the default path, no knob: the enqueue no longer runs a
pgbus_batch_executionsUPDATE for a job in no batch ("adapter: plain job" 4 579 / 4 563 → 7 401 / 7 983 i/s), and the executor readsenqueued_atwithTime.new(+5 % jobs/s without a JIT). Upgrade to get them. - The Postgres side. Fillfactor (
rails generate pgbus:tune_fillfactor), autovacuum (rails generate pgbus:tune_autovacuum),archive_retention(default7.days) and themax_connectionsbudget.commit_delay(withcommit_siblings) groups concurrent commits into one WAL flush and keeps every commit durable: the server-side alternative tocompletion_synchronous_commit = false. Measured: not measured as throughput levers; they keep the queue tables from bloating as volume grows.
Not levers (why, in docs/performance.md):
- Ractors: the host's job classes, ActiveRecord, Zeitwerk and ActiveJob are not Ractor-safe, so
perform_nowcannot move into one. - A C or Rust extension: it reaches only pgbus's own share of on-CPU time (35 % in #484), a ≤ 1.5× bound for one process, and makes pgbus a compiled gem for every host.
- Spinel or Roundhouse: Spinel runs no RubyGems or C extensions (so no
pg), and Roundhouse turns the whole app into a non-Ruby program pgbus is not part of.
Autovacuum tuning#
Queue tables churn far faster than the Postgres defaults expect.
PGMQ queue tables see heavy insert/delete churn — a message is inserted, read (an UPDATE), and archived (a DELETE) in seconds. PostgreSQL's default autovacuum is too conservative for that, so dead tuples accumulate and indexes bloat. pgbus applies aggressive per-table tuning automatically: new queues get it at creation, the install migration tunes the default queue, and pgbus:update detects untuned tables.
db:schema:load drops ALTER TABLE settings, so re-apply after a schema load with the generator:
rails generate pgbus:tune_autovacuum # generate the migration
rails generate pgbus:tune_autovacuum --database=pgbus # for a separate databasepgbus_oldest_transaction_age_seconds.Archive retention#
Archive tables grow unbounded without it, or skip them with completed_jobs :delete.
Archived (successfully-processed) messages accumulate in the a_<queue> tables. The dispatcher compacts them hourly; size the window to your volume:
Pgbus.configure do |config|
config.archive_retention = 3.days # default 7.days; nil disables cleanup
endIf nothing reads the completed jobs' archive, skip it. completed_jobs = :delete finishes a successful job with pgmq.delete, the DELETE alone, instead of the archive's DELETE + INSERT (delete_batch instead of archive_batch with completion_batching). Newly completed jobs add no a_ rows and no archive index entries; rows archived before the switch stay until archive_retention compacts them. The message is gone once the statement commits either way. You lose the completed-job history in the archive; with job stats on (stats_enabled and the pgbus_job_stats table migrated), the Insights page still counts every success. One thing the archive did tell apart: Batch::Sweep counts a stale batch job whose message is in neither the queue nor the DLQ as completed, so a purged queue's batch jobs count as completed too.
Pgbus.configure do |config|
config.completed_jobs = :delete # default :archive
enddocs/performance.md → "Delete mode".Job bursts: raise threads and the pool together#
Under a job spike, the DB connection pool is the ceiling — not the thread count.
When a queue floods, the instinct is to add worker threads. But a job holds a database connection only for the brief read_batch + archive round-trip — not for the job body — so a worker's throughput is capped by its connection pool, not its thread count. Adding threads past the pool size just makes them queue on connection checkout: latency climbs, throughput doesn't.
So size the two together. Raising threads alone plateaus at the pool size; raising both scales throughput roughly linearly (measured 8× from 2→16 when the pool matches). The connection pool auto-tunes from the thread count by default, so in practice you raise threads and let pool_size follow — but if you pin pool_size, keep it ≥ threads.
Pgbus.configure do |config|
config.worker "default", threads: 16 # more concurrency…
config.pool_size = 20 # …needs the connections to back it
endrake bench:job_burst). Watch pgbus_worker_pool_utilization — sustained near 1 means raise both.More cores: run more processes#
One worker process runs about one core of Ruby; processes: N multiplies it.
Under the GVL a worker process uses about one core however many threads it has, so throughput past one core comes from processes:. Each process brings its own pgmq connection pool and its own ActiveRecord connections, so add both up for every process and keep the total under max_connections. On one queue and one Postgres the measured fleet scales almost linearly with 1 ms of simulated network latency per round trip (toxiproxy; each process is capped by its reader's round trips), and bends at 2–4 processes with Postgres on the same machine: every job's archive is its own commit, and every process works on the same hot pages of the one queue table. The table and the Postgres cost per job are in docs/performance.md → "Fleet scaling".
rake bench:fleet: it drains one queue with WP_BENCH_PROCESSES (default 1,2,4) worker processes and reports jobs/s, and Postgres milliseconds per job from pg_stat_statements when it is available (n/a otherwise).Database on another host: turn on read-ahead#
Under network latency the worker's single reader is the ceiling.
A worker reads in one loop and runs jobs on its pool. Once the pool is busy, threads free one at a time, so each read claims one message: one read round trip per job. Add a millisecond of network to every round trip and that loop caps a worker at a fixed number of jobs per second, however many threads it has. read_ahead claims extra messages and holds them (kept invisible by the visibility heartbeat) until a thread frees, so one read feeds many jobs. Start with read_ahead equal to threads:
Pgbus.configure { |config| config.read_ahead = 12 } # or per capsule / event consumerrake bench:worker_profile (set PGBUS_BENCH_PROXY_URL to a Postgres behind toxiproxy, and WP_BENCH_READ_AHEAD to the value to try). It drives a real worker and a real event consumer and reports jobs/s plus where each thread's time goes.Several processes on one Postgres: batch the archives#
One archive_batch per flush instead of one pgmq.archive per job. Opt-in, threads only.
Every successful job archives its message, and each archive is its own commit. With several worker processes on one Postgres those commits queue on the WAL flush, and that is where the fleet bends. completion_batching gives each worker one completer that archives the jobs finishing close together with one archive_batch. There is no timer: a lone job is archived at once, and whatever finishes during a flush goes in the next. completion_batch_size (default 100) caps the ids per statement.
Pgbus.configure do |config|
config.completion_batching = true # threads only; rejected with execution_mode :async
endMeasured with four processes on a local Postgres: about 5 jobs per statement, Postgres time per job down 4–5×, jobs/s up 17–35 %; two processes gained nothing. Turn it on for several processes on one Postgres when the fleet bench's waits show LWLock:WALWrite on top. Leave it off for a single process, where it gains nothing and measured up to a third slower, and with read_ahead on a remote database, where each job thread waits a full round trip for its flush (10–30 % slower). The numbers are in docs/performance.md → "Batched completion".
visibility_timeout, and a flush that committed just before the crash leaves its jobs completed but unsignalled (uniqueness lock, batch counter, concurrency slot) until pgbus's reapers and sweeps heal them. On a QUIT the worker stops the completer before it kills the running jobs, so a flush that answers in time resolves every waiter. Shutdown waits for a flush at most immediate_shutdown_grace (QUIT) or what is left of the 5-second residual (TERM). A flush still wedged after that is abandoned and its jobs run again; if Postgres had committed it and only the reply stalled, those jobs are left completed but unsignalled, as after a crash.WP_BENCH_COMPLETION_BATCHING=1 rake bench:fleet against the same run without it.Prepared statements and connection poolers#
The hot queue operations are planned once per connection.
pgmq's read, archive, delete, send and send_batch are plpgsql functions that build their SQL and run it with EXECUTE, which Postgres parses and plans again on every call. pgbus runs the same statements as its own SQL in named prepared statements on each pooled connection (config.native_statements, on by default), so Postgres plans each one once per connection. Everything a caller sees is unchanged: return values, read_ct, vt, headers, and the queue's NOTIFY trigger, which fires on the same INSERT. A queue whose table lacks a column the statements use (a pgmq extension older than the headers column) keeps calling the pgmq functions by itself. The measurements are in docs/performance.md → "Native statements".
max_prepared_statements set. Without it, the pooler drops them between transactions; a process that sees that switches to sending the same SQL unprepared and logs a warning once; with prepared_statements: false in database.yml (and no pgbus database_url or connection_params Hash of its own) it sends it unprepared from the start. config.native_statements = false uses the pgmq functions everywhere. See also connection_guc_mode for the same pooler.Streams master hub#
One streams LISTEN connection per web host.
Each Puma worker used to open its own dedicated streams LISTEN connection on first SSE use — one direct connection per worker, on the same scarce direct-port budget the job-side supervisor scope protects. By default (streams_listen_scope = :master) the pgbus_streams plugin now runs one shared listener in the Puma master; workers connect to it lazily over a Unix socket and receive every wake — including ephemeral broadcast payloads — as framed messages.
preload_app! # required for :master — the hub waits for the pgbus initializer
plugin :pgbus_streamsDelivery semantics are unchanged: the synchronous subscribe/ack contract crosses the process boundary, durable wakes self-heal via read_after, and ephemeral wakes are never dropped by the transport. The measured cost of the extra hop is noise-level (single-broadcast SSE roundtrip p50 16.0ms via the hub vs 16.9ms per-worker on the same machine).
preload_app!, single-mode Puma, crash), each worker falls back to its own listener — the connection footprint balloons back to one per worker (visible in pgbus doctor's Connection budget and the pgbus-listen census) but no broadcast is ever lost. Roll back with streams_listen_scope = :process.Streams pool autoscaling#
Let the SSE streams pool grow into spare connections under a burst, and shrink back when it's over.
The dedicated streams pool (used for durable-broadcast publish and the dispatcher's replay reads) is normally a fixed size — streams_pool_size (default 5). Under a genuine burst of SSE clients that pool can saturate, and a saturated pool serialises replay reads (it doesn't error — the checkout just waits), so broadcasts fan out more slowly. For steady load, the right fix is simply a larger streams_pool_size. For bursty load, opt into autoscaling: a periodic maintenance check grows the pool into a fair share of live Postgres connection headroom while it's saturated and shrinks it back to streams_pool_size when the burst passes.
Pgbus.configure do |config|
config.streams_pool_autoscale = true # opt-in; default false
config.streams_pool_size = 5 # baseline + shrink floor
config.streams_pool_max = 12 # optional hard per-process cap
config.streams_pool_autoscale_interval = 300 # check cadence, seconds (default 5 min)
endThere is no connection-count target to tune. Every threshold derives from live max_connections: each check reads pg_stat_activity, counts how many pgbus stream processes share the database, and grows only into its own fair share of the free connections. streams_pool_max is an optional hard ceiling — leave it nil and the dynamic fair share is the cap.
pg_stat_activity query that runs on an existing idle connection every streams_pool_autoscale_interval seconds — like pghero's periodic stats capture. In a web process serving SSE it rides the streamer's idle LISTEN connection; a background worker that only publishes broadcasts triggers the same throttled check from the publish path (on the job pool), so pure-publisher processes autoscale too. One grow (or shrink) step per check; a sustained burst converges over a few checks.application_name it uses to count peers, so it falls back to assuming it's the only process (still connection-safe, just less precise). It's also a no-op on the shared-ActiveRecord connection path. When in doubt, a larger static streams_pool_size is always the simpler choice.streams_port = 5432), the streams pool follows it by default — putting streams_pool_size connections per process on the direct port's low max_connections ceiling. Only LISTEN needs the direct port; the pool's traffic is pooler-safe. Route the pool back through the pooler with streams_pool_port = 6432 (or streams_pool_host / streams_pool_database_url).Fan-out throughput: raise the writer threads#
When broadcasts fan out to many SSE clients, scale the writer pool statically.
With streams_writer_threads > 0, durable broadcast socket writes move off the dispatcher into a pool of writer threads (each connection pinned to one worker so its frames stay ordered). If you fan out to a large fleet of connections, more writer threads flush them in parallel — throughput scales roughly linearly with the count.
Pgbus.configure do |config|
config.streams_writer_threads = 8 # more parallel socket writes
endstreams_fanout_write_deadline_ms, default 250 ms, which also bounds each heartbeat write) evicts it, and it reconnects and replays from the durable archive. So the writer pool scales fan-out throughput; it doesn't need to grow to absorb slow clients. Size streams_writer_threads for your peak fan-out fleet (measured with bench:one[writer_burst_bench]).The metrics that tell you when to tune#
The dashboard's Queue Health panel and the Prometheus gauges surface the signals that predict trouble before it becomes an incident:
| Metric | Watch for |
|---|---|
pgbus_table_dead_tuples | Dead tuples climbing — vacuum isn't keeping up. |
pgbus_table_bloat_ratio | Dead / (dead + live) rising toward 1. |
pgbus_table_last_vacuum_age_seconds | Long gaps since the last vacuum. |
pgbus_oldest_transaction_age_seconds | A long transaction pinning the MVCC horizon. |
pgbus_worker_pool_utilization | Busy / capacity near 1 — you need more threads. |
docs/performance.md.