Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Kafka: a Distributed Messaging System for Log Processing

The log as the primitive: a broker that remembers nothing about its readers, and consumers that pull at their own pace.

Read the original ↗

Six pages at a workshop, and no replication in any of them. The Kafka paper is far smaller than Kafka's reputation, and reading it is the quickest way to find out which famous parts of the system were designed in 2011 and which arrived later because 2011 was not enough.

The problem it was solving

The plain version of what this paper builds: a file that many programs write to the end of and many other programs read through at their own speed. That is nearly all of it. Messages for one topic are appended to a file on a machine called a broker. A reader keeps its own bookmark saying how far it has got, asks for whatever comes after that position, and the broker forgets about it immediately. Nothing tracks who has read what, so nothing has to be told when a reader is finished, and a second reader costs nothing because it just keeps its own bookmark. The file is thrown away after a week whether anyone read it or not. Why it is worth your time today: this is the paper where the industry's default shape for moving data between services stopped being a queue and started being a log, and the change turned out to be about the location of one small piece of state rather than about performance.

LinkedIn had two kinds of log data, user activity events, and operational metrics, at a volume the paper describes as orders of magnitude larger than the "real" data. That much had been true for years. What had changed by 2011 is that this data had stopped being an input to overnight analytics and become part of the production pipeline: search relevance, recommendations driven by what is popular right now, ad targeting, abuse detection, the newsfeed. Once a live feature depends on an event stream, "load it into the warehouse tonight" is not a delivery mechanism.

Two families of system already existed and neither fit. Enterprise messaging, the paper names IBM Websphere MQ and the JMS specification, and benchmarks against ActiveMQ and RabbitMQ, spends its complexity budget on per-message delivery guarantees that log data does not need. The paper says outright that losing a few pageview events occasionally is not the end of the world. Worse for the workload, JMS has no API for a producer to batch messages into one request, so every message costs a full TCP round trip. And those systems assume near-immediate consumption, so their performance degrades once unconsumed messages are allowed to pile up, which is exactly what a nightly Hadoop load does.

The other family was the log aggregators: Facebook's Scribe, Yahoo's Data Highway, Cloudera's Flume. Those are built to land data in HDFS for offline consumption, they push rather than let consumers pull, and the paper's specific complaint is that they leak their implementation at the consumer, its example is the "minute files" a consumer has to know about. LinkedIn needed one stream that a Hadoop load and a real-time feature could both read, with the real-time one delayed by no more than a few seconds. The paper's design is the claim that a single system can serve both, provided it stops behaving like a queue.

One sentence in the opening is the key to every decision that follows, and it is easy to skim past: this data is orders of magnitude larger than the data the business considers real. Sit with what that ratio does to a design budget. If a system carries a thousand times more events than it does records, then any per-message cost: a header, an index entry, a row of delivery state, an acknowledgement round trip, an object the garbage collector has to walk, is multiplied by a thousand before anyone sees it, and the total is set by the overhead rather than by the payload. That is why almost every choice in the paper is a subtraction. No message id and therefore no index mapping ids to positions. No per-consumer state on the broker. No cache written by the authors. No acknowledgement waited for, in the version they measured. Read the design as a list of features and it looks thin. Read it as a per-message overhead budget being driven towards zero and it is coherent, and the parts that later had to be added back are exactly the parts that put a cost back on every message.

What it actually claims

The paper's own framing is that Kafka is a set of unconventional but practical design choices, and it is worth reading as exactly that: a list of things the authors did not do, each with a reason.

It is worth walking one message end to end as the paper describes it, because the path is shorter than anyone expects. A producer collects some messages and sends them in one request to the broker that holds the partition it is publishing to. The broker appends the batch to the last segment file and returns. It does not replicate it anywhere, and in the configuration the evaluation measures it is not even waited for. A consumer, separately and at a completely unrelated moment, looks up in ZooKeeper which broker holds the partition it has been assigned and what offset it last committed, asks that broker for a few hundred kilobytes starting from there, and receives bytes copied by the kernel straight from the file into the socket. It then records a new offset back in ZooKeeper. At no point does the broker learn anything about the consumer, and at no point does the message acquire an identity beyond its position in a file. That absence of bookkeeping is the design.

