Skip to main content

15 - Listing Events: Outbox, Offsets and Exactly-Once

A consumer killed halfway loses or duplicates alerts depending on the order of effect and offset: the experiment counts them and shows how to reach zero.

What do you think about this article?

15 - Listing Events: Outbox, Offsets and Exactly-Once
PropTechfedericocalo.dev

At a Glance

A consumer killed halfway loses or duplicates alerts depending on the order of effect and offset: the experiment counts them and shows how to reach zero.

The price dropped, and the alert arrived twice (or never)

A listing drops by a thousand euro and whoever follows it must receive an alert: exactly one. If the process that sends the alerts dies halfway, there are three cases and you already know them: the alert is not sent, it is sent twice, or it is sent once only because you drew the boundary between the consumer and the destination well. Nothing about time is computed here; what is decided here is how many times an effect happens. Event times, windows and delays are in the article on the real-time data pipeline; this one is about delivery.

The thesis is that "exactly once" is not a property of the broker but of the boundary between whoever reads and what gets written: with an ordered log, a reading position (an offset) and an effect written in the same transaction as the advance, a consumer killed halfway leaves neither losses nor duplicates. I prove it by killing it, with a real process that exits with code 1. The "Kafka" of the experiment is a simulation: a log in a PostgreSQL 17 table, not a broker. I do not measure throughput, I do not test the rebalance of a group and I do not use Flink; at the end I say what changes on a real broker, from sources only.

The outbox: the event is born in the same transaction as the fact

The first mistake is the double write: you update the price in the database and then publish to the broker. If you die in between, the price has changed and nobody knows, or the other way round. The transactional outbox pattern avoids it by writing the event into a table of the same database, in the same transaction that modifies the listing; a separate process, the relay, then carries it to the broker. The description of the pattern puts it this way: messages are sent if and only if the database transaction commits. In the listing the change_price procedure updates the listing and inserts the event in a single statement.

Outbox, simulated log with an offset per partition and a single-statement relay
SET client_min_messages = warning;
DROP TABLE IF EXISTS plain_delivery, idempotent_delivery, consumer_offset, event_log, outbox, listing CASCADE;

CREATE TABLE listing (id integer PRIMARY KEY, price integer NOT NULL);
INSERT INTO listing SELECT g, 200000 + g * 10000 FROM generate_series(1, 4) g;

-- The outbox lives in the same database as the listing: that is why it can be in the same transaction.
CREATE TABLE outbox (
  id         bigserial PRIMARY KEY,
  listing_id integer NOT NULL REFERENCES listing,
  payload    jsonb   NOT NULL,
  published  boolean NOT NULL DEFAULT false
);

-- SIMULATION of the Kafka topic: one log per partition, with an increasing position (offset).
CREATE TABLE event_log (
  partition  integer NOT NULL,
  position   bigint  NOT NULL,
  listing_id integer NOT NULL,
  payload    jsonb   NOT NULL,
  PRIMARY KEY (partition, position)
);

-- Where each consumer group has got to: the next position to read.
CREATE TABLE consumer_offset ("group" text, partition integer, next bigint NOT NULL, PRIMARY KEY ("group", partition));

-- Two destinations for the "alert whoever is house hunting" effect. The second is idempotent by construction.
CREATE TABLE plain_delivery (id bigserial PRIMARY KEY, partition integer, position bigint, listing_id integer, price integer);
CREATE TABLE idempotent_delivery (partition integer, position bigint, listing_id integer, price integer, PRIMARY KEY (partition, position));

DROP PROCEDURE IF EXISTS change_price(integer, integer);
CREATE PROCEDURE change_price(p_id integer, p_new integer) LANGUAGE sql AS $$
  WITH old AS (SELECT price FROM listing WHERE id = p_id FOR UPDATE),
       upd AS (UPDATE listing SET price = p_new WHERE id = p_id RETURNING id)
  INSERT INTO outbox (listing_id, payload)
  SELECT p_id, jsonb_build_object('listing_id', p_id, 'old_price', o.price, 'new_price', p_new) FROM old o;
