Skip to main content

Publishing messages

Publishing to a topic creates a delivery in every live queue subscribed to that topic. The message and all those deliveries commit in one PostgreSQL transaction. Each queue then tracks its own processing, retries, and acknowledgement.

The publisher addresses a topic; it does not select a worker or wait for consumers. A single publication can therefore supply a shared work queue, several independent subscriptions, or both.

Fan-out and publication guarantees​

A live queue is a Durable queue or an Exclusive queue that has not expired. Connected consumers are not required: a live queue receives publications while its consumers are offline.

On successful commit, the payload and its deliveries are stored together. There is no separate fan-out step that an application must run or retry. A publication cannot commit with only part of its selected deliveries because one queue insertion failed; that failure aborts the publication transaction.

Queue subscriptions are evaluated during publication. Declare the required queues and commit those declarations before publishing. A queue created afterward does not receive that publication, even if the message's delivery time is still in the future. Concurrent queue creation or deletion should not be used as a precise subscription boundary.

ConditionResult
Topic exists and has live queuesEach selected queue receives one delivery with the same message ID.
Topic exists but has no live queuesPublication can succeed and store the payload, but creates no deliveries. Future queues do not receive it.
Topic does not existPublication fails.
A subscribed queue has no connected consumersIts delivery waits in the queue.
An Exclusive queue has already expiredThat queue is excluded from publication.

Successful publication confirms committed storage, not successful processing. Acknowledging a message in one queue does not acknowledge it in another. A queue's retry limit can move its delivery to the dead-letter queue; queue deletion or Exclusive expiry can end access to it. Publication success does not override those lifetime and recovery rules.

Stored messages follow PostgreSQL's durability and recovery configuration. The publisher connection can close after commit without retracting them.

Prepare the subscriptions​

These examples use the connections from the Quick start: conn in Go and Rust, and client in TypeScript. Create two Durable subscriptions before publishing:

if err := conn.CreateTopic(ctx, "events"); err != nil {
return err
}
for _, queue := range []string{"subscriber-a", "subscriber-b"} {
if err := conn.CreateQueue(ctx, queue, "events", false,
postgremq.WithMaxDeliveryAttempts(5)); err != nil {
return err
}
}

Repeating identical declarations preserves the existing queues. See Durable queues and Exclusive queues for identity, lifetime, and declaration rules.

Publish a JSON event​

PostgreMQ accepts a JSON payload. This example includes an application event ID and a number; the payload has no required field names.

payload := json.RawMessage(`{
"event_id":"event-1",
"number":1
}`)
id, err := conn.Publish(ctx, "events", payload)
if err != nil {
return err
}
fmt.Printf("Published message %d\n", id)

Use encoding/json.Marshal when building a payload from application data. Publish accepts JSON bytes as json.RawMessage; those bytes must contain valid JSON.

The fields in these examples are application conventions. PostgreMQ does not enforce your payload schema or deduplicate event_id. A stable application event ID lets consumers recognize a repeated publication; it is separate from the ID PostgreMQ assigns. Evolve the payload with its consumers, and avoid including fields they do not need. Use strings for business identifiers that must retain their exact representation across languages.

Commit and visibility​

Outside an application transaction, a successful SDK publish call means the database operation committed. Its returned ID identifies the stored message and the independent deliveries created for subscribed queues.

With a transaction-scoped API, the call returns before your transaction commits. Its ID is provisional: rollback removes both the message and its deliveries. Consumers can receive the message only after commit and after any configured delivery time. Use Transactional outbox to commit application writes and publication together.

Publishing options​

ChoiceEffectGuidance
Delivery timePrevents consumption before a specified instant.See Delayed messages for timing, fan-out, and queue lifetime guarantees.
Group keyOrders related messages within each queue.Use the same key for one ordered sequence and distinct keys for independent sequences.
Application transactionCommits one or more publications with application writes.The caller owns commit, rollback, and whole-transaction retries.
SDK retry policyControls attempts and backoff for retryable database errors.It does not make an uncertain publication safe to repeat.

Retry policy is configured on the connection: WithRetryConfig in Go, ConnectionOptions::retry in Rust, and the retry connection option in TypeScript. Changing the policy adjusts retry attempts and backoff; it does not broaden which publication failures are safe to retry.

Each publish call submits one message. Publishing a collection means making multiple calls; separate nontransactional calls commit independently. If all publications must commit together, make the calls in one application transaction. Consumer fetch batching is a separate setting and does not batch a publisher's commits.

Publish related messages with the same group key to process them in order. For example, publish messages 1 and 2 with group-1: within each queue, message 2 waits for message 1 to finish or leave the group through dead-lettering or removal. Different group keys allow concurrent progress.

LanguagePublish option
Gopostgremq.WithGroupKey("group-1")
Rustpostgremq::PublishOptions::default().group_key("group-1")
TypeScript{ groupKey: 'group-1' }
SQLp_group_key => 'group-1'

Within each queue, messages in a group are delivered one at a time in publish commit order. This is FIFO ordering for that group; ungrouped messages have no strict FIFO guarantee. A delayed or repeatedly failing first message holds up the rest of its group. Acknowledgement, removal, or dead-lettering allows later messages to proceed, so replaying a dead letter can bring an older event back after newer events have run.

The group key is an ordering key, not a deduplication key. Publishing the same event twice with the same group key still creates two messages.

Handle publication failures​

A connection error can leave the outcome unknown. The database may have committed the message before the response was lost. Repeating that publication can therefore create a duplicate.

The SDKs retry nontransactional publishing automatically only for PostgreSQL serialization failures and deadlocks (40001 and 40P01), which establish that the transaction aborted. They return other errors to your application. Transactional publication is not retried automatically; retry the complete application transaction when appropriate.

Use a stable application event ID for the same event across retries, and make consumers recognize repeats before applying effects. Generate a new event ID for a new event, even when it concerns the same entity. PostgreMQ's generated ID cannot deduplicate a retried publication because the retry can receive another ID.

For work that must accompany a database change, continue with Transactional outbox. Choose the subscription lifetime and delivery arrangement in Durable queues and Exclusive queues.