Idempotency across a database commit and a Kafka offset
A short SQL exercise separates a PostgreSQL job claim, an idempotent database update and a Kafka consumer offset. Each advances at a different boundary.
By Denis Stepulenok · Published · Revised
Follow each commit separately
An outbox transaction puts the application change and its event row in the same database commit. A relay that publishes to Kafka and then marks the event sent has a different boundary. A crash after broker acknowledgement can leave the row pending, so the relay may publish the same event again.
On the consumer side, polling advances its position. The group’s committed offset is where recovery resumes. Commit the database effect first, then advance the offset for the processed portion of that partition. A crash in between allows replay. Committing the offset first can skip an effect that never reached the database.
Observe a row claim in two sessions
In a disposable PostgreSQL database, run the setup once and open two sessions. Leave the first transaction open while you run the second. The second query returns 2 because the first transaction holds the row for 1. Roll back both transactions after the observation.
-- Setup
CREATE TABLE queue_demo (id integer PRIMARY KEY);
INSERT INTO queue_demo VALUES (1), (2);
-- Session A
BEGIN;
SELECT id FROM queue_demo WHERE id = 1 FOR UPDATE;
-- Session B
BEGIN;
SELECT id FROM queue_demo
ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;
ROLLBACK;
-- Session A
ROLLBACK;
Replay one database effect
In one new session, run the setup and execute the common table expression twice. The second insertion sees the same event ID and returns no row, so the update runs only on the first attempt. The counter ends at 1. In a consumer, use a stable event ID and commit the marker and effect in one transaction before updating the offset.
CREATE TEMP TABLE processed (event_id text PRIMARY KEY);
CREATE TEMP TABLE totals (value integer NOT NULL);
INSERT INTO totals VALUES (0);
-- Run this statement twice.
WITH accepted AS (
INSERT INTO processed VALUES ('demo-event')
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id
)
UPDATE totals SET value = value + 1
WHERE EXISTS (SELECT 1 FROM accepted);
SELECT value FROM totals; -- Expected: 1
Where the guarantees stop
SKIP LOCKED lets concurrent workers take another available row. To keep a claim after the transaction ends, persist a state change or lease and define who recovers it on expiry. Rows can be processed out of arrival order.
The deduplication record covers the example’s database effect only. A separate network call needs an idempotency contract of its own. If work completes in parallel, the committed offset must leave any unfinished earlier work recoverable within its partition. The SQL exercise models neither broker failure nor consumer group rebalancing.