$$;

-- 1. Atomicity: if the transaction fails, neither the new price nor the event remains.
BEGIN; CALL change_price(1, 1); ROLLBACK;
SELECT (SELECT price FROM listing WHERE id = 1) AS listing_1_price, (SELECT count(*) FROM outbox) AS events_in_outbox;

-- 2. Six price cuts of 1,000 euro for each of the 4 listings: 24 events.
DO $$
DECLARE p integer;
BEGIN
  FOR r IN 1..6 LOOP
    FOR a IN 1..4 LOOP
      SELECT price INTO p FROM listing WHERE id = a;
      CALL change_price(a, p - 1000);
    END LOOP;
  END LOOP;
END $$;
SELECT count(*) AS events_in_outbox, count(*) FILTER (WHERE NOT published) AS to_publish FROM outbox;

-- 3. The "relay": copies the outbox into the log, partition = listing_id % 2, and assigns the positions.
WITH taken AS (
  UPDATE outbox SET published = true WHERE NOT published RETURNING id, listing_id, payload
), numbered AS (
  SELECT listing_id % 2 AS partition, listing_id, payload,
         row_number() OVER (PARTITION BY listing_id % 2 ORDER BY id) - 1 AS n
  FROM taken
)
INSERT INTO event_log (partition, position, listing_id, payload)
SELECT n.partition,
       n.n + coalesce((SELECT max(l.position) + 1 FROM event_log l WHERE l.partition = n.partition), 0),
       n.listing_id, n.payload
FROM numbered n;

SELECT partition, count(*) AS events, min(position) AS first, max(position) AS last,
       array_agg(DISTINCT listing_id ORDER BY listing_id) AS listings
FROM event_log GROUP BY partition ORDER BY partition;
SELECT position, payload FROM event_log WHERE partition = 0 AND position < 3 ORDER BY position;

-- Output:
--  listing_1_price | events_in_outbox
-- -----------------+------------------
--           210000 |                0
-- (1 row)
--
--  events_in_outbox | to_publish
-- ------------------+------------
--                24 |         24
-- (1 row)
--
--  partition | events | first | last | listings
-- -----------+--------+-------+------+----------
--          0 |     12 |     0 |   11 | {2,4}
--          1 |     12 |     0 |   11 | {1,3}
-- (2 rows)
--
--  position |                           payload
-- ----------+-------------------------------------------------------------
--         0 | {"new_price": 219000, "old_price": 220000, "listing_id": 2}
--         1 | {"new_price": 239000, "old_price": 240000, "listing_id": 4}
--         2 | {"new_price": 218000, "old_price": 219000, "listing_id": 2}
-- (3 rows)

The first test is a ROLLBACK: after calling the procedure with price 1 and cancelling, the price of listing 1 is still 210,000 and the outbox has zero events. Then 24 price cuts (6 for each of the 4 listings) produce 24 rows, all to be published. The relay is a single statement that marks the rows as published and inserts them into the log, assigning the partition (listing_id % 2) and an increasing position per partition: the result is 12 events per partition, positions from 0 to 11, listings 2 and 4 in partition 0 and listings 1 and 3 in partition 1. The key determines the partition, and it is the only reason why the events of the same listing stay in order.

One caution about the relay. Here it is atomic because log and outbox are in the same database. With a real broker it is not: the relay can publish and die before marking the row, and then the event is published twice. The pattern itself admits it ("a message consumer must be idempotent"): the outbox guarantees the event is not lost, not that it arrives once only. That is why the consumer, in the next sections, cannot trust it.

The consumer dies halfway: three ways to get it wrong and two ways not to

