LeetBuild

Consuming events

Every record can arrive twice: apply its effect, then commit its offset, and make the effect safe to apply again.

The failure mode

A consumer reads a record, does something with it (adds tokens to a bill, folds a sample into a score, queues a job) and tells the broker it is done by committing the offset. Kafka delivers at least once: the only thing it remembers about your progress is the committed offset, and it knows nothing about Redis, your database or the job queue. So every consumer has to answer two questions, and most broken ones answer neither:

  1. Where does the commit sit relative to the effect? Commit first and a crash in between loses the record for good. Effect first and a crash in between replays it.
  2. What happens when a record arrives twice? It will: after a crash, after a rebalance, after a producer retry, after someone rewinds the group to rebuild a total. If the effect is not safe to apply twice, every one of those counts double.

The smallest instance is a billing consumer:

msg = consumer.poll(1.0)
consumer.commit(message=msg, asynchronous=False)   # "done"
event = json.loads(msg.value())
redis.hincrby(f"usage:{event['tenant']}:{event['day']}", "tokens", event["tokens"])

It runs, the demo bill moves, and the code reads well. A crash (a deploy, an OOM kill, a lost container) between the second and fourth lines bills nothing for that request, and nobody can ever find out: the offset says the record was handled, and the producer will never send it again. Swap the two lines and the loss turns into a double charge on every replay. The fix is the pair: effect before the commit, and an effect that a second delivery cannot repeat.

How it shows up

The debugging courses hide this in consumers that look finished:

The symptoms rhyme. Totals that are exact in a demo with no failures. A count that is slightly low after an incident, or slightly high after a rebalance. A partition whose lag stops moving because the same record crashes the consumer on every restart. A job queued twice for the same input. None of them reproduce without injecting the failure, which is why they survive review.

The mechanism

Offsets are the only memory

A partition is an append-only log, and a consumer group stores one number per partition: the committed offset, the offset of the next record to read. On startup, and whenever a partition moves to a new member, consumption resumes from that number. Anything polled but not committed is read again; anything committed is never read again by that group.

Sequence of calls for this stepKafkabilling (member A)Redispoll -> usage, partition3, offset 1041HINCRBYusage:acme:20261112 tokens812(integer) 40318killed before thecommitrestart: committed offsetis still 1041 -> offset1041 againHINCRBY ... 812 (a secondtime)
— request- - reply· · fire-and-forget

Kafka did exactly what it promised. The duplicate is the price of not losing the record, and it is the consumer's job to make the second application harmless.

Where duplicates come from

SourceWhat happensSame offset?
Crash between effect and committhe restarted member reads from the last committed offsetyes
Rebalancea member joins, leaves, or misses max.poll.interval.ms; its partitions move with their uncommitted recordsyes
Slow member kicked outthe old member is still applying a record while the new owner applies it too, at the same timeyes
Producer retry without idempotencea lost ack makes the producer send again; the log holds two copiesno, two offsets
Replayan operator resets the group's offsets to rebuild state, or a new group reads from earliestyes, much later

Two lessons hide in that table. A dedupe keyed by (partition, offset) catches the first rows and misses producer duplicates: dedupe by an event id the producer put in the payload. And a duplicate can arrive concurrently, in another process, so a check followed by a separate write is a race: the check and the effect have to be one atomic step.

Auto-commit is not "commit after processing"

Each client commits automatically by default, and each one means something slightly different:

  • Java KafkaConsumer commits, on a timer, the offsets returned by the previous poll(). That is at-least-once only if every record from a poll is finished before the next poll. Hand records to a thread pool and the commit runs ahead of the work.
  • librdkafka (and confluent-kafka for Python, which wraps it) commits on a background timer whatever offset is stored, and by default (enable.auto.offset.store=true) an offset is stored the moment the message is handed to you. A crash mid-effect can lose a record that was committed before you finished it.
  • kafkajs eachMessage resolves the offset when your handler's promise settles. Await the effect and that is at-least-once; fire it without awaiting and it is not.
  • kafka-go ReadMessage on a reader with a GroupID commits as it reads. FetchMessage does not.

The rule is simpler than the configuration matrix: turn auto-commit off (or turn off the automatic offset store) and commit explicitly, after the effect has returned.

Delivery semantics: where the commit sits relative to processing
at-least-once: consumer events for records 0..3 with a crashpartitionconsumerside effectsrec 0donerec 1rec 2rec 3committed offset = 0consumer: runningprocess 0commit→1process 1commit→2process 2crashrestart@2process 2commit→3process 3commit→4applied: [0]a duplicate must be harmless or handled: idempotent upserts, dedupe by key
at-least-once: process, then commit the offset. Play on: the consumer will crash between the two steps of record 2.

Pop quiz

A consumer has enable.auto.commit=false, polls a record, commits its offset synchronously and then writes the effect to Redis. Which outcome does a crash between the two lines produce?

Consumer groups and partition assignment

