Idempotency and retry handling

You make event handling safe under redelivery so the notifier can retry failed sends without creating duplicate notifications.

Learning outcomes

  • Explain why Kafka relay retries, consumer crashes and rebalances can deliver the same order event more than once.
  • Use event_id and processed_events to make notification processing idempotent.
  • Explain how a MySQL transaction coordinates deduplication, notification sending and notification storage.
  • Design retry and dead-letter handling that preserves records and allows the main consumer to keep processing.
  • Explain why committing Kafka offsets after processing prevents lost notifications during worker restarts.

When an order reaches ACCEPTED, the notifier must create a notification for every event associated with that order, including PLACED and ACCEPTED. The W3B6 relay publishes these events to Kafka, but Kafka can deliver the same event more than once. Your notifier must handle those repeated deliveries without creating duplicate notification rows or losing work when the worker crashes.

The delivery guarantee

Kafka provides at-least-once delivery. A consumer receives a record one or more times until its progress is committed. This guarantee favours preserving events over guaranteeing that every event is delivered exactly once.

There are several ways the notifier can receive an event again.

The relay can publish twice. W3B6 publishes an outbox row to order-events. Suppose it successfully publishes the record but crashes before marking the outbox row as published. After restarting, the relay sees the row as pending and publishes it again. Kafka receives two records representing the same logical event.

The consumer can process twice. Suppose the worker processes an event and commits its MySQL transaction. It then crashes before committing its Kafka offset. After restarting, Kafka delivers the event again because the group has not recorded that offset as completed.

A rebalance can cause another delivery. Kafka distributes partitions among members of a consumer group. When membership changes, a partition can move to another member. If the previous member processed a record without committing its offset, the new owner can receive that record again.

These are expected consequences of at-least-once delivery. Preventing every possible duplicate at the transport layer is not the consumer's responsibility.

Your responsibility is to make processing the same logical event more than once produce the same database result.

Identifying a logical event

Use event_id to identify an order event. Do not use the Kafka offset as the identity.

An offset identifies a record's position within a Kafka partition. When the relay publishes the same event again, Kafka assigns the new record a different offset. Both records still represent the same event from order_events.

The event payload contains a stable identifier:

json
{
  "order_id": 42,
  "event_id": "6f1c0e2a-8f4b-4d1e-9a51-2b7c3d4e5f60",
  "from": "PLACED",
  "to": "ACCEPTED"
}

Here, order_id identifies the order, while event_id identifies the particular transition event. An order can have several events, so deduplicating by order_id would incorrectly suppress later notifications.

For example, an order reaching ACCEPTED produces at least these two distinct events:

order_id: 42
event_id: event-placed
to: PLACED

order_id: 42
event_id: event-accepted
to: ACCEPTED

The notifier must process both events. If either event is published again, it must recognise the repeated event_id.

The processed-events table

Migration 0007 introduces processed_events. It stores an event ID for each successfully processed event. The event_id column must be the primary key so the same logical event cannot be recorded twice.

You can use MySQL's INSERT IGNORE to attempt to insert the marker.

sql
INSERT IGNORE INTO processed_events (event_id)
VALUES (?);

The result tells you whether this event is new.

  • One affected row means the marker was inserted.
  • Zero affected rows means the event ID already exists.

In Go, check the result rather than treating every successful SQL statement as a new event:

go
result, err := tx.ExecContext(ctx, query, eventID)
if err != nil {
    return err
}

inserted, err := result.RowsAffected()
if err != nil {
    return err
}
if inserted == 0 {
    return nil
}

A duplicate event should not trigger another notification. Returning without sending is safe only when the existing marker represents successfully completed processing.

That last condition matters. A marker must not survive a failed notification send.

Coordinating the database writes

The deduplication marker and notification row belong in the same MySQL Transaction. The send operation happens between the two database writes.