sequenceDiagram
  participant P as Producer
  participant B as Broker holding the partition
  participant Z as ZooKeeper
  participant C as Consumer
  P->>B: publish a batch of messages
  Note over B: append to the last segment file<br/>and flush on a schedule
  C->>Z: read the broker and offset registries
  Z-->>C: which broker, and where I got to
  C->>B: fetch from that offset, up to N bytes
  B-->>C: bytes sent from the file to the socket
  C->>Z: record the new offset
  Note over B: the broker never learns<br/>what the consumer read

Follow the offset. It is written and read by the consumer, kept in ZooKeeper, and never touches the broker. That is the single relocation of state that makes the broker stateless, makes an extra reader free, and makes retention a policy rather than a negotiation.

A partition is a log, and a log is a pile of files
Each partition of a topic is a logical log, implemented physically as a set of segment files of approximately the same size, the paper's example is 1GB. A publish appends to the last segment file. Segment files are flushed to disk only after a configurable number of messages or a configurable interval, and a message is exposed to consumers only once it has been flushed. That is the entire storage engine, and the paper spends about a paragraph on it, because the point is how little there is.
There is no message id: there is a byte offset
A message in this paper has no explicit id. It is addressed by its logical offset in the log, which avoids maintaining the auxiliary, seek-intensive random-access index that maps ids to locations. The paper is precise about the consequence and it surprises people: those ids are increasing but NOT consecutive, and you compute the next one by adding the current message's length to it. The broker keeps in memory a sorted list of offsets including the first message of every segment file, so serving a fetch is a search of that list followed by a read.
The consumer pulls, and the argument for it is two sentences long
A pull request carries the offset to start from and an acceptable number of bytes to fetch. The paper prefers pull over the aggregators' push for two reasons: a consumer retrieves at the maximum rate it can sustain rather than being flooded by a producer that is faster than it, and rewinding is easy. The rewind examples are the ones that still matter, replaying a range after fixing a bug in consumer logic, and a consumer that flushes to a persistent store periodically checkpointing the smallest unflushed offset so a crash costs nothing.
The broker is stateless, which forces the retention policy
The broker does not track how much each consumer has read. The consumer does. That removes a great deal of complexity and overhead from the broker and makes one thing impossible: the broker can no longer know when a message is safe to delete. Kafka's answer is a time-based SLA, a message is deleted after it has been retained longer than a set period, typically seven days. The paper acknowledges that letting a consumer rewind violates the common contract of a queue, and treats that violation as a feature rather than a compromise.
No cache, because the operating system already has one
Kafka deliberately does not cache messages in memory at the Kafka layer. It relies on the file system page cache. The benefits the paper claims are avoiding double buffering, keeping a warm cache across a broker process restart, and, the argument that is specific to running on a VM, leaving the broker with almost nothing to garbage collect, which is what makes an efficient implementation in a JVM language feasible at all. Because producers and consumers both walk segment files sequentially, with the consumer usually lagging the producer slightly, ordinary OS write-through and read-ahead heuristics turn out to be very effective.
sendfile, and the four copies it removes
The paper walks the naive path from a file on a broker to a socket: read into the page cache, copy to an application buffer, copy that to a kernel buffer, send. Four copies and two system calls. The sendfile API transfers bytes from a file channel straight to a socket channel, removing two of the copies and one of the calls, and because Kafka is multi-subscriber and one message may be read by several consumer applications, that saving is paid back per reader rather than once.
Batching on both ends, with a number attached
A producer sends a set of messages in a single publish request, and although the consumer API iterates one message at a time, each pull retrieves many, typically hundreds of kilobytes' worth. The evaluation isolates what this is worth: the paper reports that a batch size of fifty messages improved producer throughput by almost an order of magnitude. Nearly all of the difference between this system and the enterprise brokers it is measured against is amortisation of the round trip.
Coordination is four ZooKeeper registries, and no master on purpose
The paper decides against a central master node explicitly, on the grounds that a master is one more thing that can fail, and lets consumers coordinate among themselves through ZooKeeper. There are four registries: broker, consumer, ownership and offset, the first three on ephemeral paths so a death removes them, the offset registry persistent. Every consumer watches the broker and consumer registries, and any change triggers a rebalance in each of them: read both registries, range-partition the available partitions deterministically among the group's members, claim a chunk in the ownership registry, and start pulling from the offset recorded there. Two consumers can momentarily believe they own the same partition, and the resolution is that one releases everything it holds, waits, and retries.
At-least-once, and deduplication is the application's job
The paper's delivery guarantee is one paragraph and it is unambiguous: Kafka guarantees at-least-once delivery, exactly-once typically requires two-phase commits, and that was not necessary for these applications. A consumer that crashes without a clean shutdown means the consumer taking over its partitions may see duplicates after the last offset committed to ZooKeeper, and an application that cares must add its own deduplication using either the offsets Kafka returns or a unique key inside the message, which the paper argues is usually cheaper than two-phase commit anyway. Ordering is guaranteed within a partition and explicitly not guaranteed across partitions.
The partition is the unit of everything, and that is the contract
Ordering is guaranteed within a partition and explicitly not across partitions, and once that is stated the rest of the operational model follows without being spelled out. A partition is one log on one broker, so a partition is the unit of ordering, the unit of storage and the unit of parallelism all at once. The rebalance in the paper hands each consumer in a group a contiguous range of the available partitions, which means the number of consumers that can usefully work on a topic is capped by the number of partitions, and adding a consumer beyond that gives you an idle process rather than more throughput. It also means the partition count is chosen up front, is awkward to raise afterwards without disturbing which key lands where, and is the number every capacity conversation about this system eventually comes back to. The paper never presents this as a limitation because for its workload it is not one, but everything a practitioner argues about: key skew, hot partitions, how many partitions is too many, is a consequence of these two sentences.
The deployment section is a second design, and it is easy to miss
Section 5 describes how this was actually run at LinkedIn, and the arrangement is more interesting than the mechanism. Each customer-facing datacenter has its own Kafka cluster, and the analytics datacenter has a separate cluster of its own that consumes from the live ones and re-publishes what it reads. That mirroring cluster is not a special replication feature. It is an ordinary consumer and an ordinary producer wired back to back, which is only possible because a consumer is nothing more than a bookmark and a fetch. Hadoop and the warehouse then load from the analytics cluster, so the offline pipeline never puts load on the machines serving live features, and a slow batch job cannot affect a real-time one. It is a good example of what a genuinely simple primitive buys you: cross-datacenter data movement fell out of the design as an application of it rather than as another subsystem to build.
The evaluation, and its honesty
A producer test and a consumer test against ActiveMQ and RabbitMQ, one topic, ten million messages. Kafka wins comfortably, and the paper names the reasons rather than resting on the number: Kafka's producer at that time did not wait for broker acknowledgements at all, Kafka's per-message overhead was far smaller than a JMS header plus indexing structures, the competing brokers had to maintain per-message delivery state on disk, and sendfile cut the transmission cost. It closes the section by saying the point is not that the other systems are inferior: they have more features, but to show what a specialised system can buy.

