How Kafka handles millions of messages per second
Kafka is fast and durable because of one rule, never change the past, only add to it. The append-only log, partitions and consumer groups, zero-copy reads, replication and acks, and compaction, with the limits stated.
13:10 video9 min read
- 2 architecture diagrams
- 2 sequence flows
- 1 data model
- 2 interviewer follow-ups
- 3 self-checks
7T+
messages a day across LinkedIn's Kafka clusters, as it reported in 2019
6,000x
linear over random disk writes in Kafka's own documentation example
1 per partition
the most consumers in one group that can share a topic's work
On this page11 sectionsHLDSenior depth
- Why an append-only log is fast, and why it needs no locking around existing records.
- How partitions and consumer groups scale reads and writes, and what ordering Kafka guarantees.
- What zero-copy and the page cache do, and when they stop applying.
- How replication, in-sync replicas and acks trade latency for durability, and what exactly-once really covers.
Kafka was built at LinkedIn, and by LinkedIn's own account it went from about a billion messages a day in 2011 to more than seven trillion a day by 2019. It is not fast because of a clever algorithm. It is fast because of a rule so simple it sounds like a mistake: never change the past, only add to it.
Picture thirty services that each need data from five others. Wire them directly and every service must know about every other, one outage loses messages, and a spike on one team topples the rest. The fix is to put one thing in the middle: producers write to a broker, and whoever cares reads from it. The sender does not know who is listening. That is decoupling.
The popular brokers of that era behaved like a vending machine: a consumer takes a message and it is gone, so nobody else can read it and nothing can be replayed. That is how a classic queue works. Kafka asked for a different shape, closer to a newspaper: written once, read by many, still on the shelf tomorrow. (Queues have changed since: some, such as RabbitMQ with its streams, now offer log-style storage too. The difference between a queue and a log is covered in the queues lesson.)
A log is a notebook where you only ever write on the next empty line. You never erase and never overwrite. Each line gets a number called an offset, and offsets only go up.
That sounds too basic to matter, but it matches how disks work. Random writes make a spinning disk's head jump around; sequential writes just keep going. Kafka's own documentation gives the contrast for one setup, six 7200 rpm SATA drives in RAID-5: about 600 MB a second for linear writes against about 100 kB a second for random writes, a difference of over 6,000 times. (Your hardware will differ, and SSDs narrow the gap, but the shape holds.) Kafka batches records so the work reaching the disk is sequential.
Never rewriting a record also removes a class of problems. There is no locking around existing records, because they never change. A small, sparse index per file lets a reader jump close to any offset without scanning.
00000000000000000000.logbytes
the records, only ever appended to
00000000000000000000.indexbytes
sparse: offset to position in the .log
00000000000000000000.timeindexbytes
sparse: timestamp to offset
The number is the offset of the first record in the segment. When a segment is full, a new one starts at the next offset. Retention and compaction work on whole segments.
One log lives on one machine, which has one disk and one network card, so it eventually maxes out. Kafka splits a topic into partitions, spread across brokers and written in parallel. Need more throughput? Add partitions.
On the read side, a consumer group is a set of workers that split a topic's partitions between them. Inside one group, each partition is read by exactly one consumer at a time, so eight partitions can keep eight workers busy and no two ever touch the same one. Each group remembers its own position (committed offsets, stored in an internal topic), so a restarted worker resumes where it stopped. And because positions are per group, completely separate teams, analytics, search and fraud, can read the same stream at the same time without knowing about each other.
Two rules to say out loud. Order is guaranteed within a partition, not across them. And records with the same key go to the same partition (by default, a hash of the key chooses it), which is how you keep one user's events in order.
Sending a file over the network the ordinary way copies the bytes several times: disk to kernel memory, into the application, into a socket buffer, out to the network card. Kafka asks the operating system to do it in one step with the sendfile system call: take the data from where it already sits and hand it to the network card. Most of the copying disappears.
It also helps that most reads are of recent data. Records written seconds ago are still in the operating system's page cache, so a cluster whose consumers keep up can serve reads with almost no disk activity. The limit: with TLS between client and broker, the broker has to encrypt the bytes in user space, so the zero-copy path does not apply, and Kafka's documentation says so.
Speed means nothing if data vanishes when a server dies. Every partition has one leader and several followers. The leader takes all reads and writes; followers fetch from it and copy the log. The followers that are keeping up form the in-sync replicas. A follower that falls behind is dropped from that set, and when a leader fails only an in-sync replica may take over, so you never recover onto stale data. (Letting an out-of-sync replica become leader, called unclean leader election, is off by default.)
The producer chooses how much proof it wants. With acks=1 the leader confirms as soon as it has written the record, which is fast but loses the record if the leader dies a moment later. With acks=all the leader waits until every in-sync replica has it. Pair that with min.insync.replicas=2 on a topic with three replicas and you can lose a whole machine without losing an acknowledged message, at the cost of a few milliseconds. Recent Kafka clients default to acks=all with the idempotent producer turned on.
Kafka does not delete a record when it is read. It deletes by policy: by age (the default is seven days) or by size, a segment at a time. A third mode, log compaction, keeps only the newest record for each key and sweeps older ones away in the background. A service that needs the current balance, not six months of transactions, can read a compacted topic and get exactly that. To remove a key entirely you write a record with that key and no value, called a tombstone, which compaction keeps for a while and then drops. (Tombstones in Cassandra behave differently but cause a related kind of trouble: see the Discord write-up.)
A compacted topic is, in effect, a replicated, fault-tolerant table of the latest value per key. You did not bolt a database on; you let the log become one.
| They ask | A strong answer |
|---|---|
| Why is Kafka fast? | Sequential appends, batching, the page cache and zero-copy reads. Name the mechanisms, not "it is distributed". |
| How do you scale it? | Add partitions for write throughput, add consumers up to one per partition, add a consumer group for each independent reader. |
| How do you avoid losing data? | Replication factor 3, acks=all, min.insync.replicas=2, unclean leader election off. It is a dial, not a fixed setting. |
| What about ordering? | Guaranteed within a partition only. Use the key to keep related records together; one partition if you need a single global order, at the cost of parallelism. |
| Can it do exactly-once? | Within Kafka, yes: the idempotent producer plus transactions. Effects outside Kafka still need idempotent writes. |
Interviewer follow-upL6A topic has 8 partitions and a consumer group has 12 consumers. What happens, and what do you do?How to answer
Eight consumers get one partition each and four sit idle, because inside a group a partition has only one reader. To use more consumers you need more partitions, but adding partitions has a cost: the key-to-partition mapping changes, so new records for a key can land in a different partition than its older ones, breaking per-key ordering across the change. Plan partition counts with growth in mind, and never rely on being able to shrink them.
Interviewer follow-upL7Can Kafka give you exactly-once processing?How to answer
Within Kafka, yes. The idempotent producer attaches a producer id and a sequence number so the broker drops retried duplicates, and transactions let a consumer-producer application read, process and write results atomically, with downstream readers set to read only committed records. The guarantee stops at Kafka's edge: if processing sends an email or updates another database, a retry can repeat that effect, so those writes must be idempotent, for example with a key checked in the same transaction as the side effect.
QuestionWhy is writing to the end of a log so much faster than updating records in place?Reveal answer
Appends are sequential, so the disk head does not jump around, and the operating system and Kafka can batch them. In Kafka's own example, linear writes were over 6,000 times faster than random writes on that hardware. Never changing existing records also removes the need to lock them.
QuestionWhy can a consumer group not use more consumers than the topic has partitions?Reveal answer
Inside a group each partition is read by only one consumer at a time, to keep order and avoid two workers handling the same records. Extra consumers have no partition and stay idle. More parallelism needs more partitions.
QuestionWhat do acks=all and min.insync.replicas=2 give you on a topic with three replicas?Reveal answer
A write is acknowledged only after every in-sync replica has it, and the partition refuses writes if fewer than two replicas are in sync. So you can lose one machine without losing an acknowledged message, at the cost of a little latency and some availability if too many replicas fail.
The queues lesson covers queue versus log, delivery guarantees and idempotency, and replication and sharding covers leaders, followers, lag and partition keys. Consistency and availability explains the quorum trade-offs behind acks and min.insync.replicas.
- Apache Kafka documentation, Design (opens in a new tab): persistence and the 600 MB/s versus 100 kB/s example, efficiency and
sendfile, replication and the in-sync set, log compaction. - LinkedIn Engineering, Kafka Ecosystem at LinkedIn (opens in a new tab) and How LinkedIn customizes Apache Kafka for 7 trillion messages per day (opens in a new tab) (2019).
Spot a mistake, or have a question?
Accuracy matters here. Tell me what looks wrong or unclear and I will fix it and credit you.