Consuming messages
Consumers receive messages from a queue and acknowledge completed work. Receiving a message reserves its delivery for a visibility timeout; acknowledgement completes that queue's delivery. If it remains unacknowledged and its timeout expires, it can be delivered again, subject to the queue's attempt limit.
All consumers of the same queue share its deliveries. Consumers of different queues have independent deliveries, even when those queues subscribe to the same topic. Choose the queue's identity and lifetime in Durable queues or Exclusive queues.
All three SDKs provide two consumer APIs: a handler consumer, which invokes your callback for each delivery, and a stream consumer, which lets your code receive and settle deliveries in its own loop. Both use the same queue and delivery guarantees.
Handler consumers
A handler consumer calls your function for each received message and settles the delivery when the function completes. Use it when each message can be handled by a callback and the SDK should manage handler concurrency and automatic acknowledgement.
Create the events topic and jobs queue using the Durable queues guide. The examples below are worker functions for the SDK 0.4.0 connections created in the Quick start, with SQL 0.1.1 installed. Keep that program's connection setup and cleanup, and replace its queue declaration, publishing, and receiving steps with the worker call. In Go, return runWorker(conn) after the deferred connection close. In Rust, replace the run function's body with run_worker(conn).await. In TypeScript, call await runWorker(client) inside the existing try block.
Each worker runs for 30 seconds and then returns so the application can close its connection. The handler logs the job; replace that body with your application work. The timer keeps the example self-contained. A service would instead remain active until its lifecycle code requests graceful shutdown.
- Go
- Rust
- TypeScript
func runWorker(conn *postgremq.Connection) error {
consumer, err := conn.ConsumeHandler("jobs",
func(ctx context.Context, message *postgremq.Message) {
if ctx.Err() != nil {
return // The handler's cancellation rule returns unfinished work.
}
fmt.Printf("Message %d: %s\n", message.ID, message.Payload)
// Returning normally acknowledges while the context is still live.
},
postgremq.WithTopic("events"),
postgremq.WithBatchSize(10),
postgremq.WithVT(30),
postgremq.WithCheckTimeout(5*time.Second),
postgremq.WithMaxInFlight(4),
)
if err != nil {
return err
}
closed := consumer.NotifyClose(make(chan error, 1))
select {
case err := <-closed:
return fmt.Errorf("worker stopped unexpectedly: %v", err)
case <-time.After(30 * time.Second):
return nil
}
}
Use the imports from the Go quick start, removing encoding/json from the worker program. The worker and its connection setup need context, fmt, log, os, time, pgxpool, and postgremq. Keep encoding/json in the separate publishing program below. WithTopic supplies the topic when the queue was declared through SQL or another connection.
async fn run_worker(conn: &postgremq::Connection) -> Result<(), Box<dyn std::error::Error>> {
let consumer = conn.consume_with_handler(
"jobs",
postgremq::ConsumeOptions::default()
.batch_size(std::num::NonZeroU32::new(10).unwrap())
.vt_secs(std::num::NonZeroU32::new(30).unwrap())
.check_timeout(std::time::Duration::from_secs(5))
.auto_extend(true),
std::num::NonZeroUsize::new(4),
|message: postgremq::Delivery| async move {
if message.stopped().is_cancelled() {
return Ok(()); // Cancellation makes the handler return unfinished work.
}
println!("Message {}: {}", message.message_id(), message.payload());
Ok(()) // Automatically acknowledged while the stop signal is still live.
},
).await?;
tokio::select! {
reason = consumer.closed() => {
Err(format!("worker stopped unexpectedly: {reason:?}").into())
}
_ = tokio::time::sleep(std::time::Duration::from_secs(30)) => Ok(()),
}
}
Rust discovers the queue's topic when starting the consumer.
async function runWorker(client: Awaited<ReturnType<typeof connect>>) {
const consumer = client.consumeHandler('jobs', async (message) => {
if (message.signal.aborted) {
return; // Cancellation makes the handler return unfinished work.
}
console.log(`Message ${message.id}:`, message.payload);
// Returning normally acknowledges while the signal is still live.
}, {
topic: 'events',
batchSize: 10,
maxInFlight: 4,
visibilityTimeoutSec: 30,
pollingIntervalMs: 5_000,
autoExtension: { enabled: true },
});
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(resolve, 30_000);
consumer.onClose((error) => {
clearTimeout(timer);
reject(error ?? new Error('Worker stopped unexpectedly'));
});
});
}
The topic option supplies the topic when the queue was declared through SQL or another connection.
Run two copies of your chosen worker program in separate terminals, using the same DATABASE_URL. Use the Submit jobs examples to publish while the workers are running, within their 30-second demonstration window. Both can process work, although PostgreMQ does not promise an even or round-robin split. A fast worker may receive most of a small batch.
Stream consumers
A stream consumer gives your application a sequence of deliveries: a Go channel, a Rust consumer with next(), or a TypeScript async iterator. Your code decides when to read the next message, when to acknowledge or return the current one, and whether to dispatch work concurrently.
Use this API when consumption needs to fit an existing processing loop or when the application should control settlement explicitly. Receiving the next item, finishing the loop body, or dropping a reference does not acknowledge a delivery. Unsettled work remains subject to visibility timeout and recovery rules.
The following functions consume the same jobs queue. They process one delivery at a time and explicitly acknowledge after printing it. Replace the print statement with application work and acknowledge only after that work succeeds.
- Go
- Rust
- TypeScript
func runStream(conn *postgremq.Connection) error {
consumer, err := conn.Consume("jobs",
postgremq.WithTopic("events"), postgremq.WithBatchSize(1))
if err != nil {
return err
}
closed := consumer.NotifyClose(make(chan error, 1))
for message := range consumer.Messages() {
fmt.Printf("Message %d: %s\n", message.ID, message.Payload)
settleCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
err := message.Ack(settleCtx)
cancel()
if err != nil {
return err
}
}
return <-closed // Nil on normal closure; the error on fatal closure.
}
async fn run_stream(conn: &postgremq::Connection) -> Result<(), Box<dyn std::error::Error>> {
let mut consumer = conn.consume(
"jobs",
postgremq::ConsumeOptions::default().batch_size(std::num::NonZeroU32::MIN),
).await?;
while let Some(delivery) = consumer.next().await {
let message = delivery?;
println!("Message {}: {}", message.message_id(), message.payload());
message.ack().await?;
}
Ok(())
}
async function runStream(client: Awaited<ReturnType<typeof connect>>) {
const consumer = client.consume('jobs', { topic: 'events', batchSize: 1 });
const closed = new Promise<Error | undefined>((resolve) => {
consumer.onClose(resolve);
});
for await (const message of consumer.messages()) {
console.log(`Message ${message.id}:`, message.payload);
await message.ack();
}
const error = await closed;
if (error) throw error;
}
Unlike the timed handler demonstration, these loops run until the consumer closes or an operation fails. Application lifecycle code should close the connection from outside the loop and await the loop's completion. If processing or settlement fails and the loop returns early, the caller must still close the connection. See Graceful shutdown for sequencing and deadlines.
For work that may fail, explicitly return the delivery with nack when another attempt is appropriate. Stream consumers do not infer success or failure from your application's return values or exceptions. They still provide automatic visibility extension by default and expose the same cancellation signals as handler deliveries.
Reading sequentially, as above, keeps application processing sequential. A stream consumer can still prefetch. If the loop launches tasks or goroutines instead of awaiting each operation, the application must bound that concurrency and account for every outstanding delivery; the handler-specific concurrency setting does not govern that work.
Choose between the two APIs
| Responsibility | Handler consumer | Stream consumer |
|---|---|---|
| Receive messages | SDK invokes the callback. | Application reads the channel, stream, or iterator. |
| Control active processing | Configure the SDK's handler concurrency limit. | Process sequentially or implement a bounded worker pool. |
| Confirm success | Normal completion can acknowledge automatically; explicit acknowledgement is also available. | Explicitly acknowledge each completed delivery. |
| Return failed work | SDK applies the handler result and cancellation rules; Go business failures require an explicit Nack. | Application explicitly returns work for retry. |
| Extend visibility | Automatic by default; configurable. | Automatic by default; configurable. |
| Respond to cancellation | Callback cooperates with the delivery's cancellation signal. | Processing code cooperates with the same signal. |
Choosing a stream consumer does not change delivery guarantees or give the application a separate copy of each message. Handler and stream consumers using the same queue compete for its deliveries. Either can use Durable or Exclusive queues and FIFO message groups.
Consumer options
Fetch size, handler concurrency, and visibility timeout control different things. Set them explicitly for a worker whose resource use needs to be predictable.
| Option | What it controls | Application consequence |
|---|---|---|
| Fetch batch size | Maximum deliveries claimed in one fetch. | A larger batch reduces fetch calls but can reserve more work ahead of processing. A fetch may return fewer messages; it does not wait for a full batch. |
| Handler concurrency | Maximum callbacks running at once per handler consumer. | Bounds active application work. It does not cap every delivery already fetched or buffered. |
| Visibility timeout | Initial period for which a claimed delivery is reserved. | A longer timeout tolerates longer interruptions but delays recovery after a consumer disappears. |
| Automatic extension | Renewal of active deliveries' visibility timeouts. | Allows processing beyond the initial timeout; it does not impose a maximum handler duration. |
| Extension threshold | Fraction of the timeout that elapses before renewal is attempted. | Earlier renewal leaves more room for database delays, at the cost of more renewal traffic. |
| Poll interval | Fallback checks when no notification wakes the consumer. | Shorter intervals reduce fallback latency and increase idle database queries. This is not a processing deadline. |
The SDK defaults are a fetch batch of 10, a 30-second visibility timeout, automatic extension enabled, and renewal around the halfway point. Handler concurrency is unlimited unless configured. Default fallback polling differs: 10 seconds in Go and Rust, 1 second in TypeScript.
The handler example above selects a batch of 10, four concurrent handlers, a 30-second visibility timeout, and a five-second fallback poll interval. Automatic extension remains enabled. Four concurrent handlers does not mean a batch is processed atomically: each delivery is acknowledged or retried independently.
Submit jobs
While the workers are running, publish ten jobs:
- Go
- Rust
- TypeScript
- SQL
for n := 1; n <= 10; n++ {
payload, err := json.Marshal(map[string]int{"number": n})
if err != nil { return err }
if _, err := conn.Publish(ctx, "events", payload); err != nil {
return err
}
}
for n in 1..=10 {
conn.publish("events", &postgremq::serde_json::json!({"number": n}),
postgremq::PublishOptions::default(),
).await?;
}
for (let n = 1; n <= 10; n++) {
await client.publish('events', { number: n });
}
SELECT postgremq.publish_message('events', jsonb_build_object('number', n))
FROM generate_series(1, 10) AS n;
The worker terminals print the received jobs. You can submit the same kind of message from an application with any of the publishing APIs.
Once processing finishes, inspect the queue:
- Go
- Rust
- TypeScript
- SQL
queue := "jobs"
stats, err := conn.GetQueueStatistics(ctx, &queue)
if err != nil { return err }
fmt.Printf("pending=%d processing=%d completed=%d\n",
stats.PendingCount, stats.ProcessingCount, stats.CompletedCount)
let stats = conn.queue_statistics(Some("jobs")).await?;
println!("pending={} processing={} completed={}",
stats.pending, stats.processing, stats.completed);
const stats = await client.getQueueStatistics('jobs');
console.log(`pending=${stats.pendingCount} processing=${stats.processingCount} completed=${stats.completedCount}`);
SELECT * FROM postgremq.get_queue_statistics('jobs');
On a new queue after this single test, expect ten completed deliveries and no pending or processing deliveries. Existing jobs contribute to these counts too.
Acknowledge work only after it succeeds
Handler consumers acknowledge automatically when a handler finishes normally while its cancellation signal is still live. TypeScript handlers that throw and Rust handlers that return Err are negatively acknowledged. In Go, the handler has no error return: explicitly call Nack when application work fails. Merely logging an error and returning normally would acknowledge the job.
All three SDKs also let a handler acknowledge or negatively acknowledge explicitly. Explicit settlement takes precedence over automatic settlement. Use a delayed negative acknowledgement when the job should be tried later:
| Language | Return a failed job with a 10-second delay |
|---|---|
| Go | message.Nack(settleCtx, postgremq.WithDelayUntil(time.Now().Add(10*time.Second))) |
| Rust | message.nack(Some(std::time::Duration::from_secs(10))).await |
| TypeScript | message.nack({ delaySeconds: 10 }) |
Handle errors from these calls. In Go, settleCtx should be a separate bounded context, rather than the handler context that may already be cancelled; the shutdown guide shows this pattern.
If a worker disappears, an unacknowledged delivery can become available again after its visibility timeout. The SDK extends that timeout while the work is active. Receiving the job again must be safe: use an application operation ID, a database uniqueness constraint, or the downstream service's idempotency key to prevent repeated effects.
With the limit of five attempts used here, a negative acknowledgement on the last attempt moves the delivery to the dead-letter queue. A crash on the last attempt needs scheduled postgremq.pmq_maintenance_fast() to complete that move after the timeout. Configure this job before relying on automatic recovery in production.
Batching and concurrency
Two workers with four handlers each can run up to eight handlers between them. Both may also hold fetched messages waiting for a handler. Increasing the fetch batch without increasing processing capacity can make more messages wait inside those workers and leave less available for other workers.
A batch is a fetch limit, not a fairness guarantee or a queue-wide concurrency limit. Start with bounded handler concurrency, then tune batch size against processing latency, database calls, and the amount of prefetched work. A larger batch also cannot bypass FIFO groups: each group permits only its current head to be claimed, while different groups can progress concurrently.
Automatic extension and lost ownership
With automatic extension enabled, the SDK renews deliveries it manages while processing continues. This includes buffered work awaiting application processing. A long-running handler can therefore exceed the initial visibility timeout without making its delivery available to another worker.
Extension depends on continued database communication. If ownership is lost, the delivery's cancellation signal fires: Go exposes ctx/message.StoppedCtx, Rust exposes message.stopped(), and TypeScript exposes message.signal. Stop work that can still be cancelled. The signal cannot undo an external effect that already completed, so idempotency remains necessary.
Automatic extension is enabled by default. The corresponding options for controlling it are:
| Setting | Go | Rust | TypeScript |
|---|---|---|---|
| Disable extension | WithNoAutoExtension() together with WithVT(30) | .auto_extend(false) | autoExtension: { enabled: false } |
| Renew after half the timeout elapses | WithExtensionThreshold(0.5) | .extension_threshold(0.5) | autoExtension: { enabled: true, extensionThreshold: 0.5 } |
Disable automatic extension only when the application takes responsibility for completing or renewing work before expiry. With extension disabled, manual renewal uses the following calls; the duration is in seconds and sets a new deadline from the time of renewal:
| Language | Renew an active delivery for 30 seconds |
|---|---|
| Go | message.SetVT(ctx, 30) |
| Rust | message.extend(std::num::NonZeroU32::new(30).unwrap()).await |
| TypeScript | message.setVt(30) |
| SQL | postgremq.set_vt(queue_name, message_id, consumer_token, 30) |
Check renewal errors and use the returned deadline. Renewal cannot recover an already expired lease. Raw SQL has no background auto-extension; a SQL consumer must arrange its own renewal calls. The consumer's visibility timeout is separate from the lifetime of an Exclusive queue.
Automatic extension also does not replace an application timeout. If a handler stalls while renewal keeps succeeding, its message can remain reserved indefinitely. Give external calls and the handler's own work appropriate deadlines, and configure graceful shutdown for process termination.
Use Transactional outbox when application changes and acknowledgement must share a transaction. For ordering boundaries, see publishing with a group key.