TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท streaming ยท messaging ยท distributed systems

Apache Kafka

A distributed, append-only log. Producers write streams of events to it, and any number of consumers read them at their own pace.

15 min8 animations

๐Ÿ–จ๏ธ Cheat sheet

A giant shared notebook

Imagine a school with a giant notebook in the hallway. Whenever something happens (a toy is sold, a parcel ships), someone writes a note on the next empty line. Nobody ever rubs anything out.

Lots of people can read the notebook. Each reader has a bookmark, so they always know where they stopped. The cook reads it to see what to bake, and the delivery person reads the same notes to see what to drive where. Neither gets in the other's way.

That notebook is Kafka. Press play to watch the first notes go in.

What Kafka is

Apache Kafka is a distributed event streaming platform. At its core is an append-only, replicated log. Applications publish events to it and other applications consume them, independently and at their own pace.

TermMeaning
ProducerAn application that writes records
ConsumerAn application that reads records
BrokerA Kafka server that stores logs and serves reads and writes
TopicA named stream of records, such as orders
PartitionOne ordered log; every topic is split into one or more
OffsetA record's position in its partition: 0, 1, 2โ€ฆ
Consumer groupConsumers that share the work of reading a topic

A record is a key, a value, a timestamp and optional headers. Consuming a record doesn't remove it. Records are kept until the topic's retention limit, by time or by size.

The big picture6 steps
๐Ÿซ School hallwayThe orders notebook01234567๐ŸชToy shop๐ŸงฎBilling reader
Press play and watch it happen!

Splitting the notebook

One notebook would get far too crowded, so Kafka splits each topic into several smaller notebooks called partitions.

Every note has a name tag (the key). Kafka always puts notes with the same name tag into the same notebook. That way all of Ana's notes stay in the right order.

Partitions and keys

A topic is divided into partitions, and partitions are spread across brokers. That's how Kafka scales writes and reads beyond one machine.

The producer picks a partition for each record. With a key, the default partitioner uses hash(key) % partitionCount, so every record with the same key goes to the same partition. Without a key, records are spread out in batches.

Kafka guarantees order within a partition only. If you need all events for one customer in order, use the customer id as the key. Adding partitions later changes which partition a key maps to, so pick a sensible count up front.

Partitions and keys6 steps
๐Ÿ“š Three notebooks for ordersNotebook 0012345Notebook 1012345Notebook 2012345๐ŸชToy shop
Press play and watch it happen!

Teams of readers

The billing team has more than one helper. Kafka shares the notebooks out between them so they can work at the same time, and no notebook is read by two billing helpers at once.

The shipping team is a different team. It reads all the same notes with its own bookmarks.

Consumer groups

Consumers that use the same group.id form a consumer group. Kafka assigns each partition to exactly one consumer in the group, which splits the work and keeps per-partition order.

Different groups are independent: each one receives every record and tracks its own offsets. One topic can feed billing, shipping and analytics without any of them knowing about the others. That's publish-subscribe and work-sharing queues in one model.

A group can't usefully have more consumers than the topic has partitions. Extra consumers sit idle.

Consumer groups share the work5 steps
๐Ÿ’ฐ Billing teamNotebook 0012345Notebook 1012345Notebook 2012345๐Ÿ‘งHelper Ava๐Ÿ‘ฆHelper Ben
Press play and watch it happen!

Bookmarks

When a reader finishes some notes, it writes its bookmark into Kafka so Kafka remembers too. If the reader trips and falls before writing its bookmark, it goes back to the last bookmark it wrote and reads a few notes again.

Offsets and commits

A consumer's position is the next offset it will read. Periodically it commits an offset to the broker, stored in the internal __consumer_offsets topic. After a restart or a rebalance, consumption resumes from the last committed offset.

Commit after processing and you get at-least-once delivery: a crash between processing and committing means some records are delivered again. Commit before processing and you risk losing records instead (at-most-once). Most systems choose at-least-once and make processing idempotent. Kafka transactions can give exactly-once semantics for read-process-write pipelines within Kafka.

Offsets and commits7 steps
๐Ÿซ School hallwayOrders notebook012345๐Ÿง’Billing reader
Press play and watch it happen!

Sharing out again

When a new helper joins, or one goes home sick, Kafka shares the notebooks out again so every notebook still has a reader. This is called a rebalance.

Rebalancing

Group membership is managed by a group coordinator on one of the brokers. Consumers send heartbeats; if one stops (it crashed, or took longer than max.poll.interval.ms between polls), it's removed. A rebalance then reassigns its partitions.

Older "eager" rebalances stopped the whole group while partitions moved. The cooperative protocol only moves the partitions that need to move, and the newer consumer protocol (KIP-848) moves that work onto the broker.

Rebalancing5 steps
Notebook 001234Notebook 101234Notebook 201234๐Ÿ‘งHelper Ava๐Ÿ‘ฆHelper Ben
Press play and watch it happen!

Spare copies

