Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 2

Delivery guarantees and idempotent consumers

Find the two places where a message can be lost or delivered twice, see at-most-once, at-least-once and idempotent processing side by side in a small simulation with one crash, and learn the techniques that make a consumer safe to run twice, including what broker transactions can and cannot cover.

Contentsand lesson path

What you will learn

  • Choose delivery semantics (at-most-once, at-least-once, effectively-once) and make consumers idempotent.

01. Why it matters

Networks drop packets, processes crash and machines restart. A messaging system cannot make those events impossible; it can only decide what happens to a message when one occurs. Either the message may be lost, or it may arrive more than once. A system that promises neither, under every kind of failure, does not exist. What you can build is a pipeline where a duplicate has no extra effect, so that the result is as if each message were processed once.

These choices have names, and you will meet them in every broker's documentation:

  • At-most-once: a message is never processed twice, but may be lost.
  • At-least-once: a message is never lost, but may be processed more than once.
  • Exactly-once: each message has its effect once. In practice this is built from at-least-once delivery plus deduplication, so many engineers prefer the term effectively-once.

For a metrics sample, losing one value in a million may be fine. For a payment, a lost message is a missing charge and a duplicate is a double charge. This lesson shows where each outcome comes from and how to design a consumer that tolerates duplicates.

02. Two places where things go wrong

The first gap is between the producer and the broker. The producer sends a message and waits for an acknowledgement. If the acknowledgement is lost on the way back, the producer cannot tell whether the broker stored the message, so it retries, and the broker may now hold two copies. Kafka solves this half with the idempotent producer: the broker gives each producer an id, the producer numbers its messages, and the broker discards a retried message whose sequence number it has already written. Two defaults matter here. The Java client turns idempotence on by default (with acks=all, meaning all in-sync replicas must store the message before the acknowledgement). The C library librdkafka, used by the Python, Go and .NET clients, keeps enable.idempotence=false by default, so you set it yourself. Producer idempotence covers retries of one producer session; it does not stop your application from sending the same business event twice.

The second gap is between the broker and the consumer. A consumer does two things for each message: it does the work (writes to a database, calls an API) and it commits its offset, which tells the broker "I am done up to here". These are two separate systems, so there is always a moment between the two steps when a crash can happen. The order of the steps decides the outcome:

  • Commit first, then work: a crash between the steps skips the message. That is at-most-once.
  • Work first, then commit: a crash between the steps repeats the message after restart. That is at-least-once.

03. One crash, three strategies

The script below replays the same four messages three times. A list stands in for the broker's log and a variable for its committed offset; the balances live in SQLite, as the consumer's database would. Each strategy crashes once at offset 2, between its two steps, and then restarts from the committed offset. The third strategy adds a processed table: the message id and the balance change are written in the same database transaction, so either both are stored or neither is. Save the file and run it; it needs only Python 3.9 or newer.

Python · delivery.py
"""One crash, three commit strategies. LOG and `committed` stand in for the broker;
the SQLite tables are the consumer's own database."""
import sqlite3

LOG = [("m1", "acct-1", 50), ("m2", "acct-2", 20), ("m3", "acct-1", 30),
       ("m4", "acct-2", 10)]                     # (message id, account, amount)
CRASH_AT = 2                                     # crash once, between the two steps


def apply(db, strategy, msg_id, account, amount):
    with db:                                     # one database transaction
        if strategy == "idempotent":
            new = db.execute("INSERT OR IGNORE INTO processed VALUES (?)",
                             (msg_id,)).rowcount == 1
            if not new:
                return                           # effect already stored: skip
        db.execute("INSERT INTO balances VALUES (?, ?) ON CONFLICT (account) "
                   "DO UPDATE SET total = total + excluded.total", (account, amount))


def run(strategy):
    db = sqlite3.connect(":memory:")
    db.execute("CREATE TABLE balances (account TEXT PRIMARY KEY, total INT)")
    db.execute("CREATE TABLE processed (message_id TEXT PRIMARY KEY)")
    committed, crashed = 0, False                # committed = next offset to read
    while committed < len(LOG):
        offset = committed
        msg = LOG[offset]
        crash_now = offset == CRASH_AT and not crashed
        if strategy == "commit-first":
            committed = offset + 1               # step 1: commit the offset
            if crash_now:
                crashed = True
                print(f"  crash before the work; restart at offset {committed}")
                continue
            apply(db, strategy, *msg)            # step 2: do the work
        else:
            apply(db, strategy, *msg)            # step 1: do the work
            if crash_now:
                crashed = True
                print(f"  crash before the commit; restart at offset {committed}")
                continue
            committed = offset + 1               # step 2: commit the offset
    rows = db.execute("SELECT account, total FROM balances ORDER BY 1").fetchall()
    print(f"  final balances: {rows}")


