Kafka: Why Exactly Once Can Send Two Emails
Outline
- 0:00 One result, two acceptances
- 0:51 One input, separate state
- 1:50 Producer retry versus repeating work
- 2:52 Pending progress and Kafka commit
- 4:00 Crash after receiver acceptance
- 4:43 Recovery rereads the input
- 5:51 Two views of the output log
- 6:36 Call before or after commit?
- 7:19 Receiver crashes around its local commit
- 8:44 Requests, effects and operation identity
- 9:45 Name each commit boundary
Transcript
0:00 Kafka stores streams of events so applications can process them and resume after failures. We'll trace its exactly-once guarantee through a crash, then close the gap around an outside action. In our crash test, Kafka exposed one committed result, but the email request was accepted twice. That sounds like a broken promise. Yeah, it sounds broken until we name which state Kafka owns. Our example uses a mock welcome-message receiver, so we can count accepted effects without sending real email. And we actually crashed the application against Kafka 4.4.
0:33 Apache's producer and consumer contracts, source code, and our test support the explanation. Links are in the description. Then if the event was processed exactly once, why did the receiver accept the welcome operation twice? Let's track input progress, Kafka's output, and the receiver's acceptance separately. First, give that operation a place to start: one signup event in an input topic. A topic is a named stream split into partitions, each an ordered log. Each record has an offset, its position in that log.
1:05 Our test starts at position 0. A handler reads it and prepares a welcome action named welcome-001. Then it writes a processed result to an output topic and calls the outside receiver. The receiver records that it accepted the operation. So the output record says processing finished, but that record isn't the receiver's effect. They're separate pieces of state in separate systems. Exactly. And the consumer group, the set of workers sharing this input, saves where to resume. After processing 0, its next position should be one.
1:38 I think a saved one looks deceptively like a completed-message count. It's a resume position, not proof of what happened outside. Right. Let's start with what Kafka recognizes on a resend. Before the transaction, take a smaller retry. The producer, our client writing records to Kafka, sends a batch. Kafka accepts it, but the acknowledgement gets lost. The producer sends again. With idempotence enabled, Kafka can recognize that producer retry and avoid appending the batch twice. But suppose our application runs the signup handler again and explicitly sends another result. Does Kafka recognize the same customer action?
2:15 No. Producer idempotence doesn't inspect the business meaning of two application sends. Those can be separate legitimate records, even if their contents look alike. Ah, so retransmitting a batch and executing our handler again need different explanations. A retry at one layer doesn't define identity at another. Yeah. Think of retransmitting one numbered shipment versus placing another identical order. Two boxes of the same item don't prove one order was duplicated. That keeps the guarantee useful without giving it mind-reading powers.
2:47 We still need to connect the handler's result to its saved resume position. So a Kafka transaction makes a shared decision for that output and next input position: commit both, or abort both. Our signup is record 0. We write its result and ask Kafka to include next position 1 in that transaction. When that request returns, can a restart already resume at one? No, it's still pending. Send offsets to transaction only stages that position. Committing the transaction saves it with the output. We've turned off automatic position commits and don't commit positions separately.
3:22 Otherwise, progress could run ahead of the output. On restart, we'd skip a signup whose output is missing. Commit the result first and crash before saving progress, and recovery can repeat it. Like sealing the result and resume point in one envelope, rather than two separate deliveries: accept both, or neither. But can the output already be stored before that decision? Yes. Stored isn't the same as committed. A committed-only reader waits for the transaction's outcome; a successful send doesn't settle it.
3:53 Okay, let's unpack this with a crash. Stop the process after those successful steps, while there's still a decision left to make. Now run that transaction up to the crash window. Our first attempt gets its output acknowledged, stages input position 1, and receives the mock service's acceptance. That success reply for welcome-001 is already back. We halt the Java process before committing Kafka. What can Kafka undo once the receiver has finished? Kafka can resolve its own transaction. This receiver isn't part of that decision, so Kafka cannot remove the receiver's accepted effect.
4:28 Our receiver database records one request and one effect from that first attempt. Its transaction already completed before the application stopped. So the receiver is finished, and Kafka still has a decision pending. Let's see what recovery makes of that. Now check what that crash left: one acceptance was recorded at the receiver. Kafka hadn't committed its output, and we found no saved resume point. Does the handler end up reading zero again? It did. We restarted with the same transactional ID, its stable name for Kafka recovery.
4:59 Kafka resolved the unfinished transaction before the handler reread 0. Oh, right. Exactly-once processing can't mean the handler only executes once. The execution happened twice in our test. Yeah. Kafka had held next position 1 aside, then discarded it when aborting the old transaction. Recovery wrote another result, called the receiver again, and committed its new Kafka transaction. When that retry committed, Kafka saved one as the group's resume point. The committed reader returned one result, while the receiver had accepted twice.
5:31 Does the retry keep welcome-001 at the receiver too, or does restarting create another operation name? It keeps that key. The transactional ID names the producer across restarts; the request key identifies our welcome operation. One sender, many numbered orders. Retrying keeps the same order number. With recovery complete, compare the output views. Our read-committed consumer returns one record. An uncommitted reader returns two, including the aborted attempt. Think of two submitted drafts versus the one approved edition.
6:03 Wait, the rejected draft can still be on the desk? How does one reader skip it? That reader setting is called read committed. Kafka's consumer code skips data from aborted transactions. Read uncommitted can expose those transactional records regardless of their eventual commit outcome. That's why we compared both views of the same output log. Ordinary, nontransactional records appear in either view. The filter is about whether a transaction committed, rather than deleting the earlier write. Right. Selecting an approved Kafka result still can't undo either receiver acceptance. So a reviewer could say, 'Fine, commit Kafka first and call the receiver afterward.'
6:41 That removes our particular duplicate window, doesn't it? It changes the window. Imagine the process commits position 1, then dies before making the outside call. That input may never trigger the call. So putting the receiver before commit risks repetition; putting it afterward can risk omission. Those are still separate deliveries: Kafka's commit can finish while the remote service is never called. But couldn't we publish the welcome command to another Kafka topic and make that handoff safe? That makes the queued command durable.
7:11 Its final consumer still has to call the receiving service. That service needs a way to recognize this same operation on retry. So the receiver must recognize this operation. Our repair stores its unique key with the modeled effect in one SQLite transaction. But storing a key isn't enough. What if the receiver dies between recording that key and performing the effect? We tested that. After inserting the key, we killed the receiver process before inserting the effect or committing. A fresh database connection found neither record.
7:41 Oh, even the key hadn't survived. It was still uncommitted work. Retrying could create both records together. Then we killed it after the shared commit, before any success reply. Both records survived this time. So the retry found the same key and created no second effect. I think that crash would fool me. I'd see a failed call even though this receiver had committed. Yeah, without a reply, the caller lacks an answer; the receiver's work may already be complete. But repeating the operation is safe within this receiver's own envelope: recognition and effect, both or neither.
8:17 Whereas saving 'done' separately can leave a receipt for work that never happened... ...or doing the effect first can leave work that recovery doesn't recognize. But suppose that effect row just queues a real email. Does the row prove the message arrived? No. It proves the local handoff. The next receiver still needs its own acceptance and retry contract. We tested process crashes on one server, not losing that server or its stored data. So could an incident dashboard say Kafka succeeded while the receiver repeated its work? Yes. Two executions and one committed output can both be correct.
8:53 Compare receiver requests with effects in our original cases. Both had two requests. The naive receiver recorded two effects; recognition reduced that to one. Yeah, those counts depend on what we're identifying. The customer is a person; the operation key identifies this welcome action; an attempt is one try at delivering it. Think of the customer as an addressee and welcome-001 as a numbered letter. Two delivery attempts can carry that same letter number. Right. We need to know how long the receiver keeps that recognition.
9:24 Suppose welcome-001 returns after its recognition record disappears. Can the receiver create another effect for that existing key? Yes. In this receiver, a missing recognition record would let that retry create the effect again. And the extra acceptance belongs to the receiver's records, not the Kafka committed-output count. I'd compare both in review. Finally, bring those counts back to our signup. Kafka committed one output alongside the resume position, after an earlier attempt was aborted. The receiver had already accepted that earlier call and accepted its retry.
9:58 It wasn't part of Kafka's transaction, so the Kafka abort couldn't retract its effect. Adding atomic recognition at the receiver kept two requests from becoming two modeled effects. The handler still ran twice; the operation's identity survived both attempts. So in a design review, name the state each commit owns and follow the last outside action through recovery. That's how exactly once becomes a precise, testable promise. Thanks for listening to Learning Podcasts.