The consumer reads from the recorded position, takes a batch of five events, applies the effect (here, writing a row recording the delivery of the alert) and advances the position. Everything lies in the order of these two steps. The Kafka documentation describes the first two cases in the same words: saving the position before processing gives "at-most-once" semantics, processing and then saving the position gives "at-least-once". The listing implements four modes, chosen from the command line, and one point where the process dies: after the seventh effect applied (CRASH_AT=7), with process.exit(1), with no commit and no orderly shutdown.

The consumer in four variants, with a simulated crash after the 7th effect
// Consumer of the "alerts" group on partition 0 of the simulated log.
// usage: CRASH_AT=7 node 02_consumer.js <at-most-once | at-least-once | idempotent-sink | exactly-once>
const { Client } = require('pg');

const mode = process.argv[2];
const CRASH_AT = Number(process.env.CRASH_AT || 0); // 0 = no crash
const GROUP = 'alerts', PART = 0, BATCH = 5;
let effects = 0;

// Simulates the "process that dies": no commit, no orderly shutdown, exit code 1.
function maybeDie() { if (CRASH_AT > 0 && effects === CRASH_AT) process.exit(1); }

async function main() {
  const db = new Client({ host: process.env.PGHOST, port: Number(process.env.PGPORT), database: 'pt15' });
  await db.connect();
  await db.query(`INSERT INTO consumer_offset VALUES ($1, $2, 0) ON CONFLICT DO NOTHING`, [GROUP, PART]);

  for (;;) {
    let next, batch;
    if (mode === 'exactly-once') await db.query('BEGIN');
    // FOR UPDATE: only one consumer at a time advances this group on this partition.
    next = (await db.query(
      `SELECT next FROM consumer_offset WHERE "group" = $1 AND partition = $2 ${mode === 'exactly-once' ? 'FOR UPDATE' : ''}`,
      [GROUP, PART])).rows[0].next;
    batch = (await db.query(
      `SELECT position, listing_id, (payload->>'new_price')::int AS price
       FROM event_log WHERE partition = $1 AND position >= $2 ORDER BY position LIMIT $3`,
      [PART, next, BATCH])).rows;
    if (batch.length === 0) { if (mode === 'exactly-once') await db.query('ROLLBACK'); break; }
    const newPos = Number(batch[batch.length - 1].position) + 1;
    const advance = () => db.query(`UPDATE consumer_offset SET next = $3 WHERE "group" = $1 AND partition = $2`, [GROUP, PART, newPos]);

    if (mode === 'at-most-once') {
      await advance();                                  // 1. first the position is recorded...
      for (const e of batch) {                          // 2. ...then the effect is performed
        await db.query(`INSERT INTO plain_delivery (partition, position, listing_id, price) VALUES ($1,$2,$3,$4)`, [PART, e.position, e.listing_id, e.price]);
        effects++; maybeDie();
      }
    } else if (mode === 'at-least-once') {
      for (const e of batch) {                          // 1. first the effect (committed at once)...
        await db.query(`INSERT INTO plain_delivery (partition, position, listing_id, price) VALUES ($1,$2,$3,$4)`, [PART, e.position, e.listing_id, e.price]);
        effects++; maybeDie();
      }
      await advance();                                  // 2. ...then the position
    } else if (mode === 'idempotent-sink') {
      for (const e of batch) {                          // like at-least-once, but the destination discards the duplicate
        await db.query(`INSERT INTO idempotent_delivery VALUES ($1,$2,$3,$4) ON CONFLICT DO NOTHING`, [PART, e.position, e.listing_id, e.price]);
        effects++; maybeDie();
      }
      await advance();
    } else {                                            // exactly-once
      for (const e of batch) {                          // effect and position: SAME transaction
        await db.query(`INSERT INTO idempotent_delivery VALUES ($1,$2,$3,$4) ON CONFLICT DO NOTHING`, [PART, e.position, e.listing_id, e.price]);
        effects++; maybeDie();
      }
      await advance();
      await db.query('COMMIT');
    }
  }
  await db.end();
}
main().catch((e) => { console.error(e); process.exit(2); });

