Skip to main content

Idempotent consumers

PostgreMQ can commit a consumer's database changes and acknowledgement in the same transaction. Either the effect and completion both commit, or neither does. This prevents the gap between applying a database change and recording that this delivery completed.

Repeated publication is a separate problem: two messages can represent the same application event. An application event ID and transactional inbox can recognize that duplication across different PostgreMQ message IDs.

Choose the duplicate boundary​

Use transactional acknowledgement when the effect is in the same PostgreSQL database as PostgreMQ. If the application only needs atomic completion of that specific delivery, another deduplication table is not inherently required.

Add an inbox when repeated publications, replay, or upstream retries must not repeat the effect. Scope the inbox key by logical subscriber and application event ID. Different subscribers may legitimately apply the same event once each; workers of one subscriber must share the same key space.

Apply an event once​

This example records an event and increments a subscriber's total. A unique inbox key makes a repeated event skip the increment while still acknowledging its delivery. eventID and delta are validated values decoded from the message payload; the publisher must preserve the event ID when retrying publication.

Create the application tables once through deployment migrations. These setup examples use an application-owned pool connected to the PostgreMQ database.

_, err := pool.Exec(ctx, `CREATE SCHEMA IF NOT EXISTS app;
CREATE TABLE IF NOT EXISTS app.inbox (
subscriber text NOT NULL, event_id text NOT NULL,
PRIMARY KEY (subscriber, event_id));
CREATE TABLE IF NOT EXISTS app.totals (
subscriber text PRIMARY KEY, value bigint NOT NULL);`)
if err != nil { return err }

The following helpers are called from a stream consumer after validating the payload. The fixed subscriber identity is subscriber-a, independent of the worker process handling the attempt.

func applyEvent(ctx context.Context, pool *pgxpool.Pool,
message *postgremq.Message, eventID string, delta int64) error {
tx, err := pool.Begin(ctx)
if err != nil { return err }
defer tx.Rollback(context.Background())
result, err := tx.Exec(ctx,
`INSERT INTO app.inbox(subscriber, event_id) VALUES ('subscriber-a', $1)
ON CONFLICT DO NOTHING`, eventID)
if err != nil { return err }
if result.RowsAffected() == 1 {
_, err = tx.Exec(ctx,
`INSERT INTO app.totals(subscriber, value) VALUES ('subscriber-a', $1)
ON CONFLICT (subscriber) DO UPDATE SET value = app.totals.value + EXCLUDED.value`, delta)
if err != nil { return err }
}
if err := message.AckWithTx(ctx, tx); err != nil { return err }
return tx.Commit(ctx)
}

The effect must happen only when the inbox insert succeeds. Recording the inbox entry in a different transaction would reintroduce a gap between deduplication and the effect.

Verify duplicates and rollback​

On fresh application tables, publish two messages carrying event-1 with delta 1 and process both. The total should be 1, the inbox should contain one entry for this subscriber, and both queue deliveries should be completed. Use each language's normal PostgreSQL query API to assert those rows; the schema above defines the observable result.

Then test a failure before commit. Neither inbox nor total changes should commit, and the delivery must remain recoverable. A transaction-scoped acknowledgement ends automatic extension when the statement completes; commit or roll back promptly. Rollback leaves recovery to lease expiry. Do not reuse the settled delivery object or assume its automatic renewal resumes.

Failure pointRecovery
Before acknowledgement, transaction rolls backNo committed effect; retry processing under a valid delivery attempt.
After acknowledgement statement, before commitCaller must finish the transaction; rollback commits neither effect nor completion.
Commit response lostThe caller cannot tell whether commit succeeded, but effect and completion remain atomic. If both committed, this delivery is complete; if neither committed, a later claim can apply the effect. The inbox additionally protects against another publication or replay of the same application event.
Duplicate publication has a new message IDShared application event ID prevents applying the increment again.

Before calling transactional acknowledgement, an aborted transaction can be retried as a whole while the delivery is still valid. Calling acknowledgement starts the SDK object's terminal operation: even if the statement fails or the transaction later rolls back, do not acknowledge again through that object. Roll back promptly and let an uncommitted delivery become available for a new claim after lease expiry. Avoid holding transactions open across slow external work.

External effects​

A PostgreSQL transaction cannot roll back an HTTP request. Use an external service's idempotency key with the stable application event ID and subscriber or operation scope. Confirm that service's retention and conflict rules; a locally stored inbox alone cannot atomically prove an external effect occurred.

Keep inbox records long enough for the application's replay and duplication horizon. Deleting them too early permits old events to apply again. See Retries and Backup and recovery for replay and restored timelines.