Skip to main content

Transactional outbox

PostgreMQ can commit application state changes and message publication in the same PostgreSQL transaction. Either all changes commit, or none do. Consumers cannot observe a published message before the application changes in that transaction are committed.

This provides the atomicity sought by the transactional outbox pattern without a separate application outbox table or a relay into PostgreMQ. The transaction boundary includes the application writes, the stored message, and its deliveries to subscribed queues.

This works when the application tables and PostgreMQ are in the same database. The examples use SDK 0.4.0 and SQL 0.1.1.

What commits together​

Begin transaction
Change application state
Publish message
Commit
Application changes and message become visible

Rollback removes both the application changes and the publication. Returning a message ID from a transaction-scoped publish call does not establish that either has committed.

This guarantee covers operations in that database transaction. External service calls remain outside that boundary. A database rollback cannot undo their effects, so consumers still need an idempotency strategy for operations on other systems.

Prepare the example​

Install PostgreMQ using the Quick start. In its local database, create an application table and a subscription before publishing:

The example stores an order and publishes its event. Before running these snippets, create an application-owned pool for the same database: a pgxpool.Pool in Go or a node-postgres Pool in TypeScript. Replace the Quick start’s Dial with DialFromPool in Go, or connect({ connectionString }) with connect({ pool }) in TypeScript, as shown in Connecting. The complete transaction examples below show that pool setup and cleanup.

The setup snippets use this pool; Rust uses conn.pool(). Apply table definitions through your normal database migrations in an application; these statements set up the local example.

if _, err := pool.Exec(ctx, `CREATE SCHEMA IF NOT EXISTS app;
CREATE TABLE IF NOT EXISTS app.orders (
id text PRIMARY KEY,
status text NOT NULL
);`); err != nil { return err }
if err := conn.CreateTopic(ctx, "orders"); err != nil { return err }
if err := conn.CreateQueue(ctx, "fulfilment", "orders", false,
postgremq.WithMaxDeliveryAttempts(5)); err != nil { return err }

The following functions accept a new order ID such as order-101. Run each example with a different ID; inserting an existing primary key fails and must not publish a new event.

Save an order and publish its event​

Use a pgxpool.Pool for both the application transaction and the queue connection. Create the queue connection with postgremq.DialFromPool(ctx, pool, ...), and close that connection before closing the pool.

func createOrder(ctx context.Context, pool *pgxpool.Pool,
conn *postgremq.Connection, orderID string) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())

if _, err := tx.Exec(ctx,
"INSERT INTO app.orders (id, status) VALUES ($1, 'created')",
orderID); err != nil {
return err
}
payload, err := json.Marshal(map[string]string{
"event_id": orderID + "-created",
"type": "order.created",
"order_id": orderID,
})
if err != nil {
return err
}
if _, err := conn.PublishWithTx(ctx, tx, "orders", payload); err != nil {
return err
}
return tx.Commit(ctx)
}

The deferred rollback is harmless after a successful commit. Use context, encoding/json, github.com/jackc/pgx/v5/pgxpool, and postgremq.dev/postgremq-go as imports.

Verify rollback​

Publish inside a transaction, then roll it back. Use an unused order ID for this test; these examples use rollback-demo.

tx, err := pool.Begin(ctx)
if err != nil { return err }
defer tx.Rollback(context.Background())
if _, err := tx.Exec(ctx,
"INSERT INTO app.orders (id, status) VALUES ('rollback-demo', 'created')"); err != nil {
return err
}
if _, err := conn.PublishWithTx(ctx, tx, "orders",
json.RawMessage(`{"order_id":"rollback-demo"}`)); err != nil { return err }
if err := tx.Rollback(ctx); err != nil { return err }

var orders, messages int
err = pool.QueryRow(ctx, `SELECT
(SELECT count(*) FROM app.orders WHERE id = 'rollback-demo'),
(SELECT count(*) FROM postgremq.messages WHERE payload->>'order_id' = 'rollback-demo')
`).Scan(&orders, &messages)
if err != nil { return err }
fmt.Printf("orders=%d messages=%d\n", orders, messages)

Both counts are zero. The publication call may have returned an ID before rollback; assigning an ID does not commit the surrounding transaction.

Process one event and publish the next​

A consumer can also commit its business changes, acknowledge the input message, and publish a follow-up event together. For example, update an order to packed, publish order.packed, and acknowledge order.created in the same transaction.

LanguagePublish in the transactionAcknowledge in the transaction
Goconn.PublishWithTx(ctx, tx, ...)message.AckWithTx(ctx, tx)
Rustconn.publish_tx(&mut tx, ...)message.ack_tx(&mut tx)
TypeScriptclient.publishWithTransaction(tx, ...)message.ackWithTransaction(tx)

Your application owns the commit and rollback. After a transactional acknowledgement finishes, the SDK stops automatically extending that delivery even though the transaction has not committed yet. Commit or roll back promptly. If you roll back, the input delivery can become available again after its visibility timeout. Do not try to acknowledge the same SDK delivery object a second time.

Handle transaction failures​

For a serialization failure or deadlock, retry the whole transaction, including the application writes. The SDK does not retry transaction-scoped publish or acknowledgement calls for you.

A connection failure during commit is different: the outcome can be unknown. Check application state using a stable business operation ID before repeating the operation. A unique order ID, as in this example, can help identify a previously committed creation; it is not a complete retry policy for every workflow.

Keep external calls out of the database transaction and keep the transaction short. Retrying a transaction may run application code again, and holding a transaction open can delay other database work.

Atomic publication prevents the gap between committed application data and its event. Consumers still need to handle repeated deliveries and repeated business requests. PostgreMQ does not infer that two messages with the same payload or application event ID are duplicates.