In at-most-once mode the position advances first (advance() before the loop of effects): if you die in the middle, the events of the batch not yet processed are skipped for ever. In at-least-once mode the effect is committed at once and the position after: if you die in the middle, on restart the batch starts again from the old position and redoes the effects already done. In idempotent-sink mode the order is the same, but the destination has a primary key on the pair (partition, position) and an ON CONFLICT DO NOTHING: the duplicate is discarded. In exactly-once mode effect and advance are inside BEGIN ... COMMIT and the position row is locked with FOR UPDATE, so only one consumer at a time can advance that partition: if the process dies, the connection drops and the database rolls everything back.

The test script runs each mode twice, one child process at a time: the first dies after the seventh effect, the second restarts without a crash. Then it counts.

The test: kill the consumer and count deliveries, duplicates and losses
// Runs the consumer twice for each mode: the first run dies after the 7th effect, the second restarts.
// One child process at a time (spawnSync), no background process.
const { spawnSync } = require('node:child_process');
const { Client } = require('pg');
const env = { ...process.env };

const run = (mode, crashAt) => spawnSync('node', [__dirname + '/02_consumer.js', mode],
  { env: { ...env, CRASH_AT: String(crashAt) }, encoding: 'utf8' }).status;

(async () => {
  const db = new Client({ host: env.PGHOST, port: Number(env.PGPORT), database: 'pt15' });
  await db.connect();
  const table = { 'at-most-once': 'plain_delivery', 'at-least-once': 'plain_delivery', 'idempotent-sink': 'idempotent_delivery', 'exactly-once': 'idempotent_delivery' };
  console.log('events in partition 0: 12');
  for (const mode of Object.keys(table)) {
    await db.query('TRUNCATE plain_delivery, idempotent_delivery; UPDATE consumer_offset SET next = 0');
    const s1 = run(mode, 7);   // the process dies after applying the 7th effect
    const afterCrash = (await db.query('SELECT next FROM consumer_offset')).rows[0]?.next;
    const s2 = run(mode, 0);   // restart without a crash
    const r = (await db.query(
      `SELECT count(*)::int AS total, count(DISTINCT position)::int AS distinct_count FROM ${table[mode]}`)).rows[0];
    console.log(`${mode.padEnd(16)} exit1=${s1} position_after_crash=${afterCrash} exit2=${s2} ` +
      `deliveries=${r.total} distinct=${r.distinct_count} duplicates=${r.total - r.distinct_count} lost=${12 - r.distinct_count}`);
  }
  await db.end();
})();

// Output:
// events in partition 0: 12
// at-most-once     exit1=1 position_after_crash=10 exit2=0 deliveries=9 distinct=9 duplicates=0 lost=3
// at-least-once    exit1=1 position_after_crash=5 exit2=0 deliveries=14 distinct=12 duplicates=2 lost=0
// idempotent-sink  exit1=1 position_after_crash=5 exit2=0 deliveries=12 distinct=12 duplicates=0 lost=0
// exactly-once     exit1=1 position_after_crash=5 exit2=0 deliveries=12 distinct=12 duplicates=0 lost=0

The output is clear-cut. With at-most-once the position after the crash is already 10, the restart resumes from there and the deliveries are 9 out of 12: 3 lost, because events 7, 8 and 9 were in the batch already "taken as done". With at-least-once the position stayed at 5, the restart redoes events 5 and 6 already sent: 14 deliveries for 12 events, 2 duplicates. With idempotency at the destination the deliveries are 12, the redone work is the same but the duplicate does not exist. With the transaction they are 12, and the crash left no trace because the position row went back to 5 together with the effects.

The two solutions are not equivalent. The transaction is possible only if the effect lives in the same database as the position, as here. An email or a push notification does not: you cannot put them in a PostgreSQL transaction. In that case you stay at "at least once" and the guarantee comes from the destination, that is from an idempotency key (the partition-position pair is a natural choice) that the sending provider must know how to honour. If it does not honour it, the duplicate is unavoidable and has to be said to whoever designs the product, not hidden in the code.

