Sub topic 1
How Kafka organizes data: topics, partitions and offsets
This chapter explains the storage model that every later chapter builds on. You will learn what a broker, topic, partition and offset are, how a record's key decides its partition, and which ordering guarantees follow from that. Spring-specific code comes in later chapters. Here the focus is the model, because most Kafka bugs in Spring applications come from misunderstanding it.
Prerequisites
This chapter assumes you have the following:
- Java and basic Spring Boot knowledge: beans, dependency injection and
application.yml. - Familiarity with Maven or Gradle dependencies.
- A basic idea of publish/subscribe messaging, where producers send messages and consumers receive them without knowing each other.
- The ability to run a local Kafka broker, for example with Docker.
You do not need to know the Kafka client API yet.
The big picture
Apache Kafka is a distributed log. Producers append records to the end of a log. Consumers read records from that log at their own pace. Kafka does not delete a record when it is read. It keeps records for a configured retention period (seven days by default) or until a size limit is reached, and any number of consumers can read the same data independently.
Four terms describe where data lives:
| Term | Meaning |
|---|---|
| Broker | A Kafka server. It stores partitions and serves producers and consumers. A cluster has several brokers. |
| Topic | A named category of records, such as `orders`. |
| Partition | One ordered, append-only log that belongs to a topic. A topic has one or more partitions. |
| Offset | The position of a record inside one partition. |
Records
A record is the unit of data in Kafka. It has these parts:
- A key, which is optional. It is used to choose the partition.
- A value, which is the payload. In this tutorial it will be an
OrderEventserialized as JSON. - Headers, which are optional key/value metadata.
- A timestamp.
Kafka stores keys and values as byte arrays. It does not know or care what they contain. Turning Java objects into bytes and back is the job of serializers and deserializers, which a later chapter covers.
Topics
A topic is a name that producers write to and consumers subscribe to. It is a logical grouping only. The physical storage is the set of partitions behind it. You create a topic with a name, a partition count and a replication factor, either with the Kafka command-line tools or, as shown in a later chapter, with a NewTopic bean.
A topic is not a queue. In a queue, a message is usually removed once a consumer takes it. In Kafka, the topic keeps the records, and each consumer tracks its own position. This difference explains most of Kafka's behavior.
Partitions
A partition is a single ordered log. Records in it are written only at the end, and they are never modified. Partitions give Kafka two properties.
- Parallelism. Different partitions can live on different brokers and can be read by different consumers at the same time. The partition count sets the upper limit on how many consumers in one group can work in parallel. Consumer groups are the subject of the next chapter.
- Ordering within a partition. Records in one partition are read in the order they were written. Kafka makes no ordering promise across partitions.
The second point is the one that matters most when you design a system. If you need events for the same order to be processed in sequence, they must be in the same partition.
How a record chooses its partition
The producer picks the partition when it sends a record. The rules of the default partitioner are:
- If the send names a partition explicitly, that partition is used.
- Otherwise, if the record has a key, the partition is a hash of the key modulo the partition count. The same key always maps to the same partition, as long as the partition count does not change.
- Otherwise, if the key is
null, the producer spreads records across partitions. Recent Kafka clients use a "sticky" strategy: they fill a batch for one partition, then move to another.
The Spring example later in this tutorial uses event.orderId() as the key. All events for one order then land in one partition and are read in order, while different orders spread across partitions.
Changing the partition count
You can add partitions to an existing topic, but you cannot remove them. Adding partitions changes the result of hash(key) % partitionCount. A key that used to map to partition 1 may now map to partition 4. New records for that key go to a different partition than its older records, so per-key ordering breaks across the change. Choose the partition count with future growth in mind, and avoid changing it on topics where key-based ordering matters.
Offsets
An offset is a number that identifies a record's position inside one partition. The first record is offset 0, the next is 1, and so on. Offsets are:
- Per partition. Offset 5 in partition 0 and offset 5 in partition 1 are unrelated records.
- Assigned by the broker when the record is appended.
- Never reused or changed, even if older records are deleted by retention.
To identify a record uniquely you need three values: topic, partition and offset.
Consumer position and committed offset
A consumer tracks two things for each partition it reads:
- The position, which is the offset of the next record it will fetch. This lives in the consumer's memory.
- The committed offset, which is the last position the consumer has saved to Kafka. Kafka stores committed offsets in an internal topic named
__consumer_offsets, keyed by consumer group, topic and partition.
If a consumer restarts, it resumes from the committed offset. This is why the commit timing matters:
- If you commit before processing and then crash, the record is lost to your application. This is at-most-once processing.
- If you process before committing and then crash, the record is read again after restart. This is at-least-once processing.
A later chapter covers how Spring handles commits. For now, remember that the committed offset is the consumer's bookmark, not a property of the record.
Starting position
When a consumer group has no committed offset for a partition, the auto.offset.reset setting decides where to start:
| Value | Behavior |
|---|---|
| `earliest` | Start at the oldest record still retained. |
| `latest` | Start at the end and read only new records. This is the default. |
| `none` | Throw an exception. |
The configuration in the next chapters sets auto-offset-reset: earliest. This setting applies only when no committed offset exists, or when the committed offset points to a record that retention has already deleted. It does not override an existing committed offset.
Replication and leaders
Each partition is copied to several brokers. The topic's replication factor is the number of copies. For each partition, one replica is the leader and the rest are followers.
- Producers and consumers talk to the leader of each partition.
- Followers copy the leader's log.
- Followers that are fully caught up form the in-sync replica set (ISR).
- If a leader fails, one of the in-sync followers becomes the new leader.
A replication factor of 1 means no copies. It suits a local development broker, and it is what the later NewTopic example uses. A production topic usually uses 3. The acks producer setting, covered in the delivery guarantees chapter, controls how many replicas must confirm a write.
Retention and compaction
Kafka removes old data by policy, not by consumption. Two cleanup policies exist:
- Delete (the default). Segments older than
retention.ms, or beyondretention.bytes, are removed. - Compact. Kafka keeps at least the latest record for each key and discards older records with the same key. This suits topics that represent current state, such as a customer profile.
Retention explains why a slow or stopped consumer can lose data. If it falls behind by more than the retention period, the records it needs are deleted, and its committed offset becomes invalid.
Seeing the model on a real broker
You can inspect all of this with the tools that ship with Kafka. These commands assume a local broker at localhost:9092 and that you run them from the Kafka installation directory. Docker users can run them inside the broker container.
Create a topic with three partitions:
bin/kafka-topics.sh --bootstrap-server localhost:9092 \
--create --topic orders --partitions 3 --replication-factor 1Describe it to see the leader and replicas of each partition:
bin/kafka-topics.sh --bootstrap-server localhost:9092 \
--describe --topic ordersSend keyed records from the console. The parse.key and key.separator properties let you type key:value on each line:
bin/kafka-console-producer.sh --bootstrap-server localhost:9092 \
--topic orders \
--property parse.key=true --property key.separator=:Type lines such as o-1:created, o-1:paid and o-2:created. Then read them back and print the partition and offset of each record:
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 \
--topic orders --from-beginning \
--property print.key=true \
--property print.partition=true \
--property print.offset=trueBoth o-1 records appear in the same partition with consecutive offsets. The o-2 record may appear in another partition. Records from different partitions can be printed in any interleaving, which shows that Kafka does not order across partitions.
Common mistakes
- Expecting global ordering. Ordering holds only inside one partition. If a design needs a total order over a whole topic, use a single partition and accept that it limits parallelism.
- Using
nullkeys and expecting related records to stay together. Without a key, related events can spread across partitions and be processed out of order. - Choosing a skewed key. If most records share one key, one partition receives most of the traffic. That partition becomes a hot spot, and its consumer becomes the bottleneck.
- Setting too few partitions. The partition count limits consumer parallelism, and increasing it later disturbs key mapping.
- Setting too many partitions. Each partition adds open files, replication traffic and recovery time on the brokers. Size the count to your expected throughput and consumer count.
- Treating offsets as global IDs. An offset is meaningful only together with its topic and partition.
- Assuming a read removes a record. Records stay until retention or compaction removes them.
Summary
A topic is a named stream split into partitions. Each partition is an append-only log whose records are numbered by offset. The producer's key decides the partition, and ordering is guaranteed only within a partition. Consumers track their own progress with committed offsets stored in Kafka, and brokers keep data for a retention period regardless of reads. Replication copies each partition to several brokers, with one leader serving traffic.
Exercise
A topic named payments has 4 partitions. Your service sends events with the account ID as the key. Events for account A-17 must be processed in the order they were sent. An operator then increases the topic to 8 partitions. What can go wrong for account A-17, and why?
Show answer
Before the change, hash("A-17") % 4 always gave the same partition. After the change, the result is hash("A-17") % 8, which can be a different partition. New events for A-17 can then go to a new partition while older events are still unread in the old one. Kafka only orders records within a partition, so a consumer can process a newer event before an older one. To avoid this, choose the partition count up front, or plan a migration (for example, drain the old topic, then switch) before adding partitions.
Exercise
A consumer group has committed offset 120 on partition 2 of orders and then restarts with auto.offset.reset set to latest. Where does it resume reading, and when would auto.offset.reset matter?
Show answer
It resumes at offset 120, because a committed offset exists and auto.offset.reset is ignored in that case. The setting matters only when the group has no committed offset for the partition (for example, a new group), or when the committed offset refers to a record that retention has already deleted.
Exercise
You run the console consumer with --from-beginning on a topic that has three partitions. The records for key o-1 appear in order, but the output mixes records from o-1 and o-2 differently each time. Is this a bug? Explain.
Show answer
No. Records with the same key go to the same partition and keep their order. Records with different keys may be in different partitions, and Kafka gives no ordering guarantee between partitions. The consumer fetches from the partitions independently, so the interleaving can vary between runs.