What if the building with the notebook loses power? Kafka keeps copies of every notebook in different buildings. One copy is the main one, and the others copy it line by line. If the main one breaks, a copy takes over and nothing is lost.

Replication

Each partition has a replication factor, typically 3. One replica is the leader and handles all writes (and by default reads). Followers fetch from the leader to stay in sync. Replicas that are caught up form the in-sync replica set (ISR).

With acks=all and min.insync.replicas=2, a write is acknowledged only once it's on at least two replicas, so losing one broker loses no acknowledged data. When a leader fails, the controller (a KRaft quorum in modern Kafka; ZooKeeper in older versions) elects a new leader from the ISR.

Replication keeps data safe7 steps
๐Ÿ  Building 1๐Ÿก Building 2๐Ÿ˜๏ธ Building 3Main notebook01234Copy notebook01234Copy notebook01234๐ŸชToy shop
Press play and watch it happen!

When a reader trips

Notebooks are sturdy, but the people around them are not. Three things go wrong most often.

A reader falls before writing the bookmark. The new reader starts from the old bookmark and repeats a few jobs. So every reader keeps a list of what it has already done and skips repeats.

A writer isn't sure its note went in. Nobody said "got it", so it writes the note again, and now the notebook has two. Each note gets a number from the writer, so the notebook can spot the second copy and ignore it.

A reader falls far behind. The notebook keeps only the last few days of pages. If a slow reader doesn't catch up in time, the pages it hasn't read get torn out. Watch how many lines each reader is behind, and add helpers before that happens.

Two more can hurt. A spare copy that stops keeping up can't be trusted when the main notebook breaks, so Kafka can refuse new notes until enough spare copies are current. And one note that nobody can read makes a reader stop at the same line forever, so it gets set aside in a "problem notes" notebook.

What can go wrong

Offsets, rebalances and replication are covered above. These are the failures they leave you to handle.

  • A consumer crashes after processing but before committing. The next owner resumes from the last committed offset, so the batch is processed again (see Offsets and commits). Symptom: duplicate side effects, such as a customer charged twice. Fix: make the handler idempotent, for example a unique key on the order id in the database, or an upsert. Kafka transactions cover only read-process-write inside Kafka.
  • A producer retry duplicates a record. If a broker's acknowledgement is lost, the producer resends and the log holds the record twice. Symptom: the same payload at two offsets. Fix: the idempotent producer, enable.idempotence, which is true by default since Kafka 3.0 (versions 3.0.0 and 3.1.0 had a bug that kept it off, so set it explicitly there). It needs acks=all, retries above 0 and max.in.flight.requests.per.connection of 5 or less. It de-duplicates retries within one producer session and partition only. Retries stop after delivery.timeout.ms (2 minutes by default), after which send fails.
  • A follower drops out of the ISR, or a consumer lags. A follower that doesn't catch up within replica.lag.time.max.ms leaves the ISR, and the partition is under-replicated (watch UnderReplicatedPartitions). A slow consumer shows as a growing records-lag-max (consumer metric) or group lag. If lag outlasts retention (retention.ms, seven days by default), the broker deletes unread records and the consumer jumps according to auto.offset.reset. Fix: alert on lag, add consumers (up to the partition count), speed up processing, and keep retention longer than your worst outage.
  • The leader is lost. With acks=1 the leader replies before followers copy the write, so a crash right then loses an acknowledged record. With acks=all and min.insync.replicas=2 (default 1), the write waits for two replicas. If the ISR shrinks below two, producers get NotEnoughReplicasException (retried until delivery.timeout.ms, then the send fails) and writes stop instead of risking loss. Keep unclean.leader.election.enable=false (the default), so an out-of-sync replica never becomes leader.
  • A poison record blocks a partition. A record that always fails (a bad payload that throws RecordDeserializationException, or a handler bug) is retried at the same offset forever, so the partition stalls and lag grows. Fix: retry a few times, then publish it to a dead-letter topic and move on. In Spring, DefaultErrorHandler with DeadLetterPublishingRecoverer, plus ErrorHandlingDeserializer for bad bytes.
1props.put(ProducerConfig.ACKS_CONFIG, "all");2props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);3// broker or topic: min.insync.replicas=2
ChoiceYou gainYou pay
acks=all instead of acks=1No acknowledged write is lost when one broker diesHigher write latency, and writes fail when the ISR is too small
Commit after processing instead of beforeNo lost records (at-least-once)Duplicates after a crash, so handlers must be idempotent
More partitionsMore parallel consumers and throughputMore files and replication work, longer failovers, and adding partitions later remaps keys
Fewer partitionsSimpler, cheaper cluster and more records share one orderA lower cap on consumer parallelism, so lag is harder to fix
A crash before the commit6 steps
Orders notebook012345๐Ÿ‘งReader Ava
Press play and watch it happen!

Kafka in a Java app

In a Java program you don't have to ask Kafka for notes yourself. With Spring you write one method and put a label on it, @KafkaListener. Spring sends a helper to collect notes and rings your method once for every note.

Listeners in Java

