Delivery guarantees
Part of the free LogicWiz Data Engineering course, Module 15: Streaming. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:00 on Monday. Tess has Sunday's live revenue next to the bank's figure, and the live number is $1,840 too high. During Sunday's deploy the payments consumer was restarted half-way through a batch, and 14 payments were counted twice. A quick fix goes in by lunch: commit first, then write. On Tuesday the number is wrong the other way: 3 payments are missing. Nora says there is a third way.
You'll learn to
- Show how the order of write and commit loses or repeats messages
- Make a sink idempotent, so a replay cannot double count
- Explain what the idempotent producer and transactions do, and where they stop
- Ignore stale updates with a version
Learn
Two steps, and a crash between them
For every batch, the payments consumer does two things. It writes the payments to the revenue ledger (the place a job writes to is called its sink). It commits its offset, which tells Kafka "I have finished up to here".
These are two separate steps, and a crash can land between them. After a restart, the committed offset is the only thing the new consumer knows. It starts reading there.
On Sunday the order was: write, then commit. Take a small version of it. Six payments are in the topic. The consumer writes four of them, and the deploy restarts it before the commit.
Write, then commit: Sunday's crash
A topic of six payments, a consumer and a ledger: the consumer writes four payments, crashes before committing, restarts from offset 0 and writes all six, leaving ten rows in the ledger.
Poll. The consumer asks for up to four payments and gets offsets 0 to 3. Nothing is written or committed yet.
Write. It adds the four payments to the ledger: $120 so far.
Crash, before the commit. The deploy restarts the consumer. The ledger keeps its four rows. Kafka still says: committed offset 0.
Restart. The new consumer asks Kafka where to begin. The answer is the committed offset, 0, so it receives all six payments.
Write again, then commit. Six rows go in, four of them for the second time. The ledger says $290. The truth is $170.
Keep your eye on "committed offset" under the topic: it is the only memory that survives the crash. Everything after it is read again.
Sunday for real: write, then commit, and crash in between
import ministream as ms
broker = ms.Broker()
broker.create_topic('payments', partitions=1)
amounts = [20, 35, 50, 15, 40, 10]
for i, amount in enumerate(amounts):
broker.produce('payments', None, {'payment_id': 5001 + i, 'amount': amount})
ledger = [] # the sink: rows we wrote
c = broker.consumer('revenue', 'payments')
for m in c.poll(max_records=4):
ledger.append(m.value) # 1. process: write the row
c.crash() # 2. dies before c.commit()
c = broker.consumer('revenue', 'payments') # the restarted consumer
for m in c.poll():
ledger.append(m.value)
c.commit()
print([row['payment_id'] for row in ledger])
print('revenue', sum(row['amount'] for row in ledger), 'true revenue', sum(amounts))
Nothing was lost: every payment reached the ledger. But the four written before the crash were written again, and revenue reads 290 against a true 170.
The quick fix loses money instead
Write-then-commit never skips a message, but it can repeat some. That promise has a name: at least once.
The quick fix swapped the two steps: commit, then write. Now a crash between them cannot repeat anything. It does something worse. The committed offset already says "done", so the restart begins after the batch, and those payments are never written. That promise is at most once: no duplicates, possible losses.
Losing data quietly is usually worse than duplicating it. Duplicates can at least be found and removed.
Commit, then write: Tuesday's crash
The same topic, consumer and ledger: the consumer commits offset 4 before writing, crashes, restarts from offset 4 and writes only the last two payments, so four payments never reach the ledger.
Poll. The same start: offsets 0 to 3 arrive.
Commit first. The consumer tells Kafka it has finished four payments. It has written none of them.
Crash, before the write. The four payments are in no ledger, and Kafka believes they are done.
Restart. The new consumer starts at the committed offset, 4, writes the last two payments and commits. Payments 5001 to 5004 are never read again: $120 gone, and no error anywhere.
Same three boxes as before. Only the order of the two steps changed, and the mistake moved from "twice" to "never".
Tuesday for real: commit, then write, and crash in between
import ministream as ms
broker = ms.Broker()
broker.create_topic('payments', partitions=1)
for i, amount in enumerate([20, 35, 50, 15, 40, 10]):
broker.produce('payments', None, {'payment_id': 5001 + i, 'amount': amount})
ledger = []
c = broker.consumer('revenue', 'payments')
batch = c.poll(max_records=4)
c.commit() # 1. commit first
c.crash() # 2. dies before writing anything
c = broker.consumer('revenue', 'payments')
for m in c.poll():
ledger.append(m.value)
c.commit()
print([row['payment_id'] for row in ledger])
No duplicates, and 5001 to 5004 are gone for good: the ledger holds only 5005 and 5006.
A topic with three partitions and a consumer group whose consumers can poll, process and commit, crash before committing, or commit first and then crash, showing which messages are processed twice and which are skipped.
Try both crashes yourself. Press "Process, crash before commit" and then a normal poll: the batch is processed twice. Then try "Commit first, then crash": the batch is skipped for good.
Make the second attempt harmless
You cannot choose when the crash comes. Nora's rule: stop trying to process each message once. Make processing it twice change nothing.
So keep the safe order, write then commit, and fix the ledger. A write you can repeat without changing the result is idempotent (Lesson 6.3). The third promise, exactly once, means the effect of each message happens once. In practice that is at-least-once delivery plus an idempotent sink. Two ways to build one:
- Upsert by a unique id. Every payment has a
payment_id, every event anevent_id. Write withINSERT ... ON CONFLICT (payment_id) DO NOTHINGor aMERGE, and a replay rewrites the same rows. - Store the offsets with the output, in the same database transaction. On restart, read them back and
seekto them (start reading there). Output and progress can then never disagree.
The same crash, with an idempotent sink
CREATE TABLE revenue_sink (
payment_id INT PRIMARY KEY,
amount NUMERIC(10,2) NOT NULL
);
-- the first attempt wrote 4 payments, then crashed before the commit
INSERT INTO revenue_sink VALUES (5001, 20), (5002, 35), (5003, 50), (5004, 15)
ON CONFLICT (payment_id) DO NOTHING;
-- the restarted consumer replays from offset 0: all 6
INSERT INTO revenue_sink VALUES (5001, 20), (5002, 35), (5003, 50), (5004, 15), (5005, 40), (5006, 10)
ON CONFLICT (payment_id) DO NOTHING;
SELECT COUNT(*) AS payments, SUM(amount) AS revenue
FROM revenue_sink;
Six payments, $170: the replay changed nothing. Remove the two ON CONFLICT lines and the second insert fails on the primary key; remove the key as well and revenue becomes $290.
Remember: exactly once = at-least-once delivery + a sink where twice changes nothing. Commit after the write, never before.
The same doubt, one hop earlier
You have felt this doubt yourself. You press Pay and the page freezes. Did it go through? Press again and you may pay twice.
A producer has the same problem when a reply is lost: it must retry, and the retry can write the message twice. Kafka's answer is the idempotent producer (enable.idempotence=true, the default since Kafka 3.0). The broker gives each producer an id, and the producer numbers every batch, per partition, with a sequence number. The leader remembers the last number it wrote for each producer:
- the next number: append
- a number already written: answer "done", write nothing
- a gap: refuse, with
OutOfOrderSequenceException
This covers one producer session only. A restarted producer gets a new id, so an application that resends after a restart writes a new message.
A retry, without and with sequence numbers
A producer and a partition leader exchange messages: a lost reply makes a plain retry write a payment twice, a sequence number lets the leader skip the repeat, and a refused out-of-order batch keeps two batches in order.
A reply gets lost. The leader writes batch A and answers, but the answer never arrives. The producer cannot tell "not written" from "written, reply lost".
The retry, with no numbers. The producer sends A again, as it should. The leader has no way to know it is a repeat, so payment 5001 is now in the log twice.
The retry, with sequence numbers. Now batch A carries the number 7. The leader remembers that 7 is the last number it wrote for this producer. Seeing 7 again, it answers "done" and writes nothing.
The numbers keep order too. Two batches are in flight and A fails. Without numbers, B would be written and the retried A would land after it. With them, the leader refuses B, because 8 is not the number it expects, and the producer resends both in order.
Read each step top to bottom. Solid arrows are requests, dashed arrows are replies. Out-of-order retries matter when batch A says 1001 shipped and batch B says 1001 delivered: B then A would leave the order on a stale status.
Read, write and commit as one
Some jobs read from Kafka and write back to Kafka: read payments, write the big ones to big_spend. The crash can still fall between writing the output and committing the input offsets.
Kafka closes that gap with a transaction: the output records and the input offsets are committed together, or not at all. The producer gets a transactional.id and talks to a broker that acts as transaction coordinator.
One more danger: a crashed job that is still half alive and still writing, a zombie. Each time a producer with the same transactional.id starts, the coordinator raises its epoch, a counter. Writes carrying an older epoch are refused. That is called fencing.
One transaction, seen by a careful reader
A producer registers with the transaction coordinator, writes three records to the output partition and commits; the coordinator writes a commit marker into the partition, and only then does a read_committed consumer receive the three records.
Register.
init_transactions(): the coordinator raises this producer's epoch to 5. A zombie still running with epoch 4 is now fenced, and anything it left open is aborted.Write.
begin_transaction(), then the sends. The coordinator notes which partitions the transaction touches, and three records land at offsets 120 to 122.A careful reader waits. A consumer with
isolation.level=read_committedfetches, and gets nothing past offset 119: the transaction is still open.Commit, input offsets included.
send_offsets_to_transaction()puts the consumer's offsets into the same transaction, thencommit_transaction(). The coordinator first records its decision, PREPARE_COMMIT, in its own log.The marker lands. The coordinator writes a commit marker into every partition the transaction touched: here, at offset 123. Only now does the careful reader get 120 to 122.
Each step adds rows at the bottom. The marker takes an offset of its own but is never handed to your code, so offsets in a transactional topic have gaps.
A retry, with and without numbers; then a transaction that crashes
import ministream as ms
broker = ms.Broker()
broker.create_topic('payments', partitions=1)
plain = broker.producer() # idempotence off
plain.send('payments', '5001', 20, lose_ack=True) # written, reply lost, sent again
safe = broker.producer(idempotent=True)
safe.send('payments', '5002', 35, lose_ack=True) # the broker drops the retry
print([(m.offset, m.key, m.value) for m in broker.messages('payments', 0)])
broker.create_topic('big_spend', partitions=1)
reader = broker.consumer('flagger', 'payments')
tx = broker.producer(transactional=True)
tx.begin()
for m in reader.poll():
if m.value >= 30:
tx.send('big_spend', m.key, m.value)
reader.crash() # dies before tx.commit()
print('after the crash:', broker.messages('big_spend', 0), broker.committed_offset('flagger', 'payments', 0))
reader = broker.consumer('flagger', 'payments') # restarted
tx = broker.producer(transactional=True) # Kafka aborts the old open transaction
tx.begin()
for m in reader.poll():
if m.value >= 30:
tx.send('big_spend', m.key, m.value)
tx.commit(reader) # output and input offsets together
print('after the retry:', [m.key for m in broker.messages('big_spend', 0)], broker.committed_offset('flagger', 'payments', 0))
The first line: the plain producer wrote 5001 twice, the idempotent one wrote 5002 once. Then the transaction: the crash left no output and no commit, so the retry did the whole job once. One flagged payment, input offset at 3.
What a careful reader pays
A transaction only helps readers that respect it. A consumer set to isolation.level=read_committed (the default is read_uncommitted) never sees aborted records. It also never reads past the first message of the oldest transaction still open on that partition. That point is called the last stable offset (LSO). Everything after it waits, even messages from producers that use no transactions.
So transactions add delay. A job that commits every 2 seconds holds its output back for up to 2 seconds. And one stuck producer stalls every read_committed reader of its partitions, until the coordinator aborts its transaction after transaction.timeout.ms (60 s).
The symptom: a sawtooth, or a 60-second plateau, in the lag of read_committed groups, while a read_uncommitted group on the same topic stays near zero.
The whole loop with the real confluent-kafka client
Runs on a Kafka cluster:
import json
from confluent_kafka import Consumer, Producer
consumer = Consumer({
'bootstrap.servers': 'broker:9092',
'group.id': 'flagger',
'enable.auto.commit': False,
'isolation.level': 'read_committed',
})
producer = Producer({
'bootstrap.servers': 'broker:9092',
'transactional.id': 'flagger-1', # turns on idempotence as well
})
consumer.subscribe(['payments'])
producer.init_transactions() # aborts what a crashed flagger-1 left open
while True:
batch = consumer.consume(num_messages=100, timeout=1.0)
if not batch:
continue
producer.begin_transaction()
for msg in batch:
if json.loads(msg.value())['amount'] >= 500:
producer.produce('big_spend', key=msg.key(), value=msg.value())
producer.send_offsets_to_transaction(
consumer.position(consumer.assignment()),
consumer.consumer_group_metadata())
producer.commit_transaction()
print(f'committed {len(batch)} payments')
committed 100 payments
committed 100 payments
committed 37 payments
Find three lines: isolation.level on the consumer, transactional.id on the producer, and send_offsets_to_transaction, which commits the input offsets inside the same transaction as the output. Error handling (abort on failure) is left out to keep it short.
Old news must not overwrite new
One problem is left. Kafka keeps order inside a partition, but order still breaks around it. A replay after a crash re-sends old messages. A late event arrives after a newer one. A sink written by several consumers sees changes in any order.
So a sink that keeps the latest state must not blindly apply the last message it receives. Give every change a version: an updated_at, a sequence number, or the source database's log position. Apply a change only if its version is newer than the one stored:
ON CONFLICT (order_id) DO UPDATE ... WHERE EXCLUDED.updated_at > order_status.updated_at
Then late, replayed and duplicate updates are all harmless.
Exactly once, hop by hop
| Hop | What goes wrong | What makes it once |
|---|---|---|
| Producer to broker | a retry after a lost reply writes twice, or lands out of order | idempotent producer (default since 3.0) with acks=all |
| Broker storage | the leader dies before followers copy | replication factor 3, min.insync.replicas=2, no unclean election (Lesson 15.5) |
| Kafka to Kafka | a crash between writing output and committing input | transactions with sendoffsetstotransaction, readers on readcommitted |
| Kafka to a database or files | a crash between the write and the offset commit | an idempotent sink: upsert on a unique id, or offsets stored in the same database transaction |
| Kafka to Delta with Spark | a crash in the middle of a micro-batch | the checkpoint plus Delta's idempotent batch commit (Lesson 15.6); for other sinks, foreachBatch with a MERGE on the event id |
| Updates to one key | replays and late changes arrive out of order | apply a change only if its version is newer |
Read it top to bottom, in the direction the data travels. A pipeline is exactly-once only if every hop is: the weakest hop decides. (Flink gets there with two-phase commit, for sinks that support it.)
"Our pipeline is exactly-once" is usually only half true. Turning on idempotence and transactions protects what happens inside Kafka. A consumer that writes to Postgres and then commits its offset is still at-least-once into Postgres. Ask where the output goes, and check that the write there is an upsert on a real unique id.
Numbers to remember
| Setting | Default | What it does |
|---|---|---|
| enable.idempotence | true since Kafka 3.0 | producer id, epoch and sequence numbers; needs acks=all (wait for every in-sync copy, Lesson 15.5), retries, and max.in.flight.requests.per.connection of 5 or less |
| max.in.flight.requests.per.connection | 5 | batches in flight on one connection; with idempotence, order holds for any value up to 5. The old cure for reordering was 1, at a cost in throughput |
| Two version traps | 3.0.0 and 3.1.0 | a bug left the default off (fixed in 3.0.1, 3.1.1 and 3.2.0); and a conflicting value such as acks=1, without asking for idempotence, turns it off silently |
| transactional.id | not set | turns on transactions, and idempotence with them; the coordinator is the broker leading the partition of transactionstate that the id hashes to |
| transaction.timeout.ms | 60 s | a transaction left open longer than this is aborted |
| isolation.level | readuncommitted | readcommitted hides aborted records and stops at the last stable offset |
| A commit, inside the coordinator | PREPARECOMMIT, markers, COMPLETE | it logs the decision, writes a commit marker (a control record) into every partition involved, then logs that it is complete |
| Kafka 4.0 (KIP-890) | epoch bumped on every transaction | a delayed write from one transaction cannot land in the next |
What changed at SwiftKart
The payments consumer goes back to write-then-commit, and the revenue ledger gets payment_id as its primary key with ON CONFLICT DO NOTHING. You replay Sunday on purpose. The 14 payments arrive a second time and the total does not move: the extra $1,840 is gone. Tuesday's 3 missing payments come back by replaying from an earlier offset, which is safe now.
The order-status table gets the version check, so a late shipped can no longer overwrite delivered.
One number from the flash sale is still unexplained. The live dashboard showed 1 cart between 09:15 and 09:30, and the next morning's batch report said 3. No crash, no duplicate. Two events were late. That is the next lesson.
In one line
Write first and commit after (at least once), make the sink idempotent with an upsert on a unique id, and apply a change only if its version is newer: that is exactly-once in practice.
Interview corner
How do you load from Kafka into a database without duplicates?
Delivery stays at-least-once, committing offsets only after the write, and I make the write idempotent: each event has a unique id and the sink upserts on it, with INSERT ... ON CONFLICT DO NOTHING or a MERGE, so a replay rewrites the same rows. Another option is to store the consumer offsets in the same database transaction as the data and seek to them on restart, so output and progress can never disagree. Kafka transactions do not help here, because they end at Kafka.
How does the idempotent producer work, and what does it not cover?
The broker assigns the producer an id and epoch, and the producer numbers each batch per partition. The leader tracks the last sequence numbers per producer and partition: a repeat is acknowledged without being written, a gap is rejected as out of order, so retries neither duplicate nor reorder, with up to 5 requests in flight. It has been the default since 3.0, needs acks=all, and is silently disabled by a conflicting setting such as acks=1 unless you enable it explicitly. It covers only one producer session and only the hop into Kafka: a restarted producer has a new id, and a database sink still needs its own idempotent write.
What happens when a transactional producer hangs halfway through a transaction?
Its records are already in the partitions, but no commit marker follows, so the last stable offset stays at the start of the open transaction. Every read_committed consumer of those partitions stops there, even for other producers' messages, while read_uncommitted consumers carry on. After transaction.timeout.ms, 60 seconds by default, the coordinator aborts the transaction and writes abort markers, and read_committed readers skip the aborted records and catch up. A restarted instance with the same transactional.id fences the old one by bumping the epoch in init_transactions.
How do you handle out-of-order updates in a streaming sink?
I carry a version on every change, such as updated_at or the source log position, and apply an update only if it is newer than what the sink holds. In SQL that is an upsert with WHERE EXCLUDED.updated_at > target.updated_at. Then late, replayed and duplicate changes cannot move a row backwards.