Migration 0007 also introduces notifications. Each notification must hold the event_id of the event that caused it, the customer's user_id, and the corresponding order_id. These are the columns the W3B7 tests inspect to verify that each event produces exactly one notification for the correct customer and order.

The processor needs to coordinate four operations:

  1. Insert the event_id into processed_events.
  2. Load the customer's user_id from orders.
  3. Send the notification.
  4. Insert the notification row into notifications.

Commit the transaction only when all four operations succeed.

The failure before sending

Consider inserting the marker in its own transaction before sending the notification.

Insert processed_events marker
Commit marker
Worker crashes
Notification is never sent
Event is delivered again
Marker already exists
Worker skips the event

The customer never receives the notification.

This is a lost notification. The worker has recorded successful processing even though the actual work did not finish.

The failure after sending

Now consider sending first and recording the marker afterward, in a separate transaction.

Send notification
Worker crashes
Marker was never recorded
Event is delivered again
Worker sends notification again

The customer receives a duplicate notification.

The problem is the gap between the side effect and the deduplication record. A crash in that gap leaves the worker unable to distinguish completed work from incomplete work.

The transaction boundary

A single database transaction coordinates the processed-event marker and notification row. A failed send causes the transaction to roll back, removing the uncommitted marker too.

The intended sequence is:

Begin MySQL transaction
Insert processed_events marker
Check affected rows
Skip if the event already exists
Load customer from orders
Send notification
Insert notifications row
Commit transaction

If loading the customer, sending, or inserting the notification fails, roll back the transaction.

This gives you an important property: the database cannot commit a processed-event marker without also committing its notification row.

The external side-effect boundary

A MySQL transaction cannot roll back an external notification provider. If a provider accepts a notification but the subsequent database commit fails, a redelivery can send that notification again.

The transaction in this exercise coordinates the database state and the send operation. The observable exactly-once requirement in W3B7 is one row in notifications per event. Extending that guarantee to an external push provider requires additional provider-side idempotency or delivery coordination.

This distinction matters when you move from the course's notification sender to a real notification service.

Processing duplicates safely

Once the processor has a transaction boundary, the Kafka worker can treat repeated deliveries as normal input.

Suppose the worker receives the same PLACED event four times. The first delivery inserts the marker, sends the notification, inserts the notification row and commits.

The remaining three deliveries attempt the same marker insert. MySQL ignores the duplicate primary key, and RowsAffected returns zero. The processor skips the send.

The resulting database state is:

event_id: event-placed
processed_events rows: 1
notifications rows: 1

The number of Kafka deliveries does not change the number of notification rows.

This is an idempotent consumer. Repeatedly processing the same logical input does not produce additional observable database effects.

Notice that idempotency is based on the event ID, not the order ID. A second event for the same order must still produce its own notification.

Committing Kafka offsets

The database transaction protects notification processing. Kafka offset management determines whether the event can be delivered again after a crash.

The worker should disable automatic offset commits. For each polled batch, it processes the records and commits the uncommitted offsets only after handling the batch.

The order of operations matters:

Poll Kafka records
Process each record
Commit database transactions
Handle forwarding where necessary
Commit Kafka offsets

A record must not be considered complete merely because the worker received it.

Consider a worker that commits its offset before processing the event:

Poll event
Commit offset
Worker crashes
Notification was never created
Kafka does not redeliver the committed record

The event is lost from the notifier's perspective.

Committing after processing gives you the opposite behaviour. If the worker crashes before the offset commit, Kafka can deliver the record again. The processed_events marker makes that repeated delivery harmless when the database transaction already succeeded.

Crash positions

There are three important points in the lifecycle.

Crash before the database transaction commits.

MySQL rolls back the incomplete transaction when the connection closes. Neither the processed-event marker nor the notification row is committed. Kafka has not received the offset commit, so the event can be processed again.

Crash after the transaction commits but before the offset commits.

The notification row and marker already exist. Kafka redelivers the record, but the processor detects the existing event_id and skips the notification. The worker can then commit the offset.

