Deep Dive into Topics & Partitions
7 min read
Deep Dive into Topics & Partitions
Welcome to the second module of the Apache Kafka course. In the previous section, we established the high-level architecture of Kafka as an Event Streaming Platform. Now, we must open the hood and examine the engine.
To truly master Kafka, one must move beyond treating it as a "black box" queue. The configuration of Topics and Partitions dictates your system's performance, ordering guarantees, and fault tolerance.
1. Topics: Organizing Your Data Streams π
Definition
A Topic is a category or feed name to which records are published. It is the core abstraction in Kafka. Topics in Kafka are always multi-subscriber; that is, a topic can have zero, one, or many consumers that subscribe to the data written to it.
The Problem
Imagine a massive e-commerce platform. You have distinct streams of data being generated simultaneously:
- User login events.
- Payment transactions.
- Inventory updates.
- Shipping notifications.
If all these data points were thrown into a single storage pipeline, the consuming applications would have to filter through millions of irrelevant messages to find the specific data they need. A "Shipping Service" has no business reading "User Login" logs. This would be computationally expensive and architecturally messy.
The Solution
Kafka solves this by introducing Topics. By creating a distinct topic for each category (e.g., user-logins, payments, inventory), producers push data to specific channels, and consumers subscribe only to the channels relevant to them.
Technical Concept: The Append-Only Log
Underneath the abstraction of a Topic is a data structure known as a Log.
- Immutability: Once a record is written to a topic, it cannot be modified. It is immutable.
- Retention: Unlike standard message queues (like RabbitMQ) which often remove messages immediately after consumption, Kafka topics persist data for a configurable amount of time (default is 168 hours, or 7 days) or until a size limit is reached.
Interesting Fact: The "Log" is one of the simplest storage abstractions possible. While Relational Databases struggle with complex B-Trees and index overhead during high-volume writes, Kafka simply appends data to the end of a file. This simplicity is why Kafka can handle millions of writes per second with O(1) disk seek time.
2. Partitions: The Secret to Kafka's Massive Scalability π§©
Definition
A Partition is a distinct, ordered, and immutable sequence of records. A Topic is broken down into one or more partitions.
The Problem
If a Topic were stored as a single file on a single machine, it would inevitably hit a physical limit.
- Storage limit: The server runs out of disk space.
- I/O limit: The server cannot handle the read/write throughput required by a global application.
- Consumer limit: If a topic is a single log, only one consumer can effectively read from it sequentially without complex locking mechanisms.
The Solution
Kafka solves this by Partitioning. A topic is spread across multiple buckets (partitions) which can be hosted on different Kafka Brokers (servers).
- Scalability: By splitting a topic into 10 partitions, you can store that topic across 10 different servers.
- Parallelism: This allows 10 different consumers to read from the topic simultaneously, each reading from a different partition.
Critical Concept: Ordering
This is the most misunderstood concept in Kafka.
- Kafka guarantees ordering ONLY within a partition.
- Kafka does NOT guarantee ordering across the entire topic if it has multiple partitions.
If you send Message A and Message B to Partition 0, Message A will always have a lower offset than Message B. However, if Message A goes to Partition 0 and Message B goes to Partition 1, they are processed independently.
Industry Standard: Partition Keys
How does Kafka decide which partition a message goes to?
- Round Robin: If no key is provided, Kafka cycles through partitions to balance the load.
- Key Hashing: If a Key (e.g.,
user_id) is provided, Kafka hashes the key and maps it to a specific partition.- Result: All events for
user_id: 101will always land in the same partition. This ensures strict ordering for that specific user.
- Result: All events for
3. Offsets: Tracking Where You Left Off in the Stream π
Definition
An Offset is a unique 64-bit integer assigned to every message as it is written to a partition. It acts as a unique identifier for the record within that specific partition.
The Problem
In a streaming system, the producer and consumer are decoupled. The producer might write 1,000 messages while the consumer is offline. When the consumer comes back online, how does it know what it has already read? How do we prevent the consumer from re-reading old data or missing new data?
The Solution
Kafka uses Offsets as pointers.
- Consumers track their progress by "committing" their current offset.
- In modern Kafka, these committed offsets are stored in a special internal topic called
__consumer_offsets.
If a consumer crashes after reading message #5, upon restarting, it asks Kafka: "What was my last committed offset?" Kafka replies: "5". The consumer then resumes reading at message #6.
Imagination Check: Think of a partition like a ruler. The measurements (0cm, 1cm, 2cm) are the offsets. They never change. You (the consumer) place your finger at the mark you are currently reading. If you walk away and come back, you need to remember where your finger was.
4. Replication: Keeping Data Safe When Servers Fail π‘οΈ
Definition
Replication involves storing copies of the same partition on multiple brokers. The Replication Factor determines how many copies exist.
The Problem
Hardware fails. It is not a matter of if, but when. If a broker hosting Partition 0 of your "Payments" topic catches fire or has a disk corruption, and that is the only copy, your data is gone forever. In banking or medical systems, this is catastrophic.
The Solution
Kafka utilizes a Leader-Follower model for replication.
- Leader: One broker is elected as the Leader for a partition. All writes and reads go to the Leader.
- Followers: Other brokers are passive Followers. They simply replicate data from the Leader.
If the Leader broker fails, one of the Followers that is "In-Sync" (caught up with the leader) is automatically elected as the new Leader.
Industry Standard: Replication Factor of 3
The standard production setting is a Replication Factor (RF) of 3.
- 1 Leader.
- 2 Followers.
- Tolerance: You can withstand the simultaneous failure of N-1 brokers (where N is the replication factor) if configured correctly, but typically RF=3 allows for 1 broker maintenance and 1 broker failure simultaneously without data loss.
π¨βπ» Hands-On: Managing Topics and Partitions
We will use the Kafka CLI tools to apply these concepts.
Prerequisite: Ensure your Kafka environment (KRaft or Zookeeper mode) is running.
1. Creating a Topic
We will create a topic named payment-transactions with 3 partitions and a replication factor of 1 (assuming a single-node local setup).
# Navigate to your Kafka directory
bin/kafka-topics.sh --create \
--topic payment-transactions \
--bootstrap-server localhost:9092 \
--partitions 3 \
--replication-factor 1Breakdown:
--bootstrap-server: The entry point to your Kafka cluster.--partitions 3: We are splitting this topic into 3 buckets.--replication-factor 1: Only 1 copy (use higher for production clusters).
2. Describing a Topic
To see the internal organization of what we just created:
bin/kafka-topics.sh --describe \
--topic payment-transactions \
--bootstrap-server localhost:9092Output Explanation:
You will see columns for Partition, Leader, Replicas, and ISR.
Partition: 0->Leader: 0Partition: 1->Leader: 0Partition: 2->Leader: 0
(Since we are running locally on Broker 0, it is the leader for all partitions).
3. Modifying Partitions
You can increase partitions, but you cannot decrease them (doing so would delete data).
bin/kafka-topics.sh --alter \
--topic payment-transactions \
--partitions 5 \
--bootstrap-server localhost:9092Warning: Changing the partition count changes the hashing algorithm for keys. If you rely on
user_idmapping to Partition 0, increasing partitions might map that user to Partition 3 in the future. This breaks strict ordering for existing keys. Plan your partition count ahead of time.
π Reference & Further Reading
- Apache Kafka Official Documentation - Topics:
https://kafka.apache.org/documentation/#intro_topics - Confluent - Kafka Topics 101:
https://developer.confluent.io/learn-kafka/kafka-internals/topics/ - Kafka CLI Tools Reference:
https://kafka.apache.org/documentation/#operations - Replication Protocol:
https://kafka.apache.org/documentation/#replication
Summary
- Topics categorize your data.
- Partitions provide scalability and parallelism.
- Offsets track the consumer's position in the log.
- Replication ensures high availability and fault tolerance.
In the next module, we will explore Producers and how to get data into these partitions reliably.
Challenge
You are a platform engineer responsible for setting up Apache Kafka for a new e-commerce application. Your task is to write the kafka-topics.sh command-line instructions to configure the necessary topics based on the requirements below. Assume you are executing these commands from the root of the Kafka installation.
Write the shell commands to perform the following operations in order:
Create a topic named
order-placements. This is a critical topic that requires high availability and must tolerate the failure of up to two brokers. To handle high volume and allow for parallel processing by consumer groups, it should be configured with 12 partitions.Create a second topic named
user-session-events. This topic is used for analytics and can handle lower fault tolerance than orders. It must tolerate the failure of one broker. Given that event ordering per user is critical, and knowing that producers will use auser_idkey, configure it with 8 partitions.After the topics are created, write the command to inspect the detailed configuration of the
order-placementstopic. This command should display the partition count, replication factor, and the leader for each partition.
Expected result
The solution should consist of three distinct kafka-topics.sh commands written in the correct sequence.
bin/kafka-topics.sh --create --topic order-placements --partitions 12 --replication-factor 3
bin/kafka-topics.sh --create --topic user-session-events --partitions 8 --replication-factor 2
bin/kafka-topics.sh --describe --topic order-placements