Overview

2 Kafka cluster data architecture

This chapter builds an architectural understanding of a Kafka cluster’s data layer: how topics and partitions organize and scale data flow, how messages are structured, how replication protects availability, and how data is stored and retained on disk. It contrasts streaming topics with state-storage topics by introducing non-compacted versus compacted retention modes. The aim is to equip architects to make decisions about throughput, ordering, durability, and cost before tackling client code.

Data is produced to named topics that are split into partitions, the unit of parallelism and redundancy. Producers append records to specific partitions; offsets mark their position, and consumer groups scale reads by assigning partitions to instances. Ordering is guaranteed only within a partition, so keys are used to co-locate related events while balancing load; changing partition counts later risks reordering. Replication is per topic, with leader–follower roles, in-sync replicas, and write guarantees governed by min.insync.replicas; a common resilient baseline is replication factor 3 with ISR 2, and consumers may read from followers. Practical guidance also covers partition-count selection, the impact on failover and metadata, and avoiding skew.

Messages consist of value (payload) plus key, headers, and timestamp; clients batch messages for efficiency and identify records by the tuple of topic, partition, and offset. Brokers persist logs as segmented files with indices, rely on the OS page cache, and enforce retention by time and/or size, with LogAppendTime often preferred for predictability. When only the latest value per key matters, compacted topics act as a durable changelog: keys are mandatory, deletions use tombstones, and background cleaners rewrite old segments without changing offsets, triggered by dirtiness ratios and compaction lags. The chapter closes with lightweight governance practices—capturing topics, partitions, replication, retention, and message contracts in AsyncAPI—so designs remain discoverable and evolvable.

An illustration of how data is processed and stored in Kafka. Data is organized into topics, which are further divided into partitions. The basic units of information are messages, which contain keys, values, and headers.
Kafka topics, where each distinct type of message is segregated into its designated topic. Here, we have two services functioning as producers, each sending data to its respective topic. Additionally, a single consumer service subscribes to and consumes data from both topics.
A topic is divided into partitions, each with its own index. When a producer sends a message, it specifies the partition to which the message should be directed.
Utilizing partitions for parallel consumption. In this setup, each thread within a service instance is allocated its own partition, with the total number of partitions determining the maximum degree of parallelization achievable.
All the partitions can be assigned to the same consumer instance.
Partitioning messages by customer name. This figure shows how messages related to the same customer are directed to a specific partition, ensuring cohesive data management.
Routing messages to the same service instance for processing
Partitions are distributed across various brokers in the cluster. The replication factor, which specifies the number of partition copies, is determined per topic. In the event of a broker failure, the data remains accessible.
Each partition has one replica designated as the leader, while the others serve as followers.
Selecting the key for the Balances topic. The account number is used as the key, ensuring that messages for the same account are routed to the same partition. This setup guarantees that updates for each account are received in the correct order.
An example of Kafka message
Each message within the partition is assigned an offset.
Kafka log files, index files, and other related files (less relevant for the current discussion)
A topic where only the final message is important for the consumer. The DashboardService is only interested in the latest balances, not their provenance or history.
During the compaction process, the data within a topic is rewritten. For each key, only the latest value is retained, and messages where the value is null are deleted.

Summary

  • Topics act as destinations that group messages together, identified by their unique names.
  • These topics are divided into partitions, facilitating parallel data processing. Message order is guaranteed within each partition. However, no ordering is guaranteed across different partitions within the same topic.
  • Partitions are replicated across different brokers to ensure redundancy, with the number of replicas determined by the replication factor.
  • Messages consist of keys, values, and optional headers, and they also include a timestamp and other metadata. Keys play a crucial role in partitioning, ensuring that messages with the same key are directed to the same partition.
  • The offset signifies a message’s position within a partition, aiding in tracking which messages have been consumed by the consumer.
  • Messages in Kafka are retained based on specific criteria, such as a defined time period, the size of the topic, or a combination of both factors.
  • Messages are consistently persisted on the disk of the broker in batches. To optimize disk usage, expedite read and write operations, and enforce retention policies, the data is partitioned into segments.
  • Specially configured topics, known as compacted topics, store only the latest value for each key in Kafka.
  • The organization of Kafka topics can be documented effectively using AsyncAPI.

FAQ

What is a Kafka topic and how is it used?A topic is a named, logical destination that groups related messages. Producers send messages to a topic by name; consumers subscribe to one or more topic names to read messages. Topic names are unique in a cluster (with internal IDs managed by Kafka).
What are partitions and how do they affect ordering and parallelism?Each topic is split into partitions to enable parallel processing. Producers append messages to a specific partition, where each message receives a monotonically increasing offset. Kafka guarantees ordering only within a single partition; there is no global ordering across a topic.
How do consumer groups scale reads across partitions?A consumer group can have multiple instances, and Kafka assigns each partition to at most one instance in the group. This yields parallel consumption up to the number of partitions. If you don’t need concurrency, a single consumer can read all partitions.
What are message batches and offsets?Clients typically send and fetch messages in batches for efficiency. Within a partition, each message has an offset (starting at 0) that marks its position. The tuple <topic, partition, offset> uniquely identifies a message; offsets are never reused, even after older data is deleted by retention.
What makes up a Kafka message (keys, values, headers, timestamps)?The value is the payload. The key is used primarily for partition selection and for compaction semantics. Headers are key–value metadata (for things like tracing IDs or versions) that can be read without deserializing the payload. Messages also carry a timestamp, typically CreateTime (producer) or LogAppendTime (broker).
How should I choose a message key, and when can I omit it?Pick a key that keeps related events together to preserve per-entity ordering (for example, customer ID or account number). Avoid skewed keys that overload one partition. Keys aren’t about uniqueness; many messages can share a key. If ordering isn’t important (e.g., logs), you can omit the key and allow random distribution.
How does replication work, and what settings improve durability?Each partition has a leader and follower replicas on different brokers. Producers write to the leader; followers pull data asynchronously. In-sync replicas (ISR) are followers caught up with the leader. Strong durability is achieved with acknowledgments from all in-sync replicas and a suitable min.insync.replicas. A common recommendation is replication factor 3 with min.insync.replicas 2. Note: in open-source Kafka, defaults are 1 partition and replication factor 1—update these for availability.
How does data retention work, and which timestamp should I use?Retention removes old data by time (default 7 days), size, or both. For predictable deletion and stability, use LogAppendTime as the message timestamp and include the original event time in the payload. If using CreateTime, brokers can enforce bounds via timestamp validation settings.
How many partitions should I create for a topic?More partitions increase parallelism but add broker and metadata overhead and can slow leader re-election. Changing the count later can break key-based ordering; decreasing isn’t supported. Start with a moderate count (e.g., 9, 12, or 15), avoid prime numbers that distribute poorly across brokers, and benchmark to refine. Use throughput targets to guide the count when possible.
What are compacted topics and when should I use them?Compacted topics retain at least the latest message per key (cleanup.policy=compact), making them useful for state storage like profiles or balances. Keys are mandatory; sending a null value creates a tombstone to mark deletion. Compaction is done by background cleaners on closed segments and can’t be triggered manually. Access remains sequential; consumers read the log to reconstruct the latest state. Tombstones are retained for a period (e.g., log.cleaner.delete.retention.ms) so consumers can observe deletions.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Kafka for Architects ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Kafka for Architects ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Kafka for Architects ebook for free