The one idea worth stealing

The reader's position is the reader's property, and moving it there turns a delivery system into a storage system.

A queue keeps delivery state on the broker. That single fact is why a queue must work out who has read what before it can forget anything, why adding a second independent reader is a change to the broker, and why one slow consumer becomes everybody's problem. Move the cursor to the consumer and all three disappear at once: storage stops caring who its audience is, an extra reader costs the system nothing, retention becomes a policy instead of a negotiation, and a reader that falls behind falls behind alone. Nothing else in the paper is as load-bearing as this one relocation of a small piece of state.

The shape recurs far outside messaging, and it is usually available: any time a server is holding per-client progress, ask whether the client could hold it instead. Pagination cursors, sync tokens, resumable uploads, change feeds, replication slots: the server gets to be stateless and the client gets to be replayable, and the price is that the client can now ask for something that has been deleted, which is a failure you can name and handle rather than one you have to prevent.

There is a smaller steal beside it. The reason Kafka has no message cache is that the operating system already runs one, it is already tuned for the access pattern in use, and it survives a process restart, three arguments for deleting a component rather than writing it. That move is available much more often than it is taken, and it is usually blocked by the assumption that a specialised cache must beat a general one.

The third steal is the one the evaluation demonstrates rather than argues: find the fixed cost in your hot path and amortise it, before you optimise anything else. A batch of fifty messages did not make each message cheaper to process. It made forty-nine round trips disappear. That is where nearly the whole margin over the enterprise brokers came from, and it is the same trick as a group commit, a pipelined HTTP request, a bulk insert, or a debounced write. When something is slow, the first question is not which line is expensive but how many times you are paying a cost that does not depend on the size of what you are sending.