Crash after both commits.

MySQL contains the notification, and Kafka records the completed offset. The consumer resumes from its committed progress.

This is why the notification transaction and offset commit must be treated as two separate operations. Kafka and MySQL do not share a distributed transaction here. You rely on redelivery and database idempotency to bridge the gap.

Partition ownership

Kafka commits offsets independently for each partition. A consumer group's members own partitions, and each member must finish handling its polled records before allowing another member to take over those partitions.

In franz-go, kgo.BlockRebalanceOnPoll() prevents a rebalance while the worker handles the records returned by a poll. After processing and committing, the worker calls AllowRebalance().

This avoids unnecessary concurrent processing caused by a partition changing owners while its previous member is still handling records.

The important rule remains the same: never commit an offset for work that has not been handled.

Retry topics

Not every notification send succeeds on the first attempt. A provider can fail temporarily, or the notification sender can have failures injected through FAIL_EVERY.

Retrying the same record indefinitely on order-events creates a problem. Kafka preserves record ordering within a partition. If the consumer blocks on one failing record, later records in that partition cannot make progress through that consumer.

Move failed records to a separate retry topic instead.

The notifier uses two consumer groups:

  • notifier consumes order-events.
  • notifier-retry consumes order-events.retry.

Both groups use the same notification processor. This separation allows the main consumer to continue handling new order events while the retry consumer waits for previously failed events.

A retry record carries an attempt header. When a record has no valid positive attempt number, processing starts at attempt 1.

The retry policy has three total send attempts:

Send attemptResultDestinationattempt header
1Send failsorder-events.retry2
2Send failsorder-events.retry3
3Send failsorder-events.dlq3

The header identifies the next attempt when a record moves to the retry topic. When the third attempt fails, the record goes to the dead-letter topic with attempt=3, rather than being assigned a fourth attempt.

Retry timing

A retry topic does not automatically delay its records. A consumer must implement the waiting period.

The retry consumer uses the record timestamp and attempt number. Its delay is:

delay = attempt * 2 seconds
ready_at = record timestamp + delay

For an attempt 2 record, the consumer waits until the record timestamp plus four seconds. For an attempt 3 record, it waits until the record timestamp plus six seconds.

The timestamp belongs to the forwarded retry record. Each forwarding operation produces a new record with its own timestamp.

The retry consumer waits for that record to become ready. It does not make the main consumer sleep.

This is important because the main consumer and retry consumer have separate progress. A failed notification does not need to block new events arriving on order-events.

With FAIL_EVERY=2, some sends fail and travel through the retry topic with attempt=2. Later attempts can succeed, and each event must eventually have exactly one notification row.

With FAIL_EVERY=1, every send fails. The event reaches the retry topic with attempts 2 and 3, then reaches the dead-letter topic with attempt=3. No notification row is created for that event.

The retry and DLQ flow

The complete flow distinguishes successful processing, temporary failures and records that cannot be processed.

An event is consumed from order-events. A failed first send moves it to order-events.retry with attempt 2. The retry consumer waits four seconds before the second attempt. A second failure moves it back to the retry topic with attempt 3. The retry consumer waits six seconds before the third attempt. A third failure moves it to order-events.dlq with attempt 3. A successful send stores a notification and commits the database transaction.An event is consumed from order-events. A failed first send moves it to order-events.retry with attempt 2. The retry consumer waits four seconds before the second attempt. A second failure moves it back to the retry topic with attempt 3. The retry consumer waits six seconds before the third attempt. A third failure moves it to order-events.dlq with attempt 3. A successful send stores a notification and commits the database transaction.

A retry record is not a new logical event. Its payload retains the same event_id. That is what allows the processor to apply the same deduplication rule across the main topic and retry topic.

A failure during processing must not leave a committed marker behind. Otherwise, the retry consumer would see the marker and skip the event even though the earlier send failed.

The retry attempt must therefore begin with the same transaction logic as the original attempt.

Unreadable records

