The queue lesson showed that some brokers delete a message once it is processed, while log brokers keep it. Kafka is the standard log broker: it keeps messages in an ordered, replicated log, and many consumers can read the same log at their own pace, or read it again from the start. That one difference makes it the standard choice for event streaming, data pipelines and high-volume messaging. This lesson covers how Kafka is built, how it stays fast and durable, how consumers scale, and how to size a cluster.
1. A Log, Not a Queue
Kafka stores records in a log: an append-only sequence where each record gets a number, its offset. Records stay for a set time (7 days by default) or size, whether or not anyone has read them. A consumer group only remembers its own position, the offset it has read up to. So every group gets every record, a group can replay by moving its offset back, and a queue's per-message retry and delay must be built with extra topics (section 10).
Consider a video app that records each play, pause and click. Many systems want the same events: analytics, recommendations, a search index, fraud checks. With a queue, you would copy each event into several queues. With Kafka, you write it once, and each system reads the log on its own. A new system added next year can read the old events from the start.
2. Core Concepts
- Topic: a named stream of records, such as
video-events. - Partition: a topic is split into partitions. Each is its own log, stored on one broker. The partition is the unit of parallelism and of ordering.
- Broker: a Kafka server. A cluster has several, and they share the partitions.
- Producer: writes records to a topic. If the record has a key (for example the user ID), the key's hash picks the partition. Records with the same key always go to the same partition, so order is kept per key. There is no order across partitions.
- Consumer group: a set of consumers that share a topic. Each partition is read by exactly one consumer in the group, so a group can use at most as many consumers as there are partitions. Different groups are independent and each gets all records.
flowchart LR
PR["Producers (key = user ID)"] --> P0["Partition 0"]
PR --> P1["Partition 1"]
PR --> P2["Partition 2"]
P0 --> A1["Group A: consumer 1"]
P1 --> A1
P2 --> A2["Group A: consumer 2"]
P0 --> B1["Group B: consumer 1"]
P1 --> B1
P2 --> B1
Group A (analytics) splits the three partitions between two consumers. Group B (the search indexer) has one consumer that reads all three. Both see every record. A fourth consumer in group A would sit idle, because there are only three partitions.
Offsets and rebalances. The broker keeps each group's committed offset per partition in an internal topic, and a restarted consumer resumes from it (commit after processing for at-least-once, as in the queue lesson). When a consumer joins, leaves or crashes, Kafka rebalances: it reassigns the partitions among the remaining consumers, and reading pauses briefly.
3. Why Kafka Is Fast
- Sequential disk writes. Records are only appended. Sequential disk writes are far faster than random ones.
- The operating system's page cache. Recent data is served from memory without Kafka managing a cache.
- Zero-copy. Data goes from the page cache to the network card without being copied through the application.
- Batching and compression. Producers send records in batches, and brokers store them as batches, which cuts both network and disk cost.
As a planning number, one partition handles 10,000 to 50,000 messages per second (the Numbers lesson). More partitions go higher.
4. Durability and Replication
Each partition has a replication factor, usually 3: one leader that takes all reads and writes, and followers that copy it. The followers that are caught up form the in-sync replicas (ISR). If the leader dies, a new leader is chosen from the ISR.
The producer decides how safe a write must be with acks:
| Setting | Write is acknowledged when | Risk |
|---|---|---|
acks=0 |
Sent, without waiting | Loss on any failure. For data you can lose |
acks=1 |
The leader has written it | Lost if the leader fails before followers copy it |
acks=all |
All in-sync replicas have it | Safest. Slightly slower |
For data that matters, use replication factor 3, acks=all and min.insync.replicas=2. A write then needs at least 2 copies. One broker can fail with no loss and no downtime. If two fail, the partition refuses writes instead of risking data. This is the consistency against availability choice from the consistency lesson, made in configuration. Do not allow an out-of-sync replica to become leader (unclean election), since it would lose records.
5. Delivery Semantics in Kafka
- At-least-once is the normal setup:
acks=all, retries on, commit after processing. Consumers must be idempotent, as in the queue lesson. - Idempotent producer: when a send is retried after a timeout, Kafka drops the duplicate using a producer ID and sequence numbers. It is on by default in recent versions and keeps order within a partition.
- Transactions: a program can read from topics, write results to other topics and commit its offsets as one atomic step. That gives exactly-once for pipelines that stay inside Kafka. A side effect outside Kafka, such as charging a card or writing to a database, still needs an idempotent consumer.
6. Producer and Consumer in Java
6.1 Producer
public class VideoEventProducer implements AutoCloseable {
private final KafkaProducer<String, String> producer;
public VideoEventProducer() {
Properties props = new Properties();
props.put("bootstrap.servers", "broker1:9092,broker2:9092");
props.put("key.serializer", StringSerializer.class.getName());
props.put("value.serializer", StringSerializer.class.getName());
props.put("acks", "all");
props.put("enable.idempotence", "true");
props.put("linger.ms", "5"); // wait up to 5 ms to fill a batch
props.put("compression.type", "lz4");
this.producer = new KafkaProducer<>(props);
}
public void publish(String userId, String eventJson) {
ProducerRecord<String, String> record =
new ProducerRecord<>("video-events", userId, eventJson); // key = user ID
producer.send(record, (metadata, exception) -> {
if (exception != null) {
// retries are exhausted: log it, alert, or store the event elsewhere
}
});
}
@Override
public void close() {
producer.close(); // sends everything still waiting
}
}
sendis asynchronous. It adds the record to a batch and returns at once. The callback later gives the partition and offset, or the error. Check it, or a failed send goes unnoticed.- The key decides the partition, so one user's events stay in order.
linger.msand compression trade a few milliseconds of delay for larger batches and much better throughput.- Create one producer and share it. It is thread-safe and holds the connections and buffers. Call
close()on shutdown, or records still in the buffer are lost.
6.2 Consumer
public class VideoEventConsumer implements Runnable {
private final KafkaConsumer<String, String> consumer;
public VideoEventConsumer() {
Properties props = new Properties();
props.put("bootstrap.servers", "broker1:9092,broker2:9092");
props.put("group.id", "analytics");
props.put("key.deserializer", StringDeserializer.class.getName());
props.put("value.deserializer", StringDeserializer.class.getName());
props.put("enable.auto.commit", "false"); // we commit after processing
props.put("auto.offset.reset", "earliest"); // used if the group has no offset
props.put("max.poll.records", "500");
this.consumer = new KafkaConsumer<>(props);
}
@Override
public void run() {
try {
consumer.subscribe(List.of("video-events"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));
for (ConsumerRecord<String, String> r : records) {
process(r.key(), r.value()); // must be idempotent
}
consumer.commitSync(); // commit after the batch is done
}
} catch (WakeupException e) {
// shutdown was requested
} finally {
consumer.close();
}
}
public void shutdown() {
consumer.wakeup(); // safe to call from another thread
}
private void process(String key, String value) { /* business logic */ }
}
- The poll loop is the heart of a consumer.
pollfetches a batch. If it is not called again withinmax.poll.interval.ms(5 minutes by default), Kafka removes the consumer from the group and rebalances. Keep the work per batch short. - Commit after processing gives at-least-once. Auto commit saves offsets on a timer, so a crash can lose or repeat records unpredictably.
commitSyncwaits for the broker, andcommitAsyncis faster but does not retry. group.idnames the group. Run more copies with the same ID to scale, up to the number of partitions.auto.offset.resetapplies only when the group has no saved offset:earliestorlatest.- A
KafkaConsumeris not thread-safe. Run each instance of this class on its own thread. To stop it, callshutdown()from another thread, which makespollthrowWakeupExceptionso the loop can close the consumer cleanly.
7. Kafka with Spring Boot
Spring Boot (with spring-kafka) creates the producer, the consumer and the poll loop for you.
7.1 Configuration
spring:
kafka:
bootstrap-servers: broker1:9092,broker2:9092
producer:
acks: all
compression-type: lz4
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringSerializer
properties:
enable.idempotence: true
linger.ms: 5
consumer:
group-id: analytics
auto-offset-reset: earliest
enable-auto-commit: false
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
listener:
ack-mode: record # commit the offset after each record is processed
These are the same settings as the plain Java code. Any other Kafka setting goes under properties. To create the topic at startup, declare a bean:
@Bean
public NewTopic videoEvents() {
return TopicBuilder.name("video-events").partitions(24).replicas(3).build();
}
Careful: if the topic exists with fewer partitions, Spring raises the count, which brings the key-mapping problem from section 9.1.
7.2 Producer
@Service
public class VideoEventPublisher {
private final KafkaTemplate<String, String> kafka;
public VideoEventPublisher(KafkaTemplate<String, String> kafka) { this.kafka = kafka; }
public void publish(String userId, String eventJson) {
kafka.send("video-events", userId, eventJson) // topic, key, value
.whenComplete((result, ex) -> {
if (ex != null) { /* log or alert: the send failed */ }
});
}
}
KafkaTemplate is the producer wrapper. Like the plain producer it sends asynchronously, so check the result. (In older Spring Kafka versions send returns a ListenableFuture instead.)
7.3 Consumer
@Component
public class VideoEventListener {
@KafkaListener(topics = "video-events", groupId = "analytics", concurrency = "3")
public void onEvent(ConsumerRecord<String, String> record) {
process(record.key(), record.value()); // must be idempotent
}
}
@KafkaListenerruns the poll loop. Spring calls your method for each record and commits the offset after it returns, according toack-mode. If the method throws, the offset is not committed and the error handler decides what happens.concurrency = "3"starts 3 consumer threads in this application instance. All instances together should not exceed the number of partitions.
For failures, add an error handler that retries and then moves the record to a dead-letter topic (by default named like video-events.DLT):
@Bean
public DefaultErrorHandler errorHandler(KafkaTemplate<String, String> template) {
var recoverer = new DeadLetterPublishingRecoverer(template);
return new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3)); // 3 retries, 1 s apart
}
Spring Boot picks this bean up automatically. While a record is being retried, its partition waits. Spring also offers @RetryableTopic for retries on separate topics, so the main topic keeps moving.
8. Retention, Replay and Compaction
- Retention by time or size: old segments are deleted after 7 days, or above a size limit.
- Replay: reset a group's offset to reprocess old records. Use it to fix a bug in a consumer, to rebuild a search index, or to start a new system from history. This is the main advantage over a queue.
- Log compaction: instead of deleting by age, keep only the latest record for each key. The topic becomes a changelog of current state, such as the latest profile of each user. A consumer can rebuild a full table by reading it.
9. Sizing a Cluster
A clickstream of 50,000 events per second, 1 KB each, kept for 7 days. Replication factor 3. Assume a consumer handles 5,000 events per second and a broker has 8 TB of disk, used up to 70%.
- Throughput: 50,000 × 1 KB = 50 MB/s in, and the replicas add 100 MB/s of internal traffic.
- Storage: 50 MB/s × 86,400 = 4.3 TB a day. For 7 days: 30 TB. With 3 copies: 90 TB.
- Brokers: 90 TB ÷ (8 TB × 0.7 usable) = 16.1, so 17 brokers. Storage decides here, not throughput.
- Partitions: the producer side needs 50,000 ÷ 10,000 = 5 at least. The consumer side needs 50,000 ÷ 5,000 = 10 consumers, so at least 10 partitions. Choose 24, which leaves room for more consumers.
Choose the partition count with care, because it is hard to change. The last subsection of this part shows why.
9.1 Changing the Number of Partitions
Increasing is allowed, but it has side effects:
- Old records stay where they are. Kafka does not move them. Only new records use the new partitions.
- Keys map to different partitions. A key is placed by
hash(key) % number of partitions, so with 24 partitions changed to 32, many keys now go elsewhere (this is the hash mod N problem from the sharding lesson). User 42's old events are in partition 7, and the new ones go to partition 19. Two consumers read them independently, so a new event can be processed before an older one. Order per key is broken across the change, and compacted topics break too, because a key may now live in two partitions.
Decreasing is not supported, and adding is unsafe when per-key order matters. Change safely, up or down: create a new topic with the new count, copy the data across if needed (Kafka Connect, MirrorMaker or a small stream job), let consumers drain the old topic to the end, then move producers to the new one and delete the old one. Every key stays in order. Better still, choose a count with room to grow at the start.
Why not use far too many? Each partition costs open files and memory, adds replication work, and slows leader election after a broker failure. Plan for the next year or two, not ten times that.
10. Operating Kafka
- Consumer lag is the number of records a group is behind the newest one. It is the most important metric. Rising lag means consumers cannot keep up, and it is Kafka's version of the queue's message age.
- Hot partitions. A key that is far more active than others overloads one partition. Choose keys that spread evenly.
- Rebalances. Consumers joining and leaving cause pauses. Avoid long processing between polls.
- Message size. The default limit is about 1 MB. Send a reference to large files in object storage.
- Failures in processing. One failing record blocks its partition, because offsets only move forward. Use retry topics and a dead-letter topic, as described in the queue lesson.
- Cluster metadata. Older versions need ZooKeeper. Newer ones use KRaft, a built-in controller. Managed services (Amazon MSK, Confluent Cloud) remove much of the operations work.
10.1 The Ecosystem
- Kafka Connect: ready-made connectors to move data in and out of databases and storage. With a change-data-capture tool such as Debezium, every database change becomes an event.
- Stream processing: Kafka Streams and Flink read topics, filter, join and aggregate, and write results back (see the batch and stream processing lesson).
- Schema registry: stores the format of events (Avro or Protobuf) and checks that changes stay compatible, so a new field does not break old consumers.
11. Common Pitfalls
- Expecting order across partitions. Order holds only within one partition.
- Too few partitions, which caps consumer parallelism and is awkward to change.
- More consumers than partitions. The extra ones sit idle.
acks=1for important data. Useacks=allandmin.insync.replicas=2.- Committing offsets before processing, which loses records on a crash.
- Non-idempotent consumers. At-least-once means duplicates.
- A skewed or hot key. One partition does all the work.
- Using Kafka as a query database. It is a log.
- Using Kafka for a few hundred messages an hour, or for task queues that need per-message retry, delay or priority. A simple queue is easier.
- Adding partitions to a live topic when per-key order matters.
- Not watching consumer lag.
12. Interview Questions This Lesson Prepares You For
- How does Kafka differ from a message queue? Kafka keeps records in a log until retention expires. Each consumer group reads independently and can replay. A queue deletes a message after it is acked, and each message goes to one consumer.
- How does Kafka guarantee ordering? Only within a partition. A key decides the partition, so all records of one key are ordered. Across partitions there is no order.
- Why is Kafka fast? It appends to a log (sequential writes), serves reads from the operating system's page cache with zero-copy transfer, batches and compresses records, and spreads partitions over many brokers.
- How do consumers scale? In a consumer group, each partition goes to one consumer, so parallelism is limited by the number of partitions. Add partitions and consumers together.
- How do you make sure no data is lost? Replication factor 3,
acks=all,min.insync.replicas=2, no unclean leader election, and consumers that commit offsets after processing. - What happens when a broker or a consumer fails? If a broker holding a partition leader dies, a new leader is chosen from the in-sync replicas. If a consumer dies, a rebalance gives its partitions to the others, and they resume from the last committed offsets.
- How would you get exactly-once? Idempotent producer and Kafka transactions inside Kafka, and idempotent consumers for side effects outside it.
- What happens if you increase the number of partitions of a topic? Existing records stay, and new records use the new partitions. Keys map to different partitions, so per-key order breaks across the change and compaction is affected. You cannot decrease partitions. Create a new topic and migrate instead.
- How do you choose the number of partitions? From the required throughput divided by the per-partition rate, and from the number of consumers you need, with headroom, because it is hard to change later.