Two consumers on the same group: they do not step on each other's toes, but they lose the order

To go faster you need more consumers. SELECT ... FOR UPDATE SKIP LOCKED is the PostgreSQL tool for this: each consumer takes rows that nobody else has locked and skips the others. The documentation warns that skipping locked rows gives an "inconsistent view" of the data, so it should not be used for general-purpose work, but it is suitable for avoiding contention among several consumers of a queue-like table. The experiment has a queue of 24 events over 4 alternating listings, a slow consumer (60 ms per batch) and a fast one (5 ms); the waits are fixed, not random, so the test can be repeated.

Two consumers with SKIP LOCKED, with and without key assignment
// Two consumers of the same group on a queue: SKIP LOCKED avoids stepping on each other's toes,
// but does not preserve per-key order. The waits are FIXED (not random) to make the test repeatable.
const { Client } = require('pg');
const conn = () => new Client({ host: process.env.PGHOST, port: Number(process.env.PGPORT), database: 'pt15' });
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function prepare(db) {
  await db.query(`DROP TABLE IF EXISTS queue; CREATE TABLE queue (id int PRIMARY KEY, listing_id int, done boolean DEFAULT false)`);
  // 24 events: listings 1..4 alternate, so each listing has 6 events in id order.
  await db.query(`INSERT INTO queue (id, listing_id) SELECT g, (g - 1) % 4 + 1 FROM generate_series(1, 24) g`);
}

// One consumer: takes a batch of 3 with SKIP LOCKED, "works" for ms milliseconds, commits.
async function consumer(name, ms, filter, log, firstClaim) {
  const db = conn(); await db.connect();
  for (;;) {
    await db.query('BEGIN');
    const { rows } = await db.query(
      `SELECT id, listing_id FROM queue WHERE NOT done ${filter} ORDER BY id LIMIT 3 FOR UPDATE SKIP LOCKED`);
    if (firstClaim) { firstClaim.resolve(); firstClaim = null; }
    if (rows.length === 0) { await db.query('ROLLBACK'); break; }
    await sleep(ms);                                              // the "work" (one send) takes ms
    await db.query('UPDATE queue SET done = true WHERE id = ANY($1)', [rows.map((r) => r.id)]);
    await db.query('COMMIT');
    for (const r of rows) log.push({ ...r, name });               // COMPLETION order
  }
  await db.end();
}

function check(log) {
  const perKey = new Map(); let inversions = 0;
  for (const e of log) {
    const last = perKey.get(e.listing_id) ?? 0;
    if (e.id < last) inversions++;      // an older event completed after a more recent one
    perKey.set(e.listing_id, Math.max(last, e.id));
  }
  return { completed: log.length, distinct: new Set(log.map((e) => e.id)).size, inversions };
}

(async () => {
  const db = conn(); await db.connect();
  for (const [title, filterA, filterB] of [
    ['without key assignment', '', ''],
    ['key assigned (listing_id even / odd)', 'AND listing_id % 2 = 0', 'AND listing_id % 2 = 1']]) {
    await prepare(db);
    const log = []; let unblock; const a_ready = new Promise((r) => (unblock = r));
    const A = consumer('A', 60, filterA, log, { resolve: unblock });   // slow
    await a_ready;                                                      // A has already taken its first batch
    const B = consumer('B', 5, filterB, log, null);                    // fast
    await Promise.all([A, B]);
    const v = check(log);
    console.log(`${title}: completed=${v.completed} distinct=${v.distinct} inversions_per_key=${v.inversions}`);
    console.log('  completion order (id):', log.map((e) => e.name + e.id).join(' '));
  }
  await db.end();
})();

