| title | Function reference |
|---|---|
| description | Public functions, views, and types in PgQue's in-development default install — signatures, behavior, and role grants. |
This is the public API reference for the in-development default install
(\i devel/sql/pgque.sql). It follows the SQL on main; stable users should
use the reference at the latest stable release.
Each entry lists the signature, return type, role grant, and development source.
At release promotion, those source links are pinned to the release tag and
switched from devel/sql/ to sql/ as defined in the
documentation contract.
If you are new to PgQue, start with tutorial.md — it walks the end-to-end send / receive / ack loop. For task-oriented patterns see examples.md, and for tick-rate and delivery-latency tuning see latency-and-tuning.md. Use this page as the lookup table.
Functions are grouped into the modern API (the preferred surface: send, receive, ack, nack, DLQ, lifecycle) and the inherited PgQ primitives (advanced; the modern API wraps them 1:1).
Each entry takes this form:
One-line description. Optional second line with a caveat.
Grant: role_name. Source: sql/<path>.
Functions shipped outside this development install are in the Experimental section.
The development installer adds durable receive_page, receive_page_coop,
receive_page_partitioned, ack_page, and renew_page. These are not in
the release installer. See bounded batch processing for signatures,
checkpoint/lease semantics, failures, and an executable one-page example.
Single-message send wrappers delegate to pgque.insert_event; batch send_batch wrappers delegate to the internal set-based pgque.insert_event_bulk primitive. The text overloads are the fast path (bytes flow through verbatim); the jsonb overloads validate and canonicalize via Postgres before storing. Postgres text cannot store NUL (\x00), so raw binary must be base64/hex-encoded by the caller.
Argument names are part of the SQL API because Postgres supports named calls (arg := value). Available publishing arguments:
| Argument | SQL type | Meaning |
|---|---|---|
queue_name |
text |
PgQue queue name. |
type_name |
text |
Application event type stored in ev_type ('default' for 2-arg send). Free-form text such as order.created; this is not a Postgres type. |
payload |
text or jsonb |
Single event payload. text is opaque/verbatim; jsonb validates and stores canonical JSON text. |
payloads |
text[] or jsonb[] |
Batch payload array. Result array positions correspond to input positions. |
partition_key |
text |
Optional routing key for a partitioned consumer. Equal non-null keys route to the same slot; null routes to slot 0. |
idem_key |
text |
Queue-scoped producer idempotency key for one logical effect. |
ttl |
interval |
Positive deduplication window for send_idem; defaults to one hour. |
Available publishing overloads:
| Function | Payload type | Return |
|---|---|---|
send(queue_name, payload) |
text or jsonb |
bigint event id |
send(queue_name, type_name, payload) |
text or jsonb |
bigint event id |
send(queue_name, type_name, payload, partition_key) |
text or jsonb |
bigint event id |
send_idem(queue_name, type_name, payload, idem_key [, ttl [, partition_key]]) |
text or jsonb |
one (event_id bigint, deduped boolean) row |
send_batch(queue_name, payloads) |
text[] or jsonb[] |
bigint[] event ids, event type 'default' |
send_batch(queue_name, type_name, payloads) |
text[] or jsonb[] |
bigint[] event ids |
Use explicit casts (::jsonb, ::jsonb[], ::text[]) when overload resolution would otherwise be ambiguous. Untyped string literals choose the text fast path.
Named-argument note: modern publishing argument names are queue_name, type_name, payload, and payloads. Positional calls are unchanged.
Inserts payload into queue with event type 'default'. Returns the event id.
Grant: pgque_writer. Source: devel/sql/pgque-api/send.sql.
select pgque.send('orders', '{"order_id": 42}'::jsonb);Fast-path send: stores the payload bytes verbatim, no JSON parse. Untyped string literals ('…') resolve to this overload. Returns the event id.
Grant: pgque_writer. Source: devel/sql/pgque-api/send.sql.
Same as the 2-arg jsonb overload, but with an explicit event type. Returns the event id.
Grant: pgque_writer. Source: devel/sql/pgque-api/send.sql.
select pgque.send('orders', 'order.created', '{"order_id": 42}'::jsonb);Fast-path send with explicit event type. Returns the event id.
Grant: pgque_writer. Source: devel/sql/pgque-api/send.sql.
Keyed JSON send. Stores partition_key in extra1; partitioned consumers hash
it to a slot. Equal non-null keys with the same pinned slot count route to the
same slot. Events follow snapshot-window order, not global event-ID or
producer commit order. Grant: pgque_writer. Source:
devel/sql/pgque-api/partition_keys.sql.
Keyed text fast path. Payload bytes are stored verbatim; routing is identical to
the JSON overload. Grant: pgque_writer. Source:
devel/sql/pgque-api/partition_keys.sql.
Default-type JSON batch send. Equivalent to pgque.send_batch(queue_name, 'default', payloads).
Grant: pgque_writer. Source: devel/sql/pgque-api/send.sql.
Set-based batch send for JSON payloads: validates each element as jsonb, stores its canonical text form, and returns event ids aligned to input order. Do not rely on the numeric ids being monotonically increasing inside one batch; use array position for input/result correlation. Empty arrays return {} without queue lookup; NULL arrays raise payloads must not be null. Non-empty batches still validate queue state once up front: unknown queues raise queue not found: <queue>, and write-disabled queues raise Insert into queue disallowed. NULL elements inside a non-null array are stored as NULL ev_data.
Grant: pgque_writer. Source: devel/sql/pgque-api/send.sql.
select pgque.send_batch('orders', 'order.created',
array['{"id":1}', '{"id":2}']::jsonb[]);
-- Named-argument calls are supported; argument names are part of the API.
select pgque.send_batch(
queue_name := 'orders',
type_name := 'order.created',
payloads := array['{"id":1}', '{"id":2}']::jsonb[]
);Default-type text batch send. Equivalent to pgque.send_batch(queue_name, 'default', payloads).
Grant: pgque_writer. Source: devel/sql/pgque-api/send.sql.
Set-based fast-path batch send for opaque text payloads. Returns event ids aligned to input order. Do not rely on the numeric ids being monotonically increasing inside one batch; use array position for input/result correlation. Empty arrays return {} without queue lookup; NULL arrays raise payloads must not be null. Non-empty batches still validate queue state once up front: unknown queues raise queue not found: <queue>, and write-disabled queues raise Insert into queue disallowed. NULL elements inside a non-null array are stored as NULL ev_data.
Grant: pgque_writer. Source: devel/sql/pgque-api/send.sql.
Not directly callable by API roles. Internal set-based primitive used by send_batch: resolves the queue/table once, allocates ids from the queue sequence, inserts all payloads with one INSERT … SELECT, and returns ids aligned to input order. It is SECURITY DEFINER so the public wrappers can use it, but EXECUTE is revoked from public API roles (including pgque_admin) to keep callers on the stable send_batch surface. The schema owner/superuser can still call it for install/debug work.
Grant: none (internal). Source: devel/sql/pgque-api/send.sql.
Deduplication is an exact match on (queue_name, idem_key) for a bounded TTL
window. It suppresses duplicate producer appends, not consumer redelivery. The
first accepted send returns its new event id with deduped = false; another
call with the same live key returns that original id with deduped = true,
without comparing or replacing the payload. Duplicate calls do not extend the
window. See the producer-idempotency guide for key
design, transaction behavior, and capacity planning.
pgque.send_idem(queue_name text, type_name text, payload jsonb, idem_key text, ttl interval default '1 hour', partition_key text default null) → table(event_id bigint, deduped boolean)
JSON producer-idempotency send. idem_key must be non-null. ttl must be a
positive finite interval. partition_key composes with partition routing when
supplied. Grant: pgque_writer. Source:
devel/sql/pgque-api/send_idem.sql.
pgque.send_idem(queue_name text, type_name text, payload text, idem_key text, ttl interval default '1 hour', partition_key text default null) → table(event_id bigint, deduped boolean)
Text fast path with the same deduplication contract. Untyped string literals
resolve to this overload. Grant: pgque_writer. Source:
devel/sql/pgque-api/send_idem.sql.
Deletes up to 10,000 expired claims for one queue. Returns 1 when the batch
was full and another pass is requested, otherwise 0. send_idem registers
this form as a queue extra-maintenance hook automatically. Grant:
pgque_admin. Source:
devel/sql/pgque-api/send_idem.sql.
Same bounded cleanup across all queues, for direct operator scheduling. Grant:
pgque_admin. Source:
devel/sql/pgque-api/send_idem.sql.
The consume API wraps pgque.next_batch, pgque.get_batch_events, pgque.finish_batch, and pgque.event_retry. Typical loop: receive → process → ack (or nack on failure).
All consume-side functions (receive, ack, nack, subscribe, unsubscribe) are granted to pgque_reader, mirroring upstream PgQ's producer/consumer role split. Apps that both produce and consume must hold both pgque_reader and pgque_writer — pgque_writer does not inherit pgque_reader.
Snapshot rule. pgque.send → pgque.ticker → pgque.receive must each run in its own committed transaction (the ticker's snapshot must be taken after send commits; receive only sees what committed before it). Same for pgque.maint_retry_events → pgque.ticker → pgque.receive. Each call must be its own committed transaction; never wrap producer and consumer calls together in one transaction. See concepts.md#the-snapshot-rule.
Pulls the complete next batch for consumer on queue, or raises an error if it exceeds max_return. A non-null max_return must be >= 1; passing 0 or a negative value raises an error. SQL null disables the explicit ceiling for compatibility; prefer an explicit resource-safe ceiling. Returns an empty set if no batch is available. Each row is a pgque.message composite (see §Message type).
Grant: pgque_reader. Source: devel/sql/pgque-api/receive.sql.
Choose a ceiling explicitly. The SQL default is 100, below the default ticker event-count threshold of 500. Ordinary bursts can therefore exceed the default receive ceiling. Pass an explicit ceiling sized for your expected batches and resource budget; alert on SQLSTATE 54000 and consumer lag. The example value below is illustrative, not a batch-size guarantee.
select * from pgque.receive('orders', 'processor', 1000);Overflow reports SQLSTATE 54000 (program_limit_exceeded). Like other SQL errors, it aborts the enclosing transaction unless recovered through a savepoint.
Complete batch or error. max_return is a safety ceiling, not a page size. Exactly that many events is valid; encountering one more raises an error, with no successful result or consumer advancement from that call. Roll back a failed transaction and retry with a larger ceiling within your resource budget, or explicitly manage the complete batch with pgque.next_batch(), pgque.get_batch_events() and pgque.finish_batch() (the low-level PgQ API). Process every event before calling ack(batch_id), which finishes the entire batch. Do not acknowledge after an overflow error. Repeating receive() with the same ceiling does not paginate or resolve overflow.
ticker_max_count is a tick-trigger threshold, not a hard batch-size cap. Setting max_return to that value cannot guarantee success during bursts. Monitor receive errors and consumer lag so an undersized ceiling does not silently stall processing.
SDK overflow handling. Both ordinary and cooperative receive return a typed
error on batch overflow. High-level consumers stop on this error. The error
includes the configured ceiling, operation, SQLSTATE, and server hint, but not
the actual batch size. Other SQL errors keep each SDK's normal error policy.
SQLSTATE 54000 alone does not identify a receive overflow.
On overflow, do not run handlers or acknowledge the batch. Do not automatically raise the resource ceiling or reset the consumer past the batch. Use the whole-batch recovery procedure above.
SQL and low-level helpers default to 100 when the argument is optional.
High-level consumers default to INT_MAX. This does not bound memory use.
Install the updated SDK separately from the database code. See each client
README for its error type and consumer behavior.
Closes the batch and advances the consumer position. Modern alias for pgque.finish_batch. Returns 1 on success, 0 if the batch was not found.
Grant: pgque_reader. Source: devel/sql/pgque-api/receive.sql.
pgque.nack(batch_id bigint, msg pgque.message, retry_after interval default '60 seconds', reason text default null) → integer
Negative-acknowledges one message. Only msg.msg_id (and the batch_id argument) are honored from the composite — type, payload, retry_count, created_at, and the extra* fields are ignored. nack() re-queries the canonical event from the active batch and uses those server-side values for all decisions and writes.
- If the canonical
ev_retryis below the queue'smax_retries(effective default 5 — seepgque.set_queue_config), re-queues afterretry_after(viapgque.event_retry). - If
ev_retry >= max_retries, routes the canonical event topgque.dead_letter(viapgque.event_dead). This is idempotent: repeated calls for the same terminal message produce exactly one DLQ row (the second call does nothing). - If
msg.msg_idis not present in the active batch — including aNULLmsg_id or a msg_id from a different batch — raisesmsg_id % not found in batch %. Grant:pgque_reader. Source:devel/sql/pgque-api/receive.sql.
perform pgque.nack(msg.batch_id, msg, interval '5 minutes', 'validation failed');Partitioned consumers keep each key on one slot. Events are ordered by event
ID within each snapshot window. A lower ID can appear in a later window if its
producer commits late. This is not global event-ID FIFO or producer commit
order. Different hash slots run in parallel. Every slot is an independent PgQ subscription and must be polled; it
scans the full stream with a server-side hash filter, producing approximately
n times read amplification. Slot leases are transactional rows, so the API
works with transaction-mode poolers. The first-party clients do not yet wrap
this API. Start with the partition-keys guide for the
worker loop, fencing, monitoring, and recovery rules.
Atomically pins n (1–256) and creates all slots 0..n-1 at one shared starting tick.
Repeating a complete setup with the same n is idempotent and does not move
cursors. An existing incomplete setup or a different n raises. Call before
producing any events this consumer must see. Grant: pgque_reader. Source:
devel/sql/pgque-api/partition_keys.sql.
Repairs or explicitly creates one slot after validating the pinned n. This is
not the normal setup path: a late slot begins at the latest tick and cannot
recover already-ticked history. Grant: pgque_reader. Source:
devel/sql/pgque-api/partition_keys.sql.
Removes one engine subscription and lease row. This may leave the logical
consumer incomplete and removes retry/dead-letter state owned by that slot.
Removing the final remaining subscription also removes the pinned-n row.
Grant: pgque_reader. Source:
devel/sql/pgque-api/partition_keys.sql.
Atomically removes every slot, its engine subscription, and the pinned slot
count. This removes retry and dead-letter state owned by those subscriptions.
Drain and acknowledge work before a controlled teardown. Grant: pgque_reader.
Source: devel/sql/pgque-api/partition_keys.sql.
pgque.claim_slot(queue_name text, consumer text, slot int, worker text, ttl interval default '30 seconds') → bigint
Claims a free/expired slot or renews the same worker's lease. Returns the
current fencing epoch on success and null when another live owner holds the
slot or its row is busy. worker must be non-empty and unique per live worker;
ttl must be finite and at least one second. A takeover increments the epoch.
Grant: pgque_reader. Source:
devel/sql/pgque-api/partition_keys.sql.
Clears the lease at a batch boundary. Returns true only for the current owner,
false for a non-owner/unleased slot, and raises if the owner still has an open
batch. Crash recovery uses lease expiry instead. Grant: pgque_reader. Source:
devel/sql/pgque-api/partition_keys.sql.
pgque.receive_partitioned(queue_name text, consumer text, slot int, n int, worker text, max_return int default 100) → setof pgque.message
Validates the pinned n, fences and renews the lease, then returns the current
batch's events whose normalized hashtextextended(partition_key, 0) maps to
slot; null keys map to slot 0. Empty filtered batches are finished
automatically. As with receive, max_return is a complete-batch safety
ceiling, not pagination. Overflow raises SQLSTATE 54000 without returning a
successful partial batch. The ticker threshold is not a hard batch-size cap.
Process the complete successful result before ack_partitioned, or use
receive_page_partitioned and committed ack_page checkpoints for bounded
work.
Grant: pgque_reader. Source:
devel/sql/pgque-api/partition_keys.sql.
pgque.ack_partitioned(queue_name text, consumer text, slot int, n int, worker text, batch_id bigint) → integer
Fences the lease owner and active batch_id, renews the lease when due, and finishes batch_id. Returns 1 when finished and 0 when no batch was open; raises SQLSTATE 55000 if a different batch is active (preventing ABA stale-worker acks). Grant: pgque_reader.
Source: devel/sql/pgque-api/partition_keys.sql.
pgque.nack_partitioned(queue_name text, consumer text, slot int, n int, worker text, msg pgque.message, retry_after interval default '60 seconds', reason text default null) → integer
Lease-fenced per-message retry/DLQ operation for a partitioned batch. Retried
events retain their partition key and return to the same slot. Raises when the
slot has no open batch. Grant: pgque_reader. Source:
devel/sql/pgque-api/partition_keys.sql.
One row for every expected slot, including missing subscriptions. Columns:
| Column | Type | Meaning |
|---|---|---|
queue_name |
text |
Queue name. |
consumer |
text |
Logical partitioned consumer. |
slot |
integer |
Slot number in 0..n-1. |
n |
integer |
Pinned slot count. |
subscribed |
boolean |
Whether the engine subscription exists. |
lease_owner |
text |
Current live owner; null when free or expired. |
lease_until |
timestamptz |
Stored lease expiry, including an expired lease. |
epoch |
bigint |
Monotonic fencing epoch. |
last_tick |
bigint |
Slot cursor; null when unsubscribed. |
pending_events |
bigint |
Pre-filter event-sequence lag; null when unsubscribed. |
pending_events measures the tick event-sequence difference before hash filtering.
It over-counts one slot's routed share by approximately n. Zero means no
measured sequence lag, not no undelivered work. Unticked events and late producer
commits can require later snapshot windows without a new event-sequence advance.
Sustained growth can mean a stalled slot or a live consumer slower than production.
Grant: select to pgque_reader and pgque_admin. Source:
devel/sql/pgque-api/partition_keys.sql.
Experimental. Function names, edge-case behavior, and client API shape may change before this feature is marked stable. Do not use this as the only processing path for critical workloads without idempotent handlers and stale-worker takeover tests.
For a usage walkthrough see the cooperative-consumers recipe; for when to choose it over fan-out see concepts.
Cooperative consumers let several subconsumers share one logical consumer cursor. The main consumer row (sub_role = 'coop_main') owns the group cursor; member rows (sub_role = 'coop_member') own active batches. The feature is bundled in the default SQL install, but downgrade after creating subconsumers is unsupported unless subconsumers are unregistered first.
pgque.register_subconsumer(queue text, consumer text, subconsumer text, convert_normal boolean default false) → integer
Registers subconsumer under logical consumer. Returns 1 for a new registration and 0 when already registered. If consumer already exists as a normal consumer, conversion is refused unless convert_normal = true, and active normal consumers cannot be converted.
Grant: pgque_reader. Source: devel/sql/pgque-api/cooperative_consumers.sql.
pgque.unregister_subconsumer(queue text, consumer text, subconsumer text, batch_handling integer default 0) → integer
Unregisters one subconsumer. Active batches are rejected by default; batch_handling = 1 routes active messages through retry/DLQ policy equivalent to nack() before unregistering. When the last member is removed, the main row returns to sub_role = 'normal'.
Grant: pgque_reader. Source: devel/sql/pgque-api/cooperative_consumers.sql.
pgque.subscribe_subconsumer(...) and pgque.unsubscribe_subconsumer(...) are aliases for the two functions above.
pgque.receive_coop(queue text, consumer text, subconsumer text, max_return int default 100, dead_interval interval default null) → setof pgque.message
Receives messages for one subconsumer. A non-null max_return must be >= 1; SQL null disables the explicit ceiling as in receive(). dead_interval enables stale-batch takeover from another inactive member; takeover allocates a fresh batch_id, so old tokens cannot ack/nack the new owner's state. The cooperative group is a trust boundary: callers allowed to use the same (queue, consumer) can steal stale batches from each other by design, so do not share one cooperative group across mutually untrusted workers.
Auto-registration. If the logical consumer or subconsumer is not yet registered, receive_coop() registers them on the fly (creates the coop_main row on first call, then the coop_member row), so a worker can call receive_coop() cold without a prior register_subconsumer. Use the explicit register_subconsumer(..., convert_normal => true) call only when you need to convert an existing normal consumer into a cooperative main.
Empty tick windows are auto-finished. When the current batch's tick window holds no events, receive_coop() calls finish_batch internally and returns the empty set. Callers polling a quiet queue do not see (and do not need to ack) a batch_id; receive() also auto-finishes empty batches.
The default cooperative ceiling is also 100; pass an explicit burst-sized ceiling rather than assuming the ticker threshold caps the batch.
Complete batch or error. As with receive(), max_return is a safety ceiling, not pagination. An oversized batch raises an error and rolls back allocation or takeover performed by that call. Retry with a sufficient ceiling within your resource budget, process the complete batch, then acknowledge. The ticker threshold does not cap batch size.
Throughput note. Cooperative allocation serializes on a FOR UPDATE of the coop_main subscription row, so many workers polling tiny batches contend on a single hot row. If you scale workers, also tune ticker_max_count and tick cadence so each batch is large enough to amortize the lock.
Grant: pgque_reader. Source: devel/sql/pgque-api/cooperative_consumers.sql.
pgque.next_batch(queue text, consumer text, subconsumer text, dead_interval interval default null) → bigint
Low-level cooperative batch allocation. Prefer receive_coop() unless the client explicitly needs PgQ-style batch primitives.
Grant: pgque_reader. Source: devel/sql/pgque-api/cooperative_consumers.sql.
pgque.next_batch_custom(queue text, consumer text, subconsumer text, min_lag interval, min_count int4, min_interval interval, dead_interval interval default null) → record
Cooperative custom batch allocation. Out columns: batch_id, prev_tick_id, next_tick_id.
Grant: pgque_reader. Source: devel/sql/pgque-api/cooperative_consumers.sql.
Updates a registered subconsumer heartbeat without creating rows. Returns the number of rows touched.
Grant: pgque_reader. Source: devel/sql/pgque-api/cooperative_consumers.sql.
Cooperative-aware inherited functions. pgque.unregister_consumer() refuses to unregister a cooperative main while subconsumers are registered; unregister subconsumers explicitly. Normal pgque.next_batch*() / pgque.receive() raise on cooperative rows in two cases: the named consumer is a coop_main with at least one registered member (the main row is the group cursor, not a per-worker token), or the named consumer is a coop_member row (member rows must go through receive_coop() / cooperative next_batch()). Both cases include a directive in the error message pointing to the cooperative form. pgque.finish_batch() rejects coop_main batches and clears member-owned cooperative batches on ack. Batch ids are bearer tokens, matching inherited PgQ behavior: a caller that learns a valid batch id can finish it, so keep batch ids inside trusted consumer code.
Registers consumer on queue. Modern alias for pgque.register_consumer. Returns 1 on new registration, 0 if already registered.
Grant: pgque_reader. Source: devel/sql/pgque-api/send.sql (despite the file name, the grant is pgque_reader — subscription management is a consumer-side operation; the file historically co-locates produce wrappers and subscription wrappers).
Removes the consumer (and its retry-queue entries) from queue. Modern alias for pgque.unregister_consumer.
Grant: pgque_reader. Source: devel/sql/pgque-api/send.sql (see note above).
Creates a queue with default settings (3 rotation tables, built-in ticker). Returns 1 if created, 0 if a queue with that name already exists. Queue names are limited to 57 bytes (UTF-8); the pgque_<name> LISTEN/NOTIFY channel must fit within Postgres's 63-byte identifier limit.
Grant: pgque_admin. Source: devel/sql/pgque.sql.
Drops queue. Fails if consumers are still attached.
Grant: pgque_admin. Source: devel/sql/pgque.sql.
Drops queue. In the default frozen installer, force = true unregisters the
attached consumers before dropping the queue. The development installer instead
treats force-drop as administrative destruction: it deletes subscriptions and
their page checkpoints directly, without acknowledging or unregistering them.
Its slot and subscription locks use NOWAIT, for ordinary and paged consumers;
any locked row aborts the whole operation with SQLSTATE 40001 and no changes
commit. Consumer identities used by another queue are retained. Orphan cleanup
skips locked identities and rechecks subscriptions after locking each candidate.
At REPEATABLE READ or SERIALIZABLE, a concurrent registration can require a
fresh snapshot; this also aborts with 40001, without partial queue removal.
Retry the whole transaction. Pause consumers when reliable removal of a busy
queue is required.
Grant: pgque_admin. Sources: devel/sql/pgque.sql
and devel/sql/pgque.sql.
Sets one queue parameter. Accepted param values (without the queue_ prefix): ticker_max_count, ticker_max_lag, ticker_idle_period, ticker_paused, rotation_period, external_ticker, max_retries.
Grant: pgque_admin. Source: devel/sql/pgque.sql (extended in devel/sql/pgque-additions/queue_max_retries.sql).
Observable behavior: numeric/interval settings are range-checked (max_retries >= 0; ticker counts/lags/idle/rotation periods must be positive). Passing SQL NULL resets the column to its schema default.
Defaults per parameter:
param |
Column | Default | Controls |
|---|---|---|---|
ticker_max_count |
queue_ticker_max_count |
500 |
event-count threshold for requesting a tick; not a batch-size cap |
ticker_max_lag |
queue_ticker_max_lag |
'3 seconds' |
max event age before a tick |
ticker_idle_period |
queue_ticker_idle_period |
'1 minute' |
tick cadence when idle |
ticker_paused |
queue_ticker_paused |
false |
pause ticking on this queue |
rotation_period |
queue_rotation_period |
'2 hours' |
table rotation period |
external_ticker |
queue_external_ticker |
false |
ticks come from an external source |
max_retries |
queue_max_retries |
NULL → effective 5 |
retry cap before the dead-letter queue |
The queue_max_retries column default is SQL NULL; nack() applies coalesce(queue_max_retries, 5), so the effective default is 5 retries before a message is dead-lettered. The global tick rate is separate — see pgque.set_tick_period_ms.
select pgque.set_queue_config('orders', 'max_retries', '10');Functions in this section are deny-by-default: the schema-wide blanket revoke execute … from public in devel/sql/pgque-additions/roles.sql strips PUBLIC, and only pgque_admin retains execute on all functions. Grant explicitly to additional roles if your policy needs broader access. uninstall() is doubly locked down — also explicitly revoked from pgque_admin — so only the schema/install owner (typically a superuser) can run it.
Schedules four pg_cron jobs in the current database: pgque_ticker (every 1 s), pgque_retry_events (every 30 s), pgque_maint (every 30 s), and pgque_rotate_step2 (every 10 s). Requires the pg_cron extension — errors if missing. Idempotent: calls stop() first.
The pgque_ticker job calls CALL pgque.ticker_loop() (not SELECT pgque.ticker()). ticker_loop is the sub-second driver: pg_cron's minimum schedule is 1 s, but the procedure internally re-ticks every pgque.config.tick_period_ms (default 100 ms = 10 ticks/sec) and commits between iterations. To change the rate, call pgque.set_tick_period_ms(ms) — no need to call start() again.
Grant: pgque_admin. Source: devel/sql/pgque-additions/lifecycle.sql.
Sub-second tick driver. Runs inside one pg_cron slot (1-second cadence) and re-invokes pgque.ticker() every pgque.config.tick_period_ms ms, committing between iterations so each tick gets its own transaction. Defined as a PROCEDURE (not a function) because Postgres only allows mid-flight COMMIT inside procedures — and forbids combining COMMIT with a SET clause, which is why the body is fully schema-qualified rather than pinning search_path.
Not normally called by hand; pgque.start() schedules it on pg_cron. Use select pgque.set_tick_period_ms(ms) to change cadence, or call pgque.ticker() directly to force a single tick out-of-band.
Grant: pgque_admin. Source: devel/sql/pgque-additions/lifecycle.sql.
Sets pgque.config.tick_period_ms. Default is 100 ms (10 ticks/sec). Allowed values are exact divisors of 1000 in the 1..1000 ms range. Returns the value that was set; raises if out of range, non-divisor, or NULL. Effective on the next pg_cron slot (≤1 s) without rescheduling.
select pgque.set_tick_period_ms(50); -- 20 ticks/sec
select pgque.set_tick_period_ms(1000); -- 1 tick/sec (the pg_cron floor; pgqd-compatible)Trade-offs at higher rates: more WAL per second, more metadata-table churn, more NOTIFY traffic. Inactive queues are cheap: if no events are coming, most ticker calls return NULL and PgQue backs off toward ticker_idle_period (default 1 minute). See latency-and-tuning.md for the rate/latency trade-off.
Grant: pgque_admin. Source: devel/sql/pgque-additions/lifecycle.sql.
Unschedules the pg_cron jobs set up by start() and clears the stored job IDs. Safe to call if pg_cron is absent.
Grant: pgque_admin. Source: devel/sql/pgque-additions/lifecycle.sql.
Returns a diagnostic report with one row per component: Postgres version, PgQue version, ticker/maintenance job status, queue count, and consumer count.
Grant: pgque_admin. Source: devel/sql/pgque-additions/lifecycle.sql.
select * from pgque.status();Returns the installed PgQue version string. Granted to pgque_reader (the only lifecycle function that is) so consumers can self-report the version.
Grant: pgque_reader. Source: devel/sql/pgque.sql.
Runs one maintenance cycle: rotation step 1 plus any queue extra-maint hooks registered via pgque.queue_extra_maint. Rotation step 2 is intentionally skipped (it must run in its own transaction and is scheduled separately by start()); retry-queue processing is not performed here — call pgque.maint_retry_events() as a separate scheduled job. Returns the total number of operations performed.
Grant: pgque_admin. Source: devel/sql/pgque-api/maint.sql.
Moves due rows from pgque.retry_queue back into queue event tables so they appear in the next tick. Must be called periodically when using nack() with retry — pgque.start() schedules it as pgque_retry_events every 30 s. When driving the scheduler manually, call this alongside pgque.maint(). The re-inserted rows carry pg_current_xact_id() as their ev_txid, so the subsequent pgque.ticker call must run in a separate transaction — see the snapshot rule.
select pgque.maint_retry_events(); -- every 30 seconds, for nack/retry redelivery
select pgque.maint(); -- every 30 seconds, for rotationGrant: pgque_admin. Source: devel/sql/pgque.sql.
Issues ticks for all unpaused, non-external queues. Returns the number of queues ticked. Each call must run in its own transaction (it records a pg_snapshot for batch visibility, and the snapshot must be committed before the next tick records its own).
Under pg_cron, this is invoked from pgque.ticker_loop() at the configured tick_period_ms cadence. When driving the scheduler manually, loop this at your target rate (default in PgQue's pg_cron path: every 100 ms).
Grant: pgque_admin. Source: devel/sql/pgque.sql.
Checks whether a tick is due for queue and inserts one if so. Returns the tick id (or NULL if no tick was created).
Grant: pgque_admin. Source: devel/sql/pgque.sql.
Note: a 4-argument
ticker(queue, tick_id, timestamp, event_seq)overload exists for queues configured withexternal_ticker = true(pushing ticks from an external clock source). External ticks must be monotonic:tick_idmust increase, andevent_seqmust not move backwards.
Forces the next pgque.ticker() call to materialize a tick for queue without waiting for the ticker_max_count or ticker_max_lag thresholds. Bumps queue_event_seq by ticker_max_count * 2 + 1000 to simulate a burst of events. Does not insert a tick itself — call pgque.ticker() (or pgque.ticker(queue)) afterwards to materialize the tick. Returns the current last tick id (from the most recent existing tick, not a new one). Useful in tests and demos; not for production hot paths. Canonical idiom:
select pgque.force_next_tick('orders');
select pgque.ticker();Grant: pgque_admin. Source: devel/sql/pgque-additions/tick_helpers.sql.
Alias for pgque.force_next_tick. Retained for compatibility with upstream PgQ (the historical name); identical behavior. The name is misleading — the function does not insert a tick by itself; it only bumps the event sequence so the next pgque.ticker() call inserts one. Raises if the queue is missing, ticker-paused, or configured for an external ticker. Prefer force_next_tick in new code.
Grant: pgque_admin. Source: devel/sql/pgque.sql.
The
force_next_tick→ticker→receivechain (or legacyforce_tickalias) must run across separate transactions for the consumer to see the events you just sent. See the snapshot rule.
Calls stop() (if pg_cron is present) and then drop schema pgque cascade. Roles (pgque_reader, pgque_writer, pgque_admin) are not dropped and must be removed manually if desired. execute is revoked from both pgque_admin (explicit) and PUBLIC (via the schema-wide blanket revoke), so only the schema/install owner (typically a superuser) can run it.
Grant: superuser / schema owner only (revoked from both pgque_admin and PUBLIC). Source: devel/sql/pgque-additions/lifecycle.sql.
All observability functions here are granted to pgque_reader. They flow up to pgque_admin (which is a member of both pgque_reader and pgque_writer) but do not flow to pgque_writer — that role is producer-only and does not inherit reader privileges. Apps that produce + consume must hold both roles.
Returns one row per queue with ticker config and live stats. Grant: pgque_reader. Source: devel/sql/pgque.sql.
| Out column | Type |
|---|---|
queue_name |
text |
queue_ntables |
integer |
queue_cur_table |
integer |
queue_rotation_period |
interval |
queue_switch_time |
timestamptz |
queue_external_ticker |
boolean |
queue_ticker_paused |
boolean |
queue_ticker_max_count |
integer |
queue_ticker_max_lag |
interval |
queue_ticker_idle_period |
interval |
ticker_lag |
interval |
ev_per_sec |
float8 |
ev_new |
bigint |
last_tick_id |
bigint |
Same columns as the 0-arg form, filtered to one queue. Grant: pgque_reader. Source: devel/sql/pgque.sql.
Returns one row per consumer across all queues. Grant: pgque_reader. Source: devel/sql/pgque.sql.
| Out column | Type |
|---|---|
queue_name |
text |
consumer_name |
text |
lag |
interval |
last_seen |
interval |
last_tick |
bigint |
current_batch |
bigint |
next_tick |
bigint |
pending_events |
bigint |
Same columns, filtered to one queue. Grant: pgque_reader. Source: devel/sql/pgque.sql.
Same columns, filtered to one (queue, consumer) pair. Either argument may be NULL to widen the selection. Grant: pgque_reader. Source: devel/sql/pgque.sql.
Inspects an active batch. Grant: pgque_reader. Source: devel/sql/pgque.sql.
| Out column | Type |
|---|---|
queue_name |
text |
consumer_name |
text |
batch_start |
timestamptz |
batch_end |
timestamptz |
prev_tick_id |
bigint |
tick_id |
bigint |
lag |
interval |
seq_start |
bigint |
seq_end |
bigint |
PgQ has a retry queue but no dead letter queue; PgQue adds one. Messages land here when nack() is called and retry_count >= max_retries.
| Column | Type | Nullable |
|---|---|---|
dl_id |
bigserial |
PK |
dl_queue_id |
int4 |
no (FK → pgque.queue, on delete cascade) |
dl_consumer_id |
int4 |
no (FK → pgque.consumer, on delete cascade) |
dl_time |
timestamptz |
no (default now()) |
dl_reason |
text |
yes |
ev_id |
bigint |
no |
ev_time |
timestamptz |
no |
ev_txid |
xid8 |
yes |
ev_retry |
int4 |
yes |
ev_type |
text |
yes |
ev_data |
text |
yes |
ev_extra1..4 |
text |
yes |
Grant: select to pgque_reader, all to pgque_admin.
pgque.event_dead(batch_id bigint, event_id bigint, reason text, ev_time timestamptz, ev_txid xid8, ev_retry int4, ev_type text, ev_data text, ev_extra1 text default null, ev_extra2 text default null, ev_extra3 text default null, ev_extra4 text default null) → integer
Inserts one row into pgque.dead_letter. Called internally by pgque.nack() when retries are exhausted — direct calls are rarely needed.
Grant: pgque_admin. Source: devel/sql/pgque-additions/dlq.sql.
Returns the most recent dead-letter rows for queue, newest first.
Grant: pgque_reader. Source: devel/sql/pgque-additions/dlq.sql.
Re-inserts one dead-letter entry into its original queue and deletes it from pgque.dead_letter. Returns the new event id.
Grant: pgque_writer (replay is a produce action — it calls insert_event to put the event back on the queue). Source: devel/sql/pgque-additions/dlq.sql.
Replays every dead-letter entry for queue. Per-event failures are isolated (one bad row does not abort the rest), surfaced via raise warning, and counted in failed; first_error carries the first failure's dl_id and sqlerrm for diagnostics. This function returns a record of (replayed bigint, failed bigint, first_error text) — a breaking change from the bare integer it returned in the previous release. Callers that read it as a single integer must be updated.
Read the result with the columns by name:
select replayed, failed, first_error from pgque.dlq_replay_all('orders');Grant: pgque_writer (replay is a produce action — it calls insert_event for each replayed entry). Source: devel/sql/pgque-additions/dlq.sql.
Deletes dead-letter rows older than older_than for queue. Returns the row count deleted. Destructive — audit the entries first.
Grant: pgque_admin. Source: devel/sql/pgque-additions/dlq.sql.
Available but most users should prefer the modern API above. These are the raw PgQ primitives — the modern API wraps them 1:1.
Inserts one event with no extra columns. Returns the event id.
Grant: pgque_writer. Source: devel/sql/pgque.sql.
pgque.insert_event(queue_name text, ev_type text, ev_data text, ev_extra1 text, ev_extra2 text, ev_extra3 text, ev_extra4 text) → bigint
Inserts one event with the four ev_extra* columns populated.
Grant: pgque_writer. Source: devel/sql/pgque.sql.
Registers consumer_id on queue_name, starting from the most recent tick. Returns 1 for new, 0 if already registered.
Grant: pgque_reader. Source: devel/sql/pgque.sql.
Registers a consumer at a specific historical tick id. Raises if the tick is not found.
Grant: pgque_reader. Source: devel/sql/pgque.sql.
Removes the subscription and retry-queue entries owned by this consumer on queue_name. Returns the number of subscriptions removed. Cooperative-aware: calling this on a coop_main with registered subconsumers raises; unregister subconsumers explicitly.
Grant: pgque_reader. Source: devel/sql/pgque.sql.
Activates the next batch for this consumer and returns its id, or NULL if no events are ready.
Grant: pgque_reader. Source: devel/sql/pgque.sql.
Same as next_batch but returns tick bounds alongside batch_id. Out columns: batch_id, cur_tick_id, prev_tick_id, cur_tick_time, prev_tick_time, cur_tick_event_seq, prev_tick_event_seq.
Grant: pgque_reader. Source: devel/sql/pgque.sql.
pgque.next_batch_custom(queue_name text, consumer_name text, min_lag interval, min_count int4, min_interval interval) → record
Activates the next batch with custom size/age constraints. Same out columns as next_batch_info. Cooperative-aware: this 5-arg legacy form raises if the named consumer is a coop_main with at least one registered member, or if it is a coop_member row — in both cases the error message directs the caller to the 7-arg cooperative form. Normal consumers and coop_main rows with no members pass through.
Grant: pgque_reader. Source: devel/sql/pgque.sql.
Streams the events in a batch. Out columns: ev_id bigint, ev_time timestamptz, ev_txid bigint, ev_retry int4, ev_type text, ev_data text, ev_extra1..4 text. Note: ev_txid is exposed here as bigint (the legacy PgQ signature), even though it is stored on the event tables as xid8 — the value is the same transaction id, narrowed for the function result.
Grant: pgque_reader. Source: devel/sql/pgque.sql.
Declares a server-side cursor over the batch and returns the first quick_limit events. Remaining events can be fetched with fetch … from <cursor_name>.
Grant: pgque_admin only. Source: devel/sql/pgque.sql.
pgque.get_batch_cursor(batch_id bigint, cursor_name text, quick_limit int4, extra_where text) → setof record
Same as above with an additional where filter applied inside the cursor.
Grant: pgque_admin only. Source: devel/sql/pgque.sql.
Security:
extra_whereis a trusted SQL fragment, not a parameter — it is concatenated verbatim into the cursor'sselect. A caller that controlsextra_wherecan inject arbitrary predicates (includingUNION ALL) and forge rows in the returned stream. This behavior is inherited from upstream PgQ and is gated behindpgque_adminfor that reason. Never pass user-controlled text asextra_where, even from admin code paths; if you need filtering driven by application input, fetch the batch withpgque.get_batch_events()and filter in the application or in a separate parameterized query.
Closes the batch and advances the subscription's last_tick. Returns 1 on success, 0 with a warning if the batch was not found. Cooperative-aware: coop_member batches clear the member cursor; coop_main batches are rejected.
Grant: pgque_reader. Source: devel/sql/pgque.sql.
Puts one event back onto the retry queue with an absolute re-delivery time. Returns 1 on success, 0 if already queued for retry.
Grant: pgque_reader. Source: devel/sql/pgque.sql.
Same as above but takes a relative delay in seconds.
Grant: pgque_reader. Source: devel/sql/pgque.sql.
Re-queues every event in the batch after retry_seconds. Returns the number of events enqueued for retry.
Grant: pgque_admin. Source: devel/sql/pgque.sql.
Table triggers that enqueue a PgQue event for every INSERT / UPDATE / DELETE. All three return trigger; attach them via CREATE TRIGGER … EXECUTE PROCEDURE pgque.<name>('queue_name', …). Grant: pgque_admin. Source: devel/sql/pgque.sql (inherited from PgQ).
Emits row data as JSON (ev_data is a JSON blob, ev_extra1 is the fully-qualified table name). Supports optional trigger args: SKIP, backup, ignore=…, pkey=…, when=…, ev_type=…, ev_extra1..4=….
Emits row data as URL-encoded key/value pairs (key1=v1&key2=v2). Useful for legacy pipelines that already consume logutriga.
Emits row data as ready-to-apply SQL (INSERT … VALUES …, UPDATE … SET … WHERE …, DELETE FROM … WHERE …) in ev_data.
Returned by pgque.receive() and consumed by pgque.nack().
| Field | Type | Notes |
|---|---|---|
msg_id |
bigint |
event id (ev_id) |
batch_id |
bigint |
batch containing this message |
type |
text |
event type (ev_type); may be null |
payload |
text |
event data (ev_data); cast to jsonb if needed |
retry_count |
int4 |
NULL on first delivery, incremented on retry |
created_at |
timestamptz |
original ev_time |
extra1 |
text |
ev_extra1; may be null |
extra2 |
text |
ev_extra2; may be null |
extra3 |
text |
ev_extra3; may be null |
extra4 |
text |
ev_extra4; may be null |
Three roles. pgque_reader (consume) and pgque_writer (produce) are siblings, not parent/child — this mirrors upstream PgQ's role model and prevents a producer-only role from acking another consumer's batch. pgque_admin is a member of both. Source: devel/sql/pgque-additions/roles.sql (plus colocated grants in devel/sql/pgque-api/*.sql and devel/sql/pgque-additions/dlq.sql).
Apps that produce and consume must be granted both pgque_reader and pgque_writer explicitly.
PgQue roles are coarse database-level roles. They are intended for trusted applications and operators sharing the same database, not as per-queue or per-tenant isolation for mutually untrusted applications.
What this means in practice:
pgque_readergetsselecton the public engine and status tables in thepgqueschema (internal idempotency and partition lease tables are revoked; usepartition_slot_status). It can callreceive,ack,nack, and the partitioned consume API on any queue with any consumer name. A reader granted for queue A can callpgque.ack(batch_id)on a batch opened by a consumer on queue B.pgque_writercan produce to any queue (pgque.send,pgque.send_idem,pgque.send_batch,pgque.insert_event).- There is no per-queue ACL and no per-tenant isolation built into PgQue. Queue names and consumer names are plain strings — any role with the matching grant can interact with them.
This is intentional, by design. The batch-ID-based primitives (ack, nack, event_retry) operate on IDs and do not enforce ownership; the producer/consumer split closes only the producer-vs-consumer boundary, not the consumer-vs-consumer one.
Recommended isolation patterns if you need mutually untrusted tenants in one database:
- Run separate PgQue installs in separate schemas per tenant (not yet officially supported — track the roadmap).
- Use separate databases per tenant and connect each tenant's application to its own database.
- Wrap the PgQue API in app-owned stored functions that enforce tenant ownership before delegating to
pgque.*, and grant only those wrapper functions to tenant roles.
| Role | Functions granted directly |
|---|---|
pgque_reader |
Read-only info functions and public tables/views; normal consume API; bounded page API (receive_page*, ack_page, renew_page); partition setup, lease, consume API and partition_slot_status; consumer primitives; experimental cooperative API. Internal partition/lease tables and pgque.idem are not directly readable. |
pgque_writer |
insert_event overloads, all send / send_idem / send_batch overloads, dlq_replay, and dlq_replay_all. Does not inherit pgque_reader — a producer-only role cannot ack, finish, or inspect consumer batches. |
pgque_admin |
Member of both reader and writer, plus lifecycle, maintenance including maint_idem, DDL, DLQ administration, schema/table/sequence administration, and the administration helpers granted by the installer. Private paging, partition, and retry helpers are not public entry points. uninstall(), insert_event_bulk(), and direct access to pgque.idem are revoked. |
This table describes the development installer. Frozen release installers can have different grants.
pgque.uninstall() and pgque.insert_event_bulk() are revoked from pgque_admin and PUBLIC. Only the install owner can run them directly. Use send_batch() instead of insert_event_bulk().
The installer also revokes direct execution of private paging, partition, and retry helpers from application roles, including pgque_admin. These include _next_batch_custom and _next_batch_coop. Use the public consume and page APIs. A schema-wide grant earlier in the installer does not override these later revocations.
The administration API includes start, stop, status, maint, maint_retry_events, ticker, force_next_tick (and its alias force_tick), create_queue, drop_queue, and set_queue_config. Grant these explicitly to additional roles if your policy requires it. To check a specific installed function, use has_function_privilege(role, function_signature, 'EXECUTE').
These objects are not part of devel/sql/pgque.sql. Load them explicitly with \i devel/sql/experimental/<file>.sql. API and stability are not guaranteed — signatures, semantics, and grants may change before promotion into the default install.
Schedules delayed delivery. If deliver_at <= now() behaves like insert_event and returns the queue event id. Otherwise inserts into pgque.delayed_events and returns the scheduled-entry id (not a queue event id).
Moves due rows from pgque.delayed_events into their target queues. Intended to be called from pgque.maint() (the experimental file overrides maint() to chain this in).
All functions below are security definer with pinned search_path and are installed without explicit grants.
pgque.queue_stats() → table(queue_name text, queue_id int4, depth bigint, oldest_msg_age interval, consumers int4, events_per_sec numeric, cur_table int4, rotation_age interval, rotation_period interval, ticker_paused boolean, last_tick_time timestamptz, last_tick_id bigint, dlq_count bigint)
pgque.consumer_stats() → table(queue_name text, consumer_name text, lag interval, pending_events bigint, last_batch_start timestamptz, batch_active boolean, batch_id bigint)
Operational checks (stuck ticker, rotation lag, DLQ growth).
pgque.otel_metrics() → table(metric_name text, metric_type text, metric_value numeric, labels jsonb)
OTel-compatible metric export rows.
pgque.stuck_consumers(threshold interval default '1 hour') → table(queue_name text, consumer_name text, lag interval, last_active timestamptz)
pgque.in_flight(queue text) → table(consumer_name text, batch_id bigint, batch_age interval, estimated_events bigint)
pgque.throughput(queue text, period interval, bucket_size interval) → table(bucket_start timestamptz, events bigint, events_per_sec numeric)
pgque.error_rate(queue text, period interval, bucket_size interval) → table(bucket_start timestamptz, retries bigint, dead_letters bigint)
Sugar overload: calls create_queue(queue) then applies each key in options via set_queue_config. Recognized keys include max_retries, rotation_period, ticker_max_count, ticker_max_lag, ticker_idle_period, ticker_paused. The 57-byte queue name limit applies here too (see the 1-arg overload above).
Shortcut for set_queue_config(queue, 'ticker_paused', 'true').
Shortcut for set_queue_config(queue, 'ticker_paused', 'false').