A group spreads a topic's partitions over its members: each partition has exactly one owner at a time, so records with the same key are applied in order by one process. Members beyond the partition count sit idle. When membership changes, the group rebalances: partitions are revoked from some members and assigned to others, and the new owner starts from the committed offset.

Consumer groups: partitions → members, offsets per group
6 partitions assigned to 3 consumers in group A; group B reads the same topictopic: 6 partitions · ▲ committed · │ latestgroup A · generation 1p01923p11717p22531p3412p42226p599consumer 1 · m-b2 partitionsconsumer 2 · m-a2 partitionsconsumer 3 · m-c2 partitionsgroup B · 2 consumers · same topic, its own committed offsetsp0 @7p1 @3p2 @30p3 @12p4 @10p5 @2
6 partitions cap parallelism at 6 consumers. Range assignor: members sorted by id (m-a < m-b < m-c) take contiguous chunks. Offsets are per group: group A committed p0@19, group B p0@7, latest 23 — the same records, read independently.

Three consequences for correctness:

  • Uncommitted work moves. Whatever a member applied but had not committed when its partition was revoked is applied again by the next owner. Commit what is finished in the revoke callback (on_revoke, onPartitionsRevoked, the GROUP_JOIN/rebalance hooks) so the replay is short.
  • A slow member is a dead member. If processing a poll takes longer than max.poll.interval.ms, the coordinator removes the member and reassigns its partitions while it is still working. For a while two processes apply the same records; only an atomic dedupe keeps that harmless.
  • Ordering is per partition, not per topic. A total that depends on order (a status machine, the latest version wins) is safe only if the producer keyed related events to one partition.

Poison records

A record that can never be processed (bad JSON, a missing field, an unknown version) is not a transient failure. If the consumer throws and does not commit, it restarts, reads the same offset and throws again: the partition stops while its lag grows, and every record behind the bad one waits. If the consumer catches the error and commits silently, the record vanishes. The middle path is a dead-letter topic: produce the original key and bytes, plus the reason, wait for that produce to be acknowledged, then commit and move on.

The distinction that matters is permanent versus transient. Redis being down is not a poison record: dead-lettering it throws away good data. A transient failure is retried (or the partition paused) without committing; only a record that will fail the same way forever goes to the dead-letter topic.

Pop quiz

The effect store (Redis) times out for 20 seconds during a failover. What should the consumer do with the records it polls in that window?

The fix and its trade-offs

1. Effect, then commit, explicitly

Python (confluent-kafka):

consumer = Consumer({
    "bootstrap.servers": BROKERS,
    "group.id": "billing",
    "enable.auto.commit": False,
    "auto.offset.reset": "earliest",
})
consumer.subscribe(["usage"])
while running:
    msg = consumer.poll(1.0)
    if msg is None or msg.error():
        continue
    apply_once(msg)                                   # the effect, idempotent
    consumer.commit(message=msg, asynchronous=False)  # then the commit

TypeScript (kafkajs):

await consumer.run({
  autoCommit: false,
  eachMessage: async ({topic, partition, message}) => {
    await applyOnce(message);
    // the committed offset is the next one to read
    const next = (BigInt(message.offset) + 1n).toString();
    await consumer.commitOffsets([{topic, partition, offset: next}]);
  },
});

Go (kafka-go):

r := kafka.NewReader(kafka.ReaderConfig{Brokers: brokers, GroupID: "billing", Topic: "usage"})
for {
    m, err := r.FetchMessage(ctx) // not ReadMessage: that commits on read
    if err != nil {
        return err
    }
    if err := applyOnce(ctx, m); err != nil {
        return err // no commit: the record comes back
    }
    if err := r.CommitMessages(ctx, m); err != nil {
        return err
    }
}

C (librdkafka):

rd_kafka_conf_set(conf, "enable.auto.commit", "false", errstr, sizeof errstr);
/* ... create the consumer, subscribe ... */
rd_kafka_message_t *m = rd_kafka_consumer_poll(rk, 1000);
if (m && !m->err && apply_once(m) == 0)
    rd_kafka_commit_message(rk, m, 0); /* 0: synchronous */
if (m)
    rd_kafka_message_destroy(m);

With librdkafka-based clients, a common alternative keeps the background auto-commit but sets enable.auto.offset.store=false and calls store_offsets / rd_kafka_offsets_store after the effect: the timer then only ever commits finished work, without a broker round trip per record.

Trade-offs: a synchronous commit per record costs a round trip each. Committing once per poll batch, after every record in it is applied, is the usual compromise; the price is a longer replay after a crash, which an idempotent effect absorbs. If records are processed concurrently, commit only the highest offset below which everything is done: committing 1045 while 1043 is still in flight loses 1043 if the process dies.

2. Make the effect safe to apply twice

Commit-after-effect turns loss into duplicates; the effect has to turn duplicates into nothing. The rule: record that the event was applied in the same atomic step as the effect.

For a Redis counter, a processed-id set and the increment in one script:

-- KEYS[1] processed ids   KEYS[2] totals hash
-- ARGV[1] event id   ARGV[2] field   ARGV[3] amount   ARGV[4] ttl seconds
if redis.call('SADD', KEYS[1], ARGV[1]) == 0 then
  return 0                          -- seen before: apply nothing
end
redis.call('EXPIRE', KEYS[1], ARGV[4])
redis.call('HINCRBY', KEYS[2], ARGV[2], ARGV[3])
return 1

The script runs atomically, so two members holding the same record during a rebalance cannot both pass the SADD. Splitting it into SISMEMBER, then HINCRBY, then SADD reopens exactly that race, and a crash between the increment and the mark brings the double count back.

For a SQL store, the same idea is a unique constraint in the transaction that applies the effect:

BEGIN;
INSERT INTO processed_events (event_id) VALUES ($1) ON CONFLICT DO NOTHING;
-- apply the effect only if that insert affected one row
COMMIT;

A third option stores the consumed offset itself in the same transaction as the effect and seeks to it on assignment, ignoring Kafka's committed offset. It is exact, but it dedupes by offset, so it does not catch producer duplicates, and every partition assignment now needs a seek.

Trade-offs and choices:

  • What is the event id? One the producer assigns once per logical event (a request id, a sample id, batch_id:shard_id), not a fresh UUID per send and not the offset. Getting this wrong makes the dedupe a no-op.
  • How long are ids kept? At least as long as a duplicate can arrive: the topic's retention if replays from earliest are possible, else a window comfortably past the longest outage. Scope the set to the thing it guards (processed:{run_id}, a set per day) so it expires with its totals; the keys and expiry guide covers the scoping.
  • Naturally idempotent effects need no set. HSET entry:{shard} ..., an upsert by primary key, or "set status to delivered if the version is newer" are safe to repeat. Increments, appends and queued jobs are not.
  • Kafka transactions give exactly-once for consume-transform-produce within Kafka: the output records and the input offsets commit together. They do nothing for an effect in Redis or Postgres.

3. Handle poison records deliberately

try:
    event = parse(msg.value())
except ValueError as err:
    dlq.produce("usage.dlq", key=msg.key(), value=msg.value(),
                headers={"reason": str(err)})
    dlq.flush(5)                                       # acknowledged before the commit
    consumer.commit(message=msg, asynchronous=False)
    continue
apply_once(event)
consumer.commit(message=msg, asynchronous=False)

Validate before the effect, so a half-valid record never moves a counter. Keep the original key and bytes in the dead-letter record so it can be replayed once fixed, and alert on its rate: a sudden stream of dead letters is an upstream bug, not noise.

Pop quiz

Two members of group eval hold the same redelivered sample for a moment during a rebalance. Both run if not redis.sismember(seen, id): redis.hincrby(totals, "passed", 1); redis.sadd(seen, id). What is the outcome?

Proving the fix

Tests for this failure mode have to inject the failure: a test that only runs the happy path passes with the commit in either place. Assert on outcomes (the totals, the queued jobs, the committed offset, the dead-letter topic), never on which functions were called.

  1. Crash after the effect, before the commit. Feed a record, let the effect run, kill the consumer before it commits (raise from a commit stub, or stop the loop there). Start a fresh consumer on the same group. The record is delivered again; assert the total moved exactly once and the committed offset is now past the record.
  2. Crash before the effect. Kill the consumer after the poll and before the effect. Restart. Assert the effect happened once: nothing was lost. A commit-first consumer fails this one.
  3. A redelivered record. Deliver the same event twice, once at the same offset (rebalance) and once at a different offset with the same event id (producer retry). Assert one count.
  4. Two members at once. Run the apply step for the same event from two threads or two connections. Assert one count. This is the test that separates an atomic script from a check-then-write.
  5. A replay. Reset the group to the start and consume the whole topic again. Assert the totals are unchanged.
  6. A poison record between good ones. Put a malformed record at offset 5 of 10. Assert the other nine are applied, the dead-letter topic holds the original bytes with a reason, nothing about the bad record reached the totals, and the committed offset reaches 10.
  7. A transient effect failure. Make the store fail for one record. Assert it is not dead-lettered and not committed, and that it is applied once the store recovers.

What to take away

  • Kafka gives you at-least-once delivery; the committed offset is its only memory of your progress.
  • Commit after the effect has returned, explicitly. Know what your client's auto-commit actually commits before trusting it.
  • Duplicates come from crashes, rebalances, producer retries and replays, some concurrently and some at a different offset. Dedupe by the event id.
  • Record the event id in the same atomic step as the effect: one Lua script, one transaction with a unique constraint, or an effect that is idempotent by nature.
  • A record that will always fail goes to a dead-letter topic with its bytes and a reason; a store that is briefly down is retried, not dead-lettered.
  • Prove it by crashing between the effect and the commit, redelivering, replaying and racing two members, and checking the totals.

Practise it

31 steps start from a starter that hides this failure mode, in 29 courses.

Sources