Not every Kafka record is a valid order event.

The notifier expects JSON containing the order event fields. Consider a record whose value is:

this is not an event

JSON decoding fails. There is no useful notification operation to retry because the worker cannot recover an event from that value.

Send this record directly to order-events.dlq. Preserve the original Kafka key and value so an operator can inspect the exact record that failed.

Do not send it to order-events.retry. A delay cannot correct malformed JSON.

The same principle applies to deciding whether a record is usable: validate the event before asking the processor to create a notification. Records that cannot be interpreted must not enter the normal notification flow.

The dead-letter topic

A dead-letter queue stores records that the normal processing path cannot handle successfully. In this project, the dead-letter queue is implemented as the Kafka topic order-events.dlq, also called the dead-letter topic.

There are two paths into it:

  • An unreadable event goes directly to the dead-letter topic.
  • A valid event that fails all three notification attempts goes there after attempt 3.

The original key and value should remain available. The forwarded record also carries an attempt header and a reason header to explain why it was moved.

You can inspect the topic with:

bash
rpk topic consume order-events.dlq -n 10

The records give an operator enough context to identify the failed order event and investigate the cause.

A dead-letter topic is not a substitute for fixing failures. It keeps the failed records out of the main processing path while preserving them for investigation and possible replay.

Forwarding before committing

Forwarding a record is another Kafka produce operation. It can fail.

For example, the worker may attempt to produce a failed event to order-events.retry, but the destination topic may be unavailable. A failed produce means the worker has not successfully preserved the record at its next destination.

If the worker commits the original offset anyway, Kafka will consider the original record handled. The event will exist neither in a successful notification nor in the retry topic.

The correct rule is to treat forwarding as part of handling the original record.

Receive original record
Determine retry or DLQ destination
Produce forwarded record
Check produce result
Commit original offset only after successful forwarding

If producing to the retry topic or dead-letter topic fails, do not commit the original offset. Stop processing the failed batch and allow Kafka to deliver the original record again after a restart.

This rule applies to both unreadable records and events whose notification sends have failed.

A successful notification transaction and a successful forwarding operation are different completion paths, but both must finish before the original offset can be committed.

Exactly once in effect

The notifier does not prevent Kafka from delivering duplicates. It makes repeated deliveries produce one committed notification row for the same logical event.

That is exactly once in effect:

  • Kafka provides at-least-once delivery.
  • MySQL uses processed_events.event_id to detect duplicates.
  • One transaction coordinates the processed-event marker and the notification row.
  • Kafka offsets are committed only after the record has been handled.
  • Failed sends are retried, while unreadable and exhausted events are preserved in the dead-letter topic.

The distinction between delivery and effect is important. Kafka can deliver an event four times, but the database should still contain one notification row for its event_id.

The W3B7 crash test makes this concrete. It creates 30 orders, waits until a notification exists for the third collected event, kills the worker with SIGKILL, and starts it again. Every event must eventually have exactly one notification row.

Some records might be delivered again after the restart. That is expected. The database marker prevents successful work from being applied twice, while uncommitted work remains eligible for processing.

The notifier's processing boundary

The next exercise, Notifier worker with retries and DLQ, combines these ideas in cmd/worker.

The processor owns the MySQL transaction and the notification decision. The Kafka consumers own polling, retry timing, forwarding and offset management.

Keep the boundaries clear. A duplicate event is a successful no-op. A failed send is eligible for another attempt. An unreadable event goes directly to the dead-letter topic. A record is not complete until its processing or forwarding operation has succeeded.

These rules let the notifier keep processing new events without losing notifications when a worker crashes or an individual record repeatedly fails.

Check your understanding

Question 1 of 4

The W3B6 relay publishes the same order_events row twice after restarting. Kafka assigns the two records different offsets. Which value should the notifier use to recognise that they represent the same logical event?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (franz-go v1.22, Redpanda, MySQL 8.4).

Finished Lesson 3.16?