The last thing to take is a habit of reading, not of building. This paper is six pages, is missing replication, has a different offset scheme, depends on a coordination service that has since been removed, and disclaims the guarantee everybody now asks about first. It is still worth reading, precisely because comparing it against the system as it is now shows you which parts were the idea and which were the circumstances. Do this with the original paper behind any tool you operate. The gap between what was designed and what exists is where all the interesting decisions are, and nobody writes them up.

What aged badly

Not much of this paper is wrong. Quite a lot of it is simply absent, and what is absent is most of what a Kafka question now means.

sequenceDiagram
  participant P as Producer
  participant L as Partition leader
  participant F as Follower replicas
  participant G as Group coordinator
  participant C as Consumer in a group
  P->>L: produce with a producer id<br/>and a sequence number
  L->>F: replicate
  F-->>L: in sync
  L-->>P: acknowledged
  C->>G: join the group
  G-->>C: the partitions you own
  C->>L: fetch from the committed offset
  C->>G: commit the offset to an internal topic

The same message in Kafka as it is now. Compare it with the diagram above: the follower replicas, the producer id that makes a retry safe, the broker-side coordinator and the offsets living in a Kafka topic are all later work. Only the producer, the leader and the fetch are in the 2011 paper, which is why the paper is a poor manual and an excellent lesson.

