Databases & Storage · Paper 05 / 05

Kafka: a Distributed Messaging System for Log Processing

Jay Kreps, Neha Narkhede, Jun Rao

2011 · NetDB · ~13 min read

Read the original paper

Kafka stores events in partitioned append-only logs and lets each consumer group track its own position, so a broker keeps no per-reader state. Read it to understand partitions, consumer lag, per-key ordering and at-least-once delivery.

At LinkedIn around 2010, every page view, search, profile edit and ad impression produced an event, and a growing list of systems wanted those events. The Hadoop warehouse wanted all of them for overnight reports. The news feed wanted profile edits within seconds. Search wanted them for relevance. Security wanted login events. Operations wanted service metrics. Each new consumer meant a new pipeline from each producer, with its own format, its own failure modes and its own on-call rotation.

The tools available split into two camps, and neither fitted. Log aggregators such as Facebook’s Scribe and Cloudera’s Flume collected log files and shipped them to Hadoop in batches, which worked for the warehouse and was useless for the feed. Enterprise message queues such as ActiveMQ and RabbitMQ delivered individual messages quickly, but the broker tracked the delivery state of every message for every consumer, acknowledged each one, and slowed badly when messages piled up because a consumer was slow or offline. A website’s event volume, with a batch consumer that reads once an hour, is exactly that case.

Jay Kreps, Neha Narkhede and Jun Rao described the system they built instead in a short 2011 paper at the NetDB workshop. After reading this explainer you should be able to say what a Kafka broker does and does not remember, trace a message from producer to two independent consumer groups, predict what a consumer sees after it crashes, and choose a partition count with its consequences in mind.

Store the log; let consumers keep their place

websearchadsmobilehadoopmetricssecurityfeedN × M pipelines, each its own format and failure modewebsearchadsmobilehadoopmetricssecurityfeedthe logN + M connections; every consumer reads the same history
Before and after. On the left, each producer has a separate pipeline to each consumer that needs its data. On the right, every producer writes once to a shared log and every consumer reads the same history from it.

The design inverts the queue. In a message queue, the broker’s job is to track messages: which consumer has each one, which have been acknowledged, which can be deleted. In Kafka, the broker’s job is to store an append-only log and serve byte ranges from it. It does not know which messages any consumer has read.

A stream of messages of one kind is a topic. A topic is divided into partitions, and each partition is a log: an ordered sequence of messages, each identified by its position. In the 2011 paper that identifier is the message’s byte position in the log, so ids increase but are not consecutive, and the next id is the current one plus the message’s length. Later versions of Kafka switched to consecutive offsets 0, 1, 2 and so on; we will use those below because they are easier to follow.

A consumer fetches by asking for “partition 2, starting at offset 118, up to this many bytes”. The broker returns that range and forgets the request. The consumer, not the broker, tracks where it is, and in the paper it records its offset periodically in ZooKeeper. Messages are deleted when they are older than a retention period, commonly days, regardless of whether anyone has read them.

QuestionMessage queue (ActiveMQ, RabbitMQ in 2011)Kafka log
Who tracks what has been read?The broker, per message per consumerEach consumer group, as one offset per partition
When is a message deleted?When acknowledgedWhen older than the retention period
What does a slow consumer cost the broker?Growing per-message state and memory pressureNothing; the data is on disk either way
Can a new system read last week’s data?No, it was deleted on deliveryYes, from any offset still retained
Ordering guaranteeVaries; per-queue order under conditionsOrder within a partition only
Delivery guarantee in the paperPer-message acknowledgementAt least once; duplicates possible after a consumer crash

One topic, three partitions, two groups

Here is the running example. The topic page-views has three partitions. Each message is a page view event, and the producer uses the member id as the key. The paper allows a producer either to pick a partition at random or to choose one with a partitioning function on a key; with a key, a typical function is a hash of the key modulo the number of partitions. Suppose member 4711 hashes to partition 1. Every page view by member 4711 is appended to partition 1, in the order the producer sent them.

Two consumer groups read the topic. The group feed has two consumers and keeps up within seconds. The group hadoop runs once an hour and reads everything new since its last run. Within a group, each partition is read by exactly one consumer at a time; the paper makes the partition the smallest unit of parallelism for exactly this reason, because it means consumers in a group never need to coordinate over individual messages. With three partitions and two consumers in feed, one consumer owns partitions 0 and 1 and the other owns partition 2.

partition 0012345678← appendspartition 101234567← appendspartition 20123456789← appends▌ group “feed” offsets · nearly caught up▌ group “hadoop” offsets · reads in hourly batches, hours behind, and that is fine
The page-views topic. Each partition is a numbered log. Each consumer group has its own offset in each partition: feed is a few messages behind, hadoop is hours behind and reads in hourly batches. Neither group affects the other.

