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.
| Term | Meaning |
|---|---|
| Producer | An application that writes records |
| Consumer | An application that reads records |
| Broker | A Kafka server that stores logs and serves reads and writes |
| Topic | A named stream of records, such as orders |
| Partition | One ordered log; every topic is split into one or more |
| Offset | A record's position in its partition: 0, 1, 2โฆ |
| Consumer group | Consumers 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.
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.
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.
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.
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.
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.
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 istrueby 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 needsacks=all,retriesabove 0 andmax.in.flight.requests.per.connectionof 5 or less. It de-duplicates retries within one producer session and partition only. Retries stop afterdelivery.timeout.ms(2 minutes by default), after whichsendfails. - A follower drops out of the ISR, or a consumer lags. A follower that doesn't catch up within
replica.lag.time.max.msleaves the ISR, and the partition is under-replicated (watchUnderReplicatedPartitions). A slow consumer shows as a growingrecords-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 toauto.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=1the leader replies before followers copy the write, so a crash right then loses an acknowledged record. Withacks=allandmin.insync.replicas=2(default 1), the write waits for two replicas. If the ISR shrinks below two, producers getNotEnoughReplicasException(retried untildelivery.timeout.ms, then the send fails) and writes stop instead of risking loss. Keepunclean.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,DefaultErrorHandlerwithDeadLetterPublishingRecoverer, plusErrorHandlingDeserializerfor bad bytes.
1props.put(ProducerConfig.ACKS_CONFIG, "all");2props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);3// broker or topic: min.insync.replicas=2
| Choice | You gain | You pay |
|---|---|---|
acks=all instead of acks=1 | No acknowledged write is lost when one broker dies | Higher write latency, and writes fail when the ISR is too small |
| Commit after processing instead of before | No lost records (at-least-once) | Duplicates after a crash, so handlers must be idempotent |
| More partitions | More parallel consumers and throughput | More files and replication work, longer failovers, and adding partitions later remaps keys |
| Fewer partitions | Simpler, cheaper cluster and more records share one order | A lower cap on consumer parallelism, so lag is harder to fix |
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)) {2consumer.subscribe(List.of("orders"));3while (true) {4for (var record : consumer.poll(Duration.ofMillis(500))) {5charge(record.key(), record.value());6}7consumer.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) {3charge(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.
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.