Ch.47: Kafka System Design: What Accepted Really Promises

Outline

Transcript

0:00 Imagine you publish to Kafka, get success, then lose one broker. Three copies were configured. The replacement has no record to return. The first broker replied before either follower copied it. We deliberately chose leader-only acknowledgment, not Kafka's current default. Then three copies describes the plan, not what that reply proved. Let's fix the promise, not just add another server. Now trace that lost record on the complete map: producers send it to the leader of one partition, an ordered slice of the stream.

0:30 Followers copy its log. Each consumer group reads independently. Above that data path, the controller tracks ownership and safe replacements. It doesn't carry each record through a majority vote. Those paths set up the failure proof we'll return to on this exact map. Source links are in the description. Before choosing components, state functional requirements: what callers can do. Are we designing a mailbox that deletes each record after one read? No. Publish keyed records into named topics. A topic names the stream; its partitions are separately ordered lines.

1:03 Separate consumer groups replay retained history independently. Two groups means two applications, not contenders for one message. And ordering belongs within one partition, not a global sequence across customers. Right. Also report failed publishes and expired read positions explicitly. A successful reply must name a promise we can preserve during replacement. With those caller promises set, consider a fictional producer workload of 50,000 records per second, each 500 encoded bytes. That's 25 decimal megabytes a second before replication.

1:33 A modest-looking record becomes a continuous storage obligation. Replication triples that storage flow to 75 megabytes per second, excluding overhead. Those copies sit in three separate failure domains, so we aren't putting them all behind one local failure. We want 24 hours of replay. Then storage has to keep up with that flow, not just hold today's starting data. Also target 100 milliseconds for 99 of 100 publishes under admitted normal load. That's our p 99 objective, not a Kafka benchmark. Losing a broker could make that target impossible.

2:08 Do we accept a weaker write to keep the latency chart green? Not for the durable route. Non-functional requirements define how well the promise holds; during unsafe replication, refusal is an allowed outcome. I'd rather expose that refusal than call data loss availability. That gives clients an honest incident contract, though their retries still need bounds. Now replay changes that storage obligation. What actually stays on disk after the first group reads, instead of receiving a disposable message?

2:36 The log records stay until retention removes them. Readers move their own positions, so one group finishing doesn't erase another group's history. Picture this: three copies of a numbered register, with each reader keeping a bookmark. Turning your page doesn't tear mine out. Yes, and Kafka uses segment files holding stretches of that log. Batching spreads overhead across many records; mostly sequential access avoids treating each record like an unrelated tiny update. That doesn't prove a throughput number.

3:05 Disks, network, batch sizes and record distribution still need measurement against the workload. My first thought was just to add disks. I'd test our actual batches before trusting a tidy log layout to rescue overloaded hardware. That ordered log opens the partitioning choice. How do we keep one customer's records together without ordering every customer together? Let's say customer 7's updates use a stable key. Our routing rule sends them to partition 2 while that partition layout stays fixed. Customer 8 can use another partition, so the leaders append independently.

3:38 We don't make unrelated customers wait for one shared ordering point. Picture checkout lanes: plenty are open, but customer 7's whole queue must use one cashier. More lanes don't divide that one ordered stream. Poor cashier. I'd reach for more partitions before checking the key distribution. That wouldn't divide customer 7's existing stream by itself. And changing the partition count can change routing. Plan that migration deliberately; don't promise the old key history stays ordered automatically.

4:08 So we gained parallelism between customers. That sets up the next limit: one ordered lane still needs a safe replication promise. Now follow one partition's record. Walk me through the mechanism: how can the leader have the new record while readers still can't see it? Take a concrete case. Replicas A, B and C have records 0 and 1. Every log end and the safe-read limit points to next position 2. Yep. Position 2 means the next slot, not a 3rd record already visible. That convention saves an off-by-one argument later.

4:42 The producer sends record 2 to leader A. A appends it, B copies it, but C is still behind. Their next positions are 3, 3 and 2. We already have record 2 on A and B. Making readers wait sounds like artificial latency. Why isn't their local copy enough? Because C still counts among the current replication members. The high watermark is that commit boundary. Ordinary readers stay inside that prefix, even when another copy runs ahead. Once C catches up and the committed boundary advances to 3, records 0, 1 and 2 are visible.

5:17 Local presence and committed visibility differ. So record 2's local presence isn't enough. What must happen before the stronger acknowledgment returns? That visibility boundary leads to the acknowledgment set. The all setting waits until every current replication member has that record. Right. The in-sync replicas are the current members keeping up with the leader, often abbreviated ISR. Minimum membership isn't the acknowledgment rule. Then even with the minimum set to 2, we still wait for C? Yes. While C remains in that set, acknowledgments set to all cover the full current in-sync set, not an arbitrary majority of configured copies.

5:54 Then minimum 2 answers whether the set is large enough to accept this kind of write; it doesn't let us ignore a 3rd current member. Right. If C falls out through the membership protocol, the current set can become A and B. That is a state change, not the client privately counting two replies. Oh, right. I was blurring admission with completion. The same integer doesn't define both. What happens when another current member disappears? Next, suppose that member disappears. A is still responding, but no follower remains in sync.

6:28 The next producer's minimum-2 durable write fails its admission check. I'd be tempted to say the cluster is down, though a consumer might still read old committed records from the responding broker. Those are different operations. Availability belongs to the operation and contract, not a single green light beside the cluster name. But a product team could prefer leader-only writes for expendable telemetry. Aren't we making a business choice rather than discovering one universally correct setting? Absolutely.