for name in ["commit-first", "commit-after", "idempotent"]:
    print(name)
    run(name)
print("correct: [('acct-1', 80), ('acct-2', 30)]")
Terminal
python3 delivery.py
Expected output
commit-first
  crash before the work; restart at offset 3
  final balances: [('acct-1', 50), ('acct-2', 30)]
commit-after
  crash before the commit; restart at offset 2
  final balances: [('acct-1', 110), ('acct-2', 30)]
idempotent
  crash before the commit; restart at offset 2
  final balances: [('acct-1', 80), ('acct-2', 30)]
correct: [('acct-1', 80), ('acct-2', 30)]

With commit-first, the offset moved past message m3 before its work ran, so the restart began at offset 3 and acct-1 never received its 30: a silent loss. With commit-after, the work for m3 was stored but the offset was not, so the restart processed m3 again and acct-1 received 30 twice. The idempotent strategy restarted at the same place, but the second attempt found m3 in processed and skipped it, so the balances are correct. The crash still happened and the message was still delivered twice; only its effect was kept to one.

04. Making a consumer safe to run twice

An operation is idempotent when doing it twice has the same effect as doing it once. Some handlers are idempotent by nature: "set order 42's status to shipped" or an upsert keyed by order id can run any number of times. Others are not: "add 30 to the balance", "insert a new row with a generated id", or "send an email". For those you add one of these techniques:

  • A deduplication table. Store a unique message id, as above, in the same transaction as the effect, with a unique constraint so that two concurrent attempts cannot both succeed. Keep the ids at least as long as a duplicate can still arrive: longer than the topic's retention if anyone may replay it.
  • A version check. Store the last applied sequence number or log position per key and ignore anything older. This also protects against an old message that arrives after a newer one.
  • An idempotency key for external calls. You cannot put a card payment and a database insert in one transaction. Many APIs, such as Stripe's, accept an idempotency key: if you call twice with the same key, the second call returns the first result instead of charging again. Use the message id as the key.

The id must come from the producer and travel with the message. An id that the consumer generates on arrival is different on every redelivery and catches nothing.

05. What broker transactions cover

Kafka also offers transactions for the read-process-write pattern: a job reads from one topic, writes results to other topics, and commits its input offsets, all in one transaction. Consumers that read with isolation.level=read_committed see the results only if the transaction committed. Kafka Streams uses this when you set processing.guarantee=exactly_once_v2. Note the defaults again: the Java consumer reads read_uncommitted unless you change it, while librdkafka defaults to read_committed.

The guarantee stops at Kafka's edge. Anything the job does outside Kafka, such as writing to a database without a dedupe key, calling an HTTP API or sending an email, is not part of the transaction and can still happen twice when the transaction is retried. For those, use the idempotency techniques above, or the transactional outbox pattern: write the side effect as a row in your database in the same transaction as your data, and let a separate relay publish or perform it, idempotently.

06. Check your understanding

Practice check · 3 questions

Duplicates and losses

Use the simulation and the techniques above.

Q1. You change `CRASH_AT` to 3 in `delivery.py` and run it again. What does the commit-after strategy print as its final balances?
Q2. Which handler can process the same shipping event twice with no dedupe table and still leave correct data?
Q3. A consumer calls a payment API, then records the charge in its database and commits the offset. After a crash right after the API call, the card is charged twice. What is the best fix?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the order-event consumer in the skill practice, write down which delivery semantics each effect needs and how you will make it idempotent. A good answer names the message id the producer will set, the table and unique constraint that store it, how long the ids are kept compared with topic retention, and how any external call (payment, email) avoids repeating. You will build this consumer in the lab of lesson 4.

08. Review prompt

Without looking back, explain: the difference between at-most-once, at-least-once and effectively-once; the two gaps where messages are lost or duplicated; what the idempotent producer prevents and what it does not; why the order of "work" and "commit" matters; three ways to make a handler idempotent; and why a Kafka transaction does not cover an email sent by the job.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check