SteelReed

Search

Search posts, questions…

7. System Design

Why Kafka is fast and durable: the log, zero-copy, batching and replication

Kafka isn't 'fast' in the low-latency sense; it's built for throughput: an append-only log with sequential I/O, zero-copy, writes to the page cache without fsync, cheap consumers thanks to offsets, client-side batching and compression, partitions and consumer groups. Then durability: replication, ISR, the high watermark, acks, min.insync.replicas, unclean leader election and ELR on Kafka 4.x (KRaft only); plus how to review producer config an AI wrote.

18 Nov 202610 min readSenior

–

1. The problem

An acks=1 producer sends 300,000 messages at 20,000/second; both followers fall 3 seconds behind and then the leader is killed. Reading the topic back: 60,640 acknowledged messages are gone, and the producer reported no error. The same scenario with acks=all: zero lost.

2. Key idea

The broker does as little as possible. Durability doesn't come from the disk but from copying the record to several machines before the ACK. Like an append-only notebook with three copies in three rooms; readers only remember which page they're on.

Design decision Gain Cost
Append-only log, sequential I/O the disk stops being the bottleneck no in-place updates or per-record deletes
Zero-copy sendfile no copies through user space lost with TLS or when the broker must recompress
Write to page cache, no fsync the ACK doesn't wait on disk one broker losing power loses data
Batching, client-side compression fewer requests, less bandwidth a few ms more latency
Replication, ISR, acks=all losing a machine loses no records too few replicas stops writes

"Fast" means high throughput, not the lowest latency.

2.1 What to choose for your topic?

Ask: how many machines hold an acknowledged record, and how many brokers can go down before writes stop.

Choice Use when Don't use when
acks=all + RF 3 + min.insync.replicas=2 money, orders, ledgers only one service sets it while others stay on acks=1
acks=1 logs and metrics where loss is acceptable data you've told users was "saved"
Unclean leader election on clickstream, metrics payments: a replica outside the ISR becomes leader and what it lacks is gone for good
Adding partitions while running topics without keys you need per-key order

The ISR are replicas keeping up with the leader within replica.lag.time.max.ms (30 s).

3. In Java

A producer for payment events: the account id is the key, to keep per-account order.

JAVA
var props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka-1:9092,kafka-2:9092");
props.put(ProducerConfig.ACKS_CONFIG, "all");                 // wait for every ISR replica
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);    // retries don't duplicate or reorder
props.put(ProducerConfig.LINGER_MS_CONFIG, 10);
props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "lz4");
props.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 60_000);
 
try (var producer = new KafkaProducer<String, String>(props, new StringSerializer(), new StringSerializer())) {
    var record = new ProducerRecord<>("payments", "acc-42", "{\"type\":\"TOPUP\",\"amount\":200000}");
    producer.send(record, (meta, ex) -> {
        if (ex != null) log.error("publish failed", ex);   // alert, or let the outbox resend
        else log.info("partition={} offset={}", meta.partition(), meta.offset());
    });
}
// 3 records with key acc-42: same partition, increasing offsets

In every client (librdkafka for Go, .NET, Python), send is asynchronous: errors only show up in callbacks or promises.

Why it's durable without fsync, and why adding partitions breaks order
  • The broker ACKs once the record is in the page cache, without calling fsync; the OS flushes later. One broker losing power may lose unflushed data, but with acks=all the record already sits on at least min.insync.replicas machines: you'd have to lose both at once.
  • Sequential I/O beats random I/O by hundreds of times on HDDs. Each partition is a set of append-only segments (1 GB by default) with offset and time indexes.
  • Zero-copy works because batches on disk are already in wire format; brokers need a large page cache so consumers read the log tail from RAM.
  • Consumers don't delete on read: each group only stores offsets in __consumer_offsets, so extra groups are nearly free and replay is possible.
  • The partitioner computes murmur2(key) % partitions. Going from 3 to 6 may move key acc-42 to another partition: new events get processed before old ones still in the old partition. Partitions can't be reduced.
  • Kafka 4.0 removed ZooKeeper entirely; metadata is managed by a controller quorum (KRaft).

4. Working with AI

Hand to AI: a 3-broker Docker lab that kills the leader and counts lost records.

Check in AI-written code:

  • Every producer writing to money topics uses acks=all, not just the service you're looking at.
  • Topics have RF 3 and min.insync.replicas=2; unclean election is off.
  • send callbacks handle errors instead of being empty.
  • Partitions of keyed topics aren't increased in production without a migration plan.

5. Exercises

Exercise 1: Review a "durable" setup

Topic payments has replication.factor=3 and min.insync.replicas=2. The AI reports "durability configured". The billing service uses acks=all; the refund service (written later, AI-generated) uses an old template default: acks=1. Is refund's data durable? Prove it, fix it.

Solution to Exercise 1

No. min.insync.replicas only applies to acks=all producers; an acks=1 producer is ACKed as soon as the leader writes to its page cache, regardless of followers. If the leader dies before followers copy the record, an acknowledged record is lost.

Proof: in a 3-broker lab, have refund send 300,000 records, pause both followers (docker pause), kill the leader, and count: tens of thousands missing, no producer error.

Fix: acks=all (with idempotence) for every producer writing that topic; check it with a script scanning service configs, and in review.

Exercise 2: Read a writes-stopped incident

During a rolling restart of broker 2, acks=all producers on payments report TimeoutException en masse; broker logs show NotEnoughReplicasException. The topic has RF 3 and min.insync.replicas=3. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.

Solution to Exercise 2
  • Diagnosis: min ISR equals RF. With one broker restarting, the ISR is 2 < 3, so every acks=all write is rejected. The client only sees TimeoutException after retrying for delivery.timeout.ms.
  • 15 minutes: wait for broker 2 to rejoin the ISR, or temporarily lower the topic's min.insync.replicas to 2 with kafka-configs --alter.
  • Root fix: min.insync.replicas=2 with RF 3: one broker can be down and writes continue, without losing acknowledged records. Add an alert on UnderMinIsrPartitionCount.

Summary

  • Kafka trades a few ms of latency for throughput: batching, linger.ms, compression.
  • An append-only log, zero-copy, the page cache and offset-only consumers make brokers fast.
  • Order exists only within a partition; adding partitions moves keys.
  • Durable with RF 3 + min ISR 2 + acks=all on every producer.
  • acks=1 ignores min ISR; min ISR equal to RF stops writes when one broker is down.

Read more: Part 3: Tuning Kafka for your goal.

Practice interview questions on this topic

All Messaging & Kafka questions →

Loading comments…