There is no replication in it at all
The 2011 system stores each partition on one broker, and its durability is a configurable flush of a segment file, the evaluation's producer does not even wait for an acknowledgement. Replication appears once, in the future-work list, described almost exactly as it eventually shipped: built-in replication across multiple brokers, with both asynchronous and synchronous models so an application can trade producer latency against the strength of the guarantee. Everything a durability conversation about Kafka now involves: acks, the in-sync replica set, min.insync.replicas, the high water mark, unclean leader election, is later work. The board on this site about replication and durability has no counterpart in the paper whatsoever.
The offset was a byte position, and now it is not
In the paper, a message id is its byte offset within the log, and the paper says plainly that ids are increasing but not consecutive. Modern Kafka's offsets are consecutive per-partition sequence numbers, which is what makes consumer lag a subtraction, makes a compacted topic's key-to-offset reasoning possible, and makes an offset something a human can reason about. It is a small change with a wide blast radius, and it is the clearest single sign that the paper describes an earlier system now running under the same name rather than the current one.
Offsets lived in ZooKeeper, and every consumer ran the rebalance
The offset registry is a ZooKeeper path, and rebalancing is a decentralised algorithm each consumer executes on a watch notification. The paper is candid that consumers can be notified at slightly different times, that one may try to take a partition another still owns, and that the resolution is to drop everything, wait, and retry, which at LinkedIn's 2011 scale stabilised after a few attempts. At a few hundred consumers that becomes the stop-the-world rebalance that a decade of operators know by feel. Committed offsets later moved into a compacted internal topic and ownership into a broker-side group coordinator. Incremental cooperative rebalancing came later still.
ZooKeeper itself has since been removed
The paper's coordination section is a ZooKeeper section: the registries, the ephemeral paths, the watches, and it argues for that arrangement over a master node specifically because a master is another failure to handle. Kafka has since gone the other way: KRaft replaces ZooKeeper with a Raft quorum of Kafka's own brokers, so cluster metadata lives in a Kafka log like everything else and the second distributed system an operator had to run is gone. Treating this section as a guide to operating Kafka would be studying a dependency that no longer exists.
"Exactly once" is nowhere in it, and it is now the first question anyone asks
The paper's whole position is a sentence: at-least-once, exactly-once typically needs two-phase commit, that was not necessary here, dedupe it yourself with an offset or a key. For clickstream data that is the correct engineering answer. It is the wrong answer for the payments-shaped workloads Kafka was subsequently sold into, and the industry spent six years closing the gap: the idempotent producer, where a producer id and a per-partition sequence number let the broker drop a retried write, and then transactions spanning a read-process-write cycle. Both are later work, and even now the guarantee they give is narrower than the phrase suggests, which is why there is a whole board here about it.
Retention was time, and only time
Because the broker is stateless it cannot know who has read what, so deleting after a fixed period is the entire retention story in the paper. Log compaction, retaining the newest value per key indefinitely, which is what lets a topic be read as a table and what everything from connector offsets to stream-processing state stores relies on - is not in it. Neither is tiered storage, which moves old segments to object storage so retention stops being bounded by the brokers' disks. Both change what a log IS: the paper's log is a buffer with a seven-day memory, and the modern one is a store.
The zero-copy path now has a condition attached
The sendfile argument is the paper's most-quoted design detail and it is almost always quoted without its precondition: sendfile works because the broker never has to look at the bytes. Encrypt the traffic and it must, so the copies the paper deleted come back the moment TLS is turned on, which, for most clusters built in the last decade, is always. This is not the paper's error. It is a later constraint arriving on top of a correct argument. But it is the clearest case on this page of a design point that survives as a slogan after the conditions that made it true stopped holding by default.
The famous argument about the log is not in this paper
It is worth separating the paper from its reputation. What this paper argues is narrow and well-supported: for log processing at this volume, a specialised system beats both an enterprise broker and a log aggregator, and here is the throughput to prove it. The much larger claim usually attributed to it: the log as the universal primitive underneath databases, replication, stream processing and system integration, the idea that reorganised a decade of data infrastructure, is Jay Kreps's later writing and the stream-processing literature that followed it. The paper is modest, careful, and does not attempt the argument it gets the credit for.
What to take from it today
Read it in an hour, and read it with the current documentation open beside it. What survives whole is the relocation of the reader's position from the server to the reader, and it is worth carrying into designs that have nothing to do with messaging, because it is what turns a delivery system into a storage system that anyone may read as many times as they like. What survives with conditions attached is the performance argument: batching and letting the operating system do the caching are still right, and the zero-copy path is still right until you turn on encryption. What does not survive is everything the system had to grow afterwards, and the honest reading of that is not that the paper was wrong but that a design tuned so hard for one workload will be asked to do others, and each of those will cost it a subtraction it was proud of. If there is one thing to take away, it is the exercise itself: put a system's original paper next to the system, and the difference will teach you more than either alone.

Related on chalk

The same idea as a board, lab, video or lesson.

Further reading

Read the original for the full argument and its evidence.