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.
- Go
- Rust
- TypeScript
- SQL
_, 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 }
postgremq::sqlx::raw_sql("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);")
.execute(&pool).await?;
await pool.query(`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);`);
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);
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.
- Go
- Rust
- TypeScript
- SQL
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)
}
async fn apply_event(
pool: &postgremq::sqlx::PgPool, message: &postgremq::Delivery,
event_id: &str, delta: i64,
) -> Result<(), Box<dyn std::error::Error>> {
let mut tx = pool.begin().await?;
let result = postgremq::sqlx::query(
"INSERT INTO app.inbox(subscriber, event_id) VALUES ('subscriber-a', $1)
ON CONFLICT DO NOTHING",
).bind(event_id).execute(&mut *tx).await?;
if result.rows_affected() == 1 {
postgremq::sqlx::query(
"INSERT INTO app.totals(subscriber, value) VALUES ('subscriber-a', $1)
ON CONFLICT (subscriber) DO UPDATE SET value = app.totals.value + EXCLUDED.value",
).bind(delta).execute(&mut *tx).await?;
}
message.ack_tx(&mut tx).await?;
tx.commit().await?;
Ok(())
}
import type { Pool } from 'pg';
import type { Message } from 'postgremq';
async function applyEvent(pool: Pool, message: Message, eventID: string, delta: number) {
const tx = await pool.connect();
let discard = false;
try {
await tx.query('BEGIN');
const result = await tx.query(
`INSERT INTO app.inbox(subscriber, event_id) VALUES ('subscriber-a', $1)
ON CONFLICT DO NOTHING`, [eventID]);
if (result.rowCount === 1) {
await tx.query(
`INSERT INTO app.totals(subscriber, value) VALUES ('subscriber-a', $1)
ON CONFLICT (subscriber) DO UPDATE SET value = app.totals.value + EXCLUDED.value`,
[delta]);
}
await message.ackWithTransaction(tx);
await tx.query('COMMIT');
} catch (error) {
try { await tx.query('ROLLBACK'); } catch { discard = true; }
throw error;
} finally {
tx.release(discard);
}
}
BEGIN;
WITH inserted AS (
INSERT INTO app.inbox(subscriber, event_id)
VALUES ('subscriber-a', 'event-1') ON CONFLICT DO NOTHING
RETURNING 1
)
INSERT INTO app.totals(subscriber, value)
SELECT 'subscriber-a', 1 FROM inserted
ON CONFLICT (subscriber) DO UPDATE
SET value = app.totals.value + EXCLUDED.value;
-- Use the ID and token of the current claim:
SELECT postgremq.ack_message('jobs', 123, 'returned-consumer-token');
COMMIT;
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 point | Recovery |
|---|---|
| Before acknowledgement, transaction rolls back | No committed effect; retry processing under a valid delivery attempt. |
| After acknowledgement statement, before commit | Caller must finish the transaction; rollback commits neither effect nor completion. |
| Commit response lost | The 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 ID | Shared 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.