6:57 We chose the stronger contract for these records. A weaker route can be explicit, but silently weakening this route turns success into a different promise. Fair. I'll keep refusal in this design, because recovering fewer records than we acknowledged would violate its stated requirement. And timeout doesn't prove nothing was appended. That leaves an unknown client outcome, which we'll handle after resolving safe replacement. Now imagine the leader fails after acknowledging record 2. Why isn't the responding replica with the longest log automatically the best replacement? Because its tail might contain uncommitted records.

7:32 Election must preserve the committed prefix, not reward whichever disk accumulated the most speculative bytes. B has one extra, uncommitted record 3; C doesn't. Both still have every acknowledged record: 0, 1 and 2. Yes. The controller's ownership and eligibility state authorizes a safe leader; replicas reconcile divergent uncommitted tails during recovery. Good. I'd have picked B for its longer tail and gotten lucky for the wrong reason. We need the promised history and the controller's approval.

7:59 Kafka calls that control system KRaft: its controllers agree on who owns each partition and which copies may take over. They don't vote on each payload. Okay, let's unpack this. If the active in-sync set becomes empty, have we necessarily lost every safe replacement? For the empty-set case, start a separate failure branch. A, B and C hold the acknowledged records 0 through 2. Minimum stays 2. C leaves first. A and B still share all three records. Then B loses connectivity. Does being disconnected erase its copy?

8:30 No. In this case B keeps that history. A is alone, below 2 current members, so committed progress freezes at next position 3. So here is our checkpoint: A is active, B is disconnected but intact, and no new record has joined the promise. The controller keeps B as an eligible leader replica, or ELR. Yep. That label records a safe election candidate outside active replication. Now suppose A's machine loses power before its recent file writes reach disk. Ah. They were in the operating system's memory cache, waiting for disk. Losing that machine's power loses those bytes; merely restarting the Kafka process isn't the same event.

9:10 Exactly. Kafka's accepted change proposal starts with that nasty last-copy problem. In our case B still has every promised record after A loses power. Then how does that disconnected copy actually take over, rather than leaving us with a useful label and no reachable leader? B reconnects with its records intact. It remains listed eligible, and the controller permits it to participate again. With no other active member, B can become leader. Whew. We can read 0 through 2 again. But B alone still cannot acknowledge a new minimum-2 write.

9:42 Right. Current Kafka enables this feature by default for new 4.1-and-later clusters. Safe election restored our old promise, not the margin for another one. That's the relief I wanted from three copies, without pretending all failures are survivable. Now we can handle the client's other problem: a reply that vanished. Now take one batch the broker committed, but whose successful reply vanished. Repeating it as a new application send can create duplicates. Then I'd want a stable identity before retrying.

10:14 What does Kafka's idempotent producer actually recognize, rather than our application wishing for no duplicates? With the idempotent producer, the retry retransmits that batch using the same producer identity and sequence numbers. The broker recognizes it instead of appending the records again. Does that identity include the business meaning of each record? No. It's the producer's protocol identity. It doesn't declare two unrelated producers' business requests identical or make an external email send exactly once.

10:41 My mental model was stretching the word idempotent across the whole workflow. The broker can recognize a retransmission while the application still repeats its business action. Right. Idempotence requires the all setting for acknowledgments, enabled retries, and at most 5 requests awaiting replies on one connection. Keep those settings compatible; the flag doesn't fix every combination. So a lost response calls for a protocol-aware retry, not a guess that timeout meant rejection. That keeps uncertainty explicit at the producer boundary.

11:12 Producer uncertainty is one boundary; consumer progress is another. The broker now exposes records 0 through 2, but what has each application actually finished? For example, group 1 saved next position 2 after processing 0 and 1. Group 2 bookmarked 1, so it still needs 1 and 2. Both read the same retained partition, with different bookmarks. Their progress doesn't move the broker's committed boundary backwards or erase each other's records. And saving progress before the application's work is durable can skip that work after a crash. Saving later can repeat it on recovery.

11:47 That replay boundary needs its own output protocol. The broker's durable record alone doesn't make a database change and bookmark one atomic action. Yes. Now let retention remove the earliest records while group 2 is offline. A bookmark can point before the available history. Yeah. I'd report that gap and apply a deliberate recovery policy. Quietly pretending the missing record was processed would corrupt the application's meaning of caught up. That retention gap opens a capacity tradeoff. 24 hours can't survive any storage budget just because we wrote it in a requirement.

12:20 If our chosen peak runs for the whole day, that's 2.16 decimal terabytes of logical input, or 6.48 for three copies before overhead. That's a sizing scenario, not a hardware claim. We'd need headroom and a declared response when storage runs short. Retention limits and admission policy must agree with the replay promise. And bound batches and outstanding work. Faster ingestion isn't useful if it builds an unbounded memory queue while followers lose ground. I think replica lag deserves a view next to publish latency.

12:52 A quick reply from one broker can hide the safety margin shrinking elsewhere. Track the number of partitions below our required in-sync count, alongside storage pressure. Those warning signals can't grant a replacement authority or create another durable copy. Fair. And if every usable copy is destroyed, no election rule recreates the missing bytes. Our failure budget needs a surviving safe copy, not just a dashboard. Finally, return to the same complete map. The producer reaches the partition leader; followers support its chosen acknowledgment, and the committed prefix feeds both consumer groups.

13:28 The controller selects an authorized replacement, including qualified eligible replicas in our current feature setting. It doesn't bypass minimum-2 admission for new durable writes. The opening record is now acknowledged only under that stronger contract. A safe copy can preserve it through our leader failure; lost replies remain retry uncertainty. And separate consumer bookmarks follow retained history. That is the full path: durable append, authorized replacement, bounded replay, with explicit failures between them.

13:56 So I'd start the interview answer by defining success and its failure budget, then choose storage, replication, admission and election rules that agree with it. Three configured copies isn't the proof. The proof is which copies support this result, which replacement may lead, and when we refuse a new result. Thanks for listening to Learning Podcasts.