The two groups are completely independent. The broker stores each message once. When feed fetches partition 1 from offset 5,002 and hadoop fetches it from offset 1,340, the broker serves two byte ranges from the same file. If hadoop is down for a day, nothing on the broker changes except that its offset stops moving. When it comes back it starts where it left off, as long as the data is still within retention. A third group, say a new fraud detector, can join next month and start from the oldest retained offset.

The one ordering guarantee follows from the structure. Member 4711’s page views are all in partition 1, partition 1 is an ordered log, and only one consumer in each group reads it, so each group sees member 4711’s events in the order they were produced. There is no ordering between partitions. An event for member 4711 and an event for member 9000 in partition 2 may be processed in either order.

Try itProduce to partitions, consume as a group

Messages with the same key always land in the same partition, so one user's events stay in order. Consumers in a group split the partitions between them and each keeps an offset.

P0→ C1P1→ C2P2→ C1filled = consumed by the group · the bar is the group's offset
messages0
group lag0unread messages across partitions
active consumers2of 2each owns at least one partition

The broker keeps no per-message state. Each group simply remembers how far it has read, so a new system can start from offset zero and replay history, and a crashed consumer resumes from its last offset. Messages are kept for a retention period whether anyone read them or not.

Now change one variable: add consumers to feed. With three consumers, each owns one partition and throughput rises. With four, one consumer owns nothing and sits idle, because a partition cannot be split between consumers of a group. Try it in the simulation. The partition count is therefore a ceiling on a group’s parallelism, and the paper notes that LinkedIn deliberately created more partitions than it had consumers so that load would balance well.

Predict first

Keep the example, but the topic now needs more throughput, so the team raises page-views from three partitions to six while producers are running. The producer still uses hash of member id modulo the partition count. What happens to member 4711’s events, and to the ordering guarantee?

Show the worked answer

Member 4711’s key hashed to partition 1 under modulo 3. Under modulo 6 it may map to a different partition, say 4. Events produced before the change sit in partition 1; events after it go to partition 4. A consumer group reading both partitions can process a new event for 4711 from partition 4 before an older one still waiting in partition 1. Per-key order is broken across the change, though it holds again for events produced afterwards.

This is why teams pick a partition count with room to grow when a topic is created, and why increasing it on a keyed topic is treated as a migration rather than a setting change. Kafka lets you add partitions, but not remove them, and does not move existing data when you do.

Why a log on disk can be faster than a queue in memory

The paper’s performance claims rest on choices that look odd at first. Kafka does not cache messages in its own process memory. Each partition is stored as a set of segment files of about a gigabyte. New messages are appended to the last segment, which is flushed to disk after a configurable number of messages or amount of time; in the paper’s design, consumers only see messages once they are flushed. The broker keeps in memory only the offset of the first message in each segment, which is enough to find the file for any requested offset.

Reads and writes go through the operating system’s page cache instead of an application cache. That avoids keeping two copies of the same data in memory, keeps the cache warm when the broker process restarts, and keeps the Java heap small so garbage collection stays cheap. Because consumers usually read data soon after it is written, most reads are served from the page cache without touching disk. A lagging consumer reads from disk, but sequentially.

To send data to a consumer, the paper uses the sendfile system call, which copies bytes from a file to a network socket inside the kernel. The usual path, read the file into a user buffer and then write the buffer to a socket, involves four data copies and two system calls; sendfile removes two of the copies and one of the calls. Producers and consumers also batch: a producer sends a set of messages in one request and a consumer fetches many messages at once. The per-message overhead in Kafka’s storage format is a few bytes, where the paper measured ActiveMQ’s at well over a hundred.

The evaluation compares Kafka with ActiveMQ and RabbitMQ on a pair of machines with small messages. The paper reports that Kafka produced around 50,000 messages a second when sending one message per request and around 400,000 with batches of 50, far above the other two, and that its consumer was more than four times faster than either. Read those numbers with the authors’ own caveats in mind, which they state. The Kafka producer in the test sent asynchronously and did not wait for the broker to acknowledge each message, while the other systems did. Kafka had no replication at the time, so it was doing less work per message than a broker offering stronger guarantees. The comparison shows what a design without per-message state can do; it is not a like-for-like durability comparison.

A consumer crashes mid-batch

At-least-once delivery is the paper’s guarantee, and it is easiest to understand by watching it happen.

Predict first

A consumer in feed owns partition 1. It processes messages and commits its offset every five seconds. Its last commit recorded offset 120, meaning “the next message to read is 120”. It has since processed messages 120 to 134, updating a follower-count cache for each, and then the process is killed. Where does its replacement start, and what happens to the cache?

Show the worked answer

The group rebalances, and another consumer takes over partition 1. It reads the last committed offset, 120, and starts there. Messages 120 to 134 are processed a second time.