With plain Java you run the poll loop yourself:

1try (var consumer = new KafkaConsumer<String, String>(props)) {2    consumer.subscribe(List.of("orders"));3    while (true) {4        for (var record : consumer.poll(Duration.ofMillis(500))) {5            charge(record.key(), record.value());6        }7        consumer.commitSync();8    }9}

Spring for Apache Kafka wraps that loop in a listener container. You write only the handler:

1@KafkaListener(topics = "orders", groupId = "billing")2public void onOrder(ConsumerRecord<String, String> record) {3    charge(record.key(), record.value());4}

The container polls, calls your method once per record (or per batch), commits offsets according to its ack mode, and hands exceptions to an error handler that can retry or publish to a dead-letter topic. Setting concurrency = "3" runs three consumers in the same group.

๐Ÿ”ง Going deeper

Not the same "listener": brokers also have listeners and advertised.listeners settings. Those are the network addresses a broker binds to and tells clients to connect to. A wrong advertised.listeners value is the classic reason clients connect once and then fail, especially in Docker.

When not to use Kafka: for request/response calls, or a small job queue where each message should be deleted once handled, a simpler queue or a plain HTTP call is often a better fit. Kafka shines when many consumers need the same stream of events, when you want to replay history, or at very high throughput.

@KafkaListener in a Spring app5 steps
โ˜• Your Java appOrders notebook012345๐Ÿ™‹Helper who asks๐Ÿ””Your bell
Press play and watch it happen!

๐Ÿ”Ž Spot it in real code

This is the shared notebook as real Java code: one app writes notes, another reads them. Pick a label, then tap the line where that happens. Can you find all five?

Tap the line where you see: Someone writing a note.

0 of 5 placed

๐Ÿงฉ Finish the code

Now set the notebook up yourself. The checkout app must never lose a note if a shelf of copies breaks, and the billing reader must never skip a note or charge anyone twice, even if it trips halfway through a pile. Pick the right piece of code for each numbered gap.
  1. 1 Only say "done" once every up-to-date copy has the note
  2. 2 Join the billing team of readers, who share the notebooks
  3. 3 Don't let the bookmark move by itself on a timer
  4. 4 Charge each order, but never the same one twice
  5. 5 Move the bookmark only after the whole pile is charged
1// Checkout: an acknowledged order must survive a broker failure2var producerProps = new Properties();3producerProps.put("bootstrap.servers", "kafka:9092");4producerProps.put("acks", 1);5producerProps.put("enable.idempotence", "true");6 7// Billing: never skip an order, never charge one twice8var consumerProps = new Properties();9consumerProps.put(2, "billing");10consumerProps.put("enable.auto.commit", 3);11 12try (var consumer = new KafkaConsumer<String, String>(consumerProps)) {13    consumer.subscribe(List.of("orders"));14    while (true) {15        for (var rec : consumer.poll(Duration.ofMillis(500))) {16            4;17        }18        5;19    }20}
0 of 5 gaps filled

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐Ÿš•UberStream moving drivers, match riders in seconds and never double-charge.guided design

๐Ÿงช Debug it for real

  • ๐Ÿ’ณBilling charged some customers twiceThe billing reader works through the shared notebook of orders. Some customers were charged twice, and after a restart one order was never charged at all. Find out why and fix it.Java 21Kafka clientJUnit 5intermediate30 min

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Apache Kafka, told the same way as the story.
  1. Two readers read the same notebook. Do they get in each other's way?
  2. Why do all notes with Ana's name tag go into the same notebook?
  3. A reader trips before writing its bookmark into Kafka. What happens when it gets back up?
  4. A note that nobody can read keeps stopping a reader at the same line. What should the reader do?
  5. Every spare copy of the notebook has fallen behind, so only the main one is up to date, and the rule says two copies must have each note. A writer tries to add a note. What happens?
Answer every question to check.Passing marks Apache Kafka as done.
Got the hang of Apache Kafka? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ•ธ๏ธ Distributed systems from zeroStep 7 of 7

โ† Previous on the path๐Ÿ“‹ Distributed cachingLast step ๐ŸŽ‰Back to the path

๐ŸŽฏ Backend interview prepStep 9 of 9

โ† Previous on the pathโš–๏ธ CAP theoremLast step ๐ŸŽ‰Back to the path

๐Ÿ“จ Event-driven systemsStep 1 of 5

Next on the path โ†’๐Ÿงฅ Message queues vs event streams

๐Ÿ‘‰ Read next

  • ๐Ÿ”˜IdempotencyPressing a lift button five times still calls one lift: the system remembers each press.
  • ๐Ÿ“’Event sourcing and CQRSA bank passbook where every deposit is a new line never rubbed out, plus a balance board in the window.
  • ๐ŸงฅMessage queues vs event streamsA coat-check pile, where each ticket is handled once, versus a guestbook anyone can reread from any page.
  • ๐Ÿ“ปRedis Streams and pub/subA radio show that's gone once aired, next to a deli ticket rail where tickets stay until someone serves them.