Partitions, keys, consumer groups and offsets
Start a single Kafka broker, send keyed events and watch the key decide the partition, then read them with a consumer group that commits explicitly: inspect committed offsets and lag, add events, and replay from the beginning. Learn why partition count caps parallelism and why adding partitions moves keys.
Contentsand lesson path
On this page
- Why it matters
- Start a broker
- Keys choose the partition
- Consumer groups share partitions
- Offsets and explicit commits
- Check your understanding
- Apply it
- Review prompt
Lessons of Messaging & Event Streaming
- Queues, topics and logs Concept · 20 min
- Delivery guarantees and idempotent consumers Concept · 20 min
- Partitions, keys, consumer groups and offsets Concept · 20 min
- Producing and consuming with retries and a dead-letter queue Lab · 30 min
- Load leveling, backpressure, claim checks and broker sizing Worked example · 25 min
- Messaging check Knowledge check · 8 questions
What you will learn
- Design topics, partitions and message keys so related messages stay ordered, and scale consumers with consumer groups and explicit offset commits.
01. Why it matters
A Kafka topic is not one log but several. It is split into partitions, and each partition is an ordered log of its own, stored and served by one broker at a time. Partitions are how Kafka scales: different partitions can be written and read in parallel, on different machines. They are also the limit of ordering: Kafka keeps records in order within a partition, and promises nothing about the order between two partitions.
Three design decisions follow from this, and they are hard to change once a topic is in production. Which key each message carries decides which partition it lands in, and so which messages stay in order relative to each other. How many partitions the topic has caps how many consumers can share the work. And when each consumer commits its offset decides where it restarts after a crash. This lesson lets you see all three on a real broker. You need Docker and Python 3.10 or newer. It was tested with the apache/kafka:3.7.2 image and confluent-kafka 2.16.1 (which bundles librdkafka 2.16.0); the same ideas apply to Kafka 4.x.
02. Start a broker
Create a lab folder; lessons 4 and 5 reuse it. The command starts one Kafka process that acts as both broker and controller (the role that manages cluster metadata; Kafka 4.x runs only in this KRaft mode, without ZooKeeper). It listens on port 19092 to avoid clashing with anything already on 9092. --tmpfs keeps the data in memory, so removing the container leaves nothing behind. The helper kafka.sh runs Kafka's command-line tools inside the container.
The next block waits until the broker answers, creates a virtual environment with the Python client, and creates the orders topic with 3 partitions. Its last line sends one warm-up message with Kafka's own console producer. The first send from an idempotent producer makes the broker create an internal topic for producer ids; without the warm-up, the first Python run would print a harmless Coordinator load in progress: retrying warning while that happens.
mkdir mq-lab && cd mq-lab
docker run -d --name mq-kafka -p 19092:19092 \
--tmpfs /var/lib/kafka/data:mode=1777 \
-e KAFKA_NODE_ID=1 -e KAFKA_PROCESS_ROLES=broker,controller \
-e KAFKA_LISTENERS=PLAINTEXT://:19092,CONTROLLER://:19093 \
-e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://localhost:19092 \
-e KAFKA_CONTROLLER_LISTENER_NAMES=CONTROLLER \
-e KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT \
-e KAFKA_CONTROLLER_QUORUM_VOTERS=1@localhost:19093 \
-e KAFKA_LOG_DIRS=/var/lib/kafka/data \
-e KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 \
-e KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR=1 \
-e KAFKA_TRANSACTION_STATE_LOG_MIN_ISR=1 \
-e KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS=0 \
apache/kafka:3.7.2 > /dev/null#!/usr/bin/env bash
# Run a Kafka command-line tool inside the broker container.
tool=$1; shift
docker exec -i mq-kafka /opt/kafka/bin/"$tool" --bootstrap-server localhost:19092 "$@"chmod +x kafka.sh
until ./kafka.sh kafka-topics.sh --list > /dev/null 2>&1; do sleep 1; done
python3 -m venv .venv && .venv/bin/pip install -q confluent-kafka==2.16.1
./kafka.sh kafka-topics.sh --create --topic orders --partitions 3
echo warm-up | ./kafka.sh kafka-console-producer.sh --topic warm-up 2> /dev/nullCreated topic orders.03. Keys choose the partition
When a message has a key, the producer computes a hash of the key (a number derived from its bytes) and takes it modulo the partition count. The same key always gives the same partition, so all events for one order are stored, and read, in the order they were sent. A message with no key has no such pull: the producer spreads keyless messages over the partitions in batches, which balances load but gives no ordering between them.
The script sends three events (created, paid, shipped) for each of three orders, keyed by order id, and prints where each one landed, sorted by key. It sets two producer options explicitly. partitioner: murmur2_random uses the same hash function as the Java client; librdkafka's default, consistent_random, uses CRC32 instead. enable.idempotence: True stops a retried send from duplicating or reordering events, as lesson 2 explained.
"""Produce the events of three orders, keyed by order id, and print where each landed.
Usage: python keys.py TOPIC [PARTITIONER]"""
import sys
from confluent_kafka import Producer
topic = sys.argv[1]
partitioner = sys.argv[2] if len(sys.argv) > 2 else "murmur2_random"
landed = []
producer = Producer({
"bootstrap.servers": "localhost:19092",
"partitioner": partitioner, # murmur2_random = the Java client's hash
"enable.idempotence": True, # retries cannot duplicate or reorder events
})
for step in ("created", "paid", "shipped"):
for order in ("order-12", "order-13", "order-17"):
producer.produce(topic, key=order, value=step, on_delivery=lambda err, m:
landed.append((m.key().decode(), m.partition(), m.offset(),
m.value().decode())))
producer.flush(10)
for key, partition, offset, value in sorted(landed):
print(f"{key} partition {partition} offset {offset} {value}").venv/bin/python keys.py ordersorder-12 partition 1 offset 0 created
order-12 partition 1 offset 1 paid
order-12 partition 1 offset 2 shipped
order-13 partition 2 offset 0 created
order-13 partition 2 offset 1 paid
order-13 partition 2 offset 2 shipped
order-17 partition 0 offset 0 created
order-17 partition 0 offset 1 paid
order-17 partition 0 offset 2 shippedEach order has its own partition, and inside it the offsets 0, 1, 2 follow the order the events were sent. Now send the same keys through librdkafka's default hash into a second topic and print only the partition of each key:
./kafka.sh kafka-topics.sh --create --topic orders-crc --partitions 3 > /dev/null
.venv/bin/python keys.py orders-crc consistent_random | awk '{print $1, $2, $3}' | uniqorder-12 partition 0
order-13 partition 0
order-17 partition 2With CRC32, order-12 and order-13 share partition 0 and order-17 moved to 2. Each client is consistent with itself, so ordering per key still holds as long as one client writes the topic. If a Java service and a Python service both produce events for the same order with different hash functions, those events land in different partitions and lose their relative order. Pick one partitioner for each topic and set it in every producer.
The modulo has a second consequence. If you later raise the topic from 3 to 6 partitions, hash mod 6 sends many keys to a different partition than before. Old events stay where they are, new events for the same key go elsewhere, and for a while a consumer can see an order's new events before its old ones. Choose a partition count with room to grow, and when you must add partitions, do it while you can pause producers or tolerate brief misordering. A skewed key, such as one customer that sends half of all events, makes one partition hot; adding partitions does not help, because the key still maps to one of them.
04. Consumer groups share partitions
Consumers that use the same group.id form a consumer group. The group divides the partitions among its members so that each partition is read by exactly one member at a time. With 3 partitions, a group of 3 runs at full parallelism. A fourth member gets nothing and waits as a hot standby, so the partition count is the ceiling on useful consumers in one group. Different groups are independent: each one reads all partitions.
Membership changes cause a rebalance, in which partitions are reassigned. It happens when a member joins, leaves cleanly, misses heartbeats for longer than session.timeout.ms, or does not call poll within max.poll.interval.ms because its processing is too slow. With the original "classic" protocol, members pause while the group agrees on a new assignment. Kafka 4.0 made a newer protocol (KIP-848) generally available, in which the broker computes assignments and rebalances incrementally, without stopping the whole group. Clients opt in with group.protocol=consumer; librdkafka 2.16 still defaults to classic, and in the 3.7.2 broker used here the new protocol was only an early-access preview, so the lab uses the classic one.
05. Offsets and explicit commits
Each group stores, per partition, a committed offset: the offset of the next record it wants. It lives in an internal Kafka topic, so it survives restarts of both consumers and brokers. When a group has no committed offset yet, auto.offset.reset decides where it starts: earliest for the oldest retained record, latest for new records only.
By default, clients auto-commit every few seconds, committing whatever poll has returned so far, whether or not your code has finished with it. The consumer below turns that off and commits each record after it has processed it, with commit(message=msg), which stores offset + 1. That is at-least-once: a crash between processing and committing repeats one record. If you hand records to worker threads, commit an offset only when every record before it in that partition is done; otherwise a crash skips the unfinished ones.
"""Read the orders topic in consumer group GROUP, commit after each event, and stop
after LIMIT events (or when nothing new arrives for 5 seconds).
Usage: python consume.py GROUP LIMIT"""
import sys
from confluent_kafka import Consumer
group, limit = sys.argv[1], int(sys.argv[2])
consumer = Consumer({
"bootstrap.servers": "localhost:19092",
"group.id": group,
"enable.auto.commit": False, # we decide when work is done
"auto.offset.reset": "earliest", # a new group starts at the oldest event
})
consumer.subscribe(["orders"])
done = 0
while done < limit:
msg = consumer.poll(5.0)
if msg is None:
break # no new events for 5 seconds
if msg.error():
raise SystemExit(msg.error())
print(f"p{msg.partition()} offset {msg.offset()}: {msg.key().decode()} "
f"{msg.value().decode()}")
consumer.commit(message=msg, asynchronous=False) # stores offset + 1
done += 1
consumer.close().venv/bin/python consume.py shipping 100 | sort -k1,1 -k3np0 offset 0: order-17 created
p0 offset 1: order-17 paid
p0 offset 2: order-17 shipped
p1 offset 0: order-12 created
p1 offset 1: order-12 paid
p1 offset 2: order-12 shipped
p2 offset 0: order-13 created
p2 offset 1: order-13 paid
p2 offset 2: order-13 shippedRecords from different partitions can arrive interleaved in any order, so the output is sorted; within each partition the offsets are in order. Next, ask the broker for the group's position. Lag is the distance between the end of a partition's log and the group's committed offset: how many records are waiting. Save the helper and run it, then produce the nine events again and look a second time.
# Show committed offset, end of log and lag for each partition of group $1.
./kafka.sh kafka-consumer-groups.sh --describe --group "$1" 2>/dev/null |
awk -v g="$1" '$1 == "GROUP" || $1 == g {print $2, $3, $4, $5, $6}' | column -tbash lag.sh shipping
.venv/bin/python keys.py orders > /dev/null
bash lag.sh shippingTOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
orders 0 3 3 0
orders 1 3 3 0
orders 2 3 3 0
TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
orders 0 3 6 3
orders 1 3 6 3
orders 2 3 6 3Each partition now holds 6 records and the group has committed 3, so the lag is 3 per partition. A group that falls behind shows growing lag; that is the main health signal for consumers, and lesson 4 watches it during a burst. Finally, replay: reset the group to the earliest offset while no member is running, then read again. All 18 records come back, because the log keeps them for the topic's retention period (7 days by default) whether or not anyone read them.
./kafka.sh kafka-consumer-groups.sh --group shipping --topic orders \
--reset-offsets --to-earliest --execute | awk 'NF {print $2, $3, $4}' | column -t
.venv/bin/python consume.py shipping 100 | wc -lTOPIC PARTITION NEW-OFFSET
orders 0 0
orders 1 0
orders 2 0
18Leave the broker running for the lab in lesson 4. If you stop here, remove it with docker rm -f mq-kafka; the start command above recreates it with no data.
06. Check your understanding
07. Apply it
For the order-event topic in the skill practice, write down the key you will use and why, the partition count and the expected number of consumers in each group, and when each consumer commits. Then run two copies of consume.py with the same group in two terminals while you produce events, and use lag.sh and kafka-consumer-groups.sh --describe --members to see which member owns which partition.
08. Review prompt
Without looking back, explain: what a partition is and what ordering Kafka keeps; how a key chooses a partition and why two clients can disagree; what happens to keys when partitions are added; why a group cannot use more members than partitions; what triggers a rebalance; what a committed offset means; why auto-commit can skip work; and how to replay a topic.
References
- Apache Kafka 4.4 documentation: Introduction (topics, partitions, consumer groups)
- Apache Kafka 4.4 documentation: Design (consumer position, offsets)
- Apache Kafka 4.4 documentation: Consumer configs
- librdkafka configuration properties (partitioner, group.protocol)
- Apache Kafka 4.4 documentation: Consumer Rebalance Protocol (KIP-848)
- Apache Kafka 4.2 upgrade notes (KRaft only, new consumer protocol)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.