Whether that matters depends on the processing. If the consumer sets a field to a value, such as “last seen time for member 4711”, repeating it is harmless. If it increments a counter, those fifteen events are counted twice. The paper is explicit that duplicates are possible after an unclean shutdown and that an application which cares must deduplicate, for example using the offset or a unique id carried in the message.

The alternative is to commit the offset before processing. Then a crash after the commit and before the work loses messages instead of repeating them, which is at-most-once delivery. The paper chose at-least-once because losing events was worse than repeating them for LinkedIn’s uses, and because duplicates can be handled downstream while lost data cannot be recovered.

The broker side of the 2011 design was weaker still. There was no replication. If a broker died, the messages on it that had not been consumed were unavailable until it came back, and if its disk was lost they were gone. The paper lists built-in replication as future work. For LinkedIn’s first use, activity data headed for analytics, that was an acceptable risk. It would not have been acceptable for payments.

What changed after the paper

Almost every limitation the paper states was addressed in the following decade, and each fix cost some of the original simplicity.

Kafka 0.8, in 2013, added replication. Each partition has a leader and followers, and the leader tracks the set of in-sync replicas. A producer can ask to be acknowledged only once all in-sync replicas have the message. That closed the data-loss gap and introduced settings, such as how many replicas must acknowledge and whether an out-of-sync replica may become leader, that every operator now has to understand. The same release moved to consecutive offsets. Consumer offsets moved from ZooKeeper into an internal Kafka topic shortly after, because ZooKeeper was not built for that write rate.

Log compaction gave topics a second retention mode: keep at least the latest message for every key, instead of everything for a period. A compacted topic can serve as the durable store for a table, which is how Kafka Streams keeps its state and how change-data-capture tools publish a database’s current rows.

Kafka 0.11, in 2017, added idempotent producers and transactions, marketed as exactly-once semantics. The idempotent producer attaches a producer id and a per-partition sequence number to each batch, so the broker can discard a retried batch it has already written. Transactions let a consumer-producer write its output messages and commit its input offsets atomically. In our crash example, if the follower-count updates were written to an output topic inside a transaction with the offset commit, the replacement would never see them twice. The guarantee is precise and narrow: it covers reads and writes within Kafka. If the consumer updates an external cache or sends an email, those side effects still need to be idempotent.

Finally, ZooKeeper itself was removed. KIP-500 replaced it with KRaft, a Raft-based quorum of controllers inside Kafka that stores cluster metadata as, fittingly, a replicated log. KRaft was declared production-ready in Kafka 3.3 in 2022, and Kafka 4.0 in 2025 removed ZooKeeper mode entirely. Tiered storage, which moves older segments to object storage, and a rewritten consumer group protocol have since changed the cost of long retention and of rebalancing.

When a log is the wrong tool

The design has costs that follow directly from its strengths. Ordering exists only within a partition, so a workflow that needs a global order across all events must use one partition and give up parallelism. Parallelism per consumer group is capped by the partition count, and the count is hard to change on keyed topics. A slow message blocks the messages behind it in the same partition, because a consumer cannot skip ahead without moving its offset past it.

That last point matters for task queues. If each message is a job that takes anywhere from a second to ten minutes, and jobs are independent, a log forces each consumer to work through its partition in order, and one slow job delays everything behind it. A traditional queue that hands each message to whichever worker is free, and redelivers it if the worker dies, fits better. Kafka has been adding share groups for this case, which is an admission that the original model was designed for streams of events, not for distributing work.

How to read the original

The paper is short, around seven pages, and readable in one sitting. Read the introduction and related work for the problem; the descriptions of why existing queues and log aggregators fell short are the clearest statement of the requirements. Then read the architecture section, which covers storage, efficient transfer, the stateless broker and distributed coordination with consumer groups and ZooKeeper. This is the heart of the paper and most of it is still accurate about Kafka today.

The delivery guarantees section is a few paragraphs and worth reading word for word, because it says plainly what Kafka did not promise. The section on LinkedIn’s deployment describes the cluster layout, the replication to an analytics data centre by consumers, the auditing system that counts messages per time window to detect loss, and the use of Avro with a schema registry. In the evaluation, read the paragraphs that explain why Kafka was faster as closely as the figures, and note the asynchronous producer and the absence of replication. Then read Jay Kreps’s 2013 essay “The Log”, listed below, which turns the paper’s mechanism into a general argument about how data systems should be built.

This closes the databases category. Codd separated what data means from how it is stored; ARIES made the log the record of truth for a single database; the LSM-tree and Bigtable turned that log into the storage layout; and Kafka made the log something many systems share. The next category, Cloud & Infrastructure, starts with the Google File System, the layer Bigtable stored every SSTable and commit log in, and asks how a file system should behave when it expects its disks to fail every day.