// Output (the number of inversions changes between runs: 3 here, between 3 and 6 in six reruns; with the key assigned it is always 0):
// without key assignment: completed=24 distinct=24 inversions_per_key=3
//   completion order (id): B4 B5 B6 B7 B8 B9 B10 B11 B12 B13 B14 B15 B16 B17 B18 B19 B20 B21 B22 B23 B24 A1 A2 A3
// key assigned (listing_id even / odd): completed=24 distinct=24 inversions_per_key=0
//   completion order (id): B1 B3 B5 B7 B9 B11 B13 B15 B17 B19 B21 B23 A2 A4 A6 A8 A10 A12 A14 A16 A18 A20 A22 A24

In the first case no event is processed twice (24 completed, 24 distinct), but the fast consumer finishes events 4 to 24 before the slow one completes 1, 2 and 3: those in the reported run there are 3 per-key inversions (in six reruns, on a heavily loaded machine, I counted 3 to 6), that is at least three times when an older event of the listing is completed after a more recent one. For a price-drop alert it means saying "the price has dropped to 218,000" after having said "it has dropped to 217,000". In the second case each consumer has its own keys (even and odd): the inversions are zero. A partitioned broker obtains the same effect by assigning each partition to a single consumer; I did not verify it on a broker. The cost is already visible here: each key is served by a single consumer, so a very active listing cannot be spread out.

The test does not say how fast it is: the milliseconds are fake and serve to make the order likely, not guaranteed: the inversion count depends on the scheduler, whereas the fact that it is zero with the key assigned does not. It says that per-key order is not a free side effect of a database with a good index, but an assignment rule that you have to write yourself or receive from the broker.

What changes with a real broker

Everything that follows comes from the documentation and I have not run it. Kafka offers an idempotent producer: the broker assigns each producer an identifier and deduplicates messages with a sequence number, so a relay that repeats the send after a network error does not write duplicates into the log. KIP-98, which introduced it, specifies however that idempotence does not cover writes across several partitions: for those you need transactions, which make the write across several partitions atomic. The case we solved here with a database transaction, reading from one topic and writing to another, is solved in Kafka by writing the consumer's position, which is a message in an internal topic, in the same transaction as the output topics; consumers with "read_committed" isolation see only what has been confirmed.

The limits declared in the same documentation matter as much as the features. Kafka's exactly-once holds inside Kafka (Kafka Streams, or the read-process-write path between topics). For an external system, such as sending an email, it requires the cooperation of the destination: the route indicated is to save the position in the same place as the output, exactly what I did in the transactional mode. Otherwise, by default, Kafka guarantees "at-least-once". The documentation also warns that many systems claim "exactly-once" in a misleading way, because it does not hold when consumers or producers fail or there is more than one. I did not measure group rebalancing or log compaction, and I do not write about them.

Where it fits in the series

The theme of delivery sits downstream of that of time: the events that here receive a position are those that the real-time pipeline has already ordered and deduplicated by event time, and the model of the listing as an entity is described in the article on the platform architecture. For the opposite side, where the readings of the sensors that produce similar events are stored for the long term, there is the article on sensor time series in PostgreSQL.

Previous in the series: 14. Building Sensor Time Series in PostgreSQL. Next in the series: 16. Dynamic Rental Pricing: Elasticity and Guardrails.

What you can do now

You can write an event in the same transaction as the fact that generates it, and explain why the outbox is not enough to avoid duplicates. You can say in which order effect and position advance have to be to obtain "at most once", "at least once" or the transactional combination, and you have seen with a killed process how many deliveries each one loses or duplicates. You can choose between transaction and idempotency at the destination depending on whether the effect lies in your database or outside, and you know why several consumers with SKIP LOCKED require a key assignment if order matters. Finally you can tell apart what you have demonstrated (the simulation) from what you have read (the broker).

Sources

Listings 01 (SQL), 02, 03 and 04 (Node 24 with the pg 8.23.1 driver) were run on 2026-11-12 on PostgreSQL 17.10 in a temporary cluster, then deleted. The log is a simulation in a table: it is not Kafka and no broker was used. Listing 02 is launched by 03. Synthetic data; the waits in listing 04 are fixed and only serve to make the order repeatable.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects