Sub topic 13
Log-based brokers and partitions
This chapter assumes you know what producers, consumers, acknowledgements, and competing consumers are, and that you have seen why a work queue gives only limited ordering. It covers a different broker design: the append-only log. You will see how partitions, offsets, and consumer groups work, and what you give up compared with a classic queue.
From queue to log
In a classic queue broker such as RabbitMQ, a message is a task. The broker hands it to one consumer. After the consumer acknowledges it, the broker deletes it.
A log-based broker such as Apache Kafka or Redpanda works differently. The broker appends each message to the end of a file-like structure called a log. The broker never deletes a message because a consumer read it. Messages leave the log only when a retention rule removes them, for example "older than seven days" or "log larger than 50 GB".
Consumers do not receive messages by acknowledgement. Each consumer tracks its own position in the log, called an offset. An offset is the sequence number of a message within a partition. Reading a message does not change the log. It only moves that consumer's position.
This has three consequences:
- Many independent consumers can read the same messages without affecting each other.
- A consumer can move its offset back and read old messages again. This is called replay.
- The broker keeps no per-message state for each consumer, only one stored offset per consumer group and partition. This is one reason log brokers reach high throughput.
Partitions
One log on one machine limits throughput and parallelism. A log-based broker splits a topic into partitions. Each partition is its own append-only log with its own offsets.
The producer chooses the partition for each message. The usual rule is to hash the message key and take the remainder modulo the partition count. Messages with the same key always land in the same partition. Messages with different keys may land in different ones.
Ordering inside and across partitions
A partition preserves the order in which messages were appended. Across partitions, there is no ordering guarantee. If all events for one order must be processed in sequence, use the order ID as the key. Every event for that order then goes to one partition and is read in order.
Two events with different keys have no defined order relative to each other. Do not build logic that depends on one.
Consumer groups
A consumer group is a set of consumers that share a topic's work. The broker assigns each partition to exactly one consumer in the group. That consumer reads the partition in order.
- If a group has more partitions than consumers, some consumers read several partitions.
- If a group has more consumers than partitions, the extra consumers sit idle.
- Different groups are independent. A
billinggroup and ananalyticsgroup each receive every message and keep separate offsets.
This is how a log broker provides both work-queue behavior (one group, shared work) and publish/subscribe behavior (several groups, each seeing everything).
The partition count therefore caps parallelism within a group. A topic with 6 partitions can keep at most 6 consumers of one group busy. Increasing the partition count later changes the hash result for keys. Existing keys can move to a different partition, which breaks the per-key ordering across the change. Choose a count with headroom at the start.
Offsets and commits
A consumer periodically commits its offset, which means it tells the broker "I have finished everything before this position". After a crash or restart, the consumer resumes from the last committed offset.
The commit timing sets the delivery guarantee:
- Commit after processing: a crash between processing and committing causes re-reading. This gives at-least-once delivery, so the consumer must be idempotent.
- Commit before processing: a crash after committing loses the unprocessed messages. This gives at-most-once delivery.
This is the same trade-off as acknowledging a message in a queue. The difference is that the commit covers a whole range of messages, not one.
A runnable model
The following Python program models the core ideas without a broker: key-based partitioning, per-partition offsets, committed positions, and replay. It uses hashlib because Python's built-in hash() for strings changes between runs.
import hashlib
class PartitionedLog:
def __init__(self, partition_count):
self.partitions = [[] for _ in range(partition_count)]
def append(self, key, value):
digest = hashlib.md5(key.encode()).hexdigest()
p = int(digest, 16) % len(self.partitions)
self.partitions[p].append((key, value))
return p, len(self.partitions[p]) - 1
class Consumer:
def __init__(self, log, assigned_partitions):
self.log = log
self.committed = {p: 0 for p in assigned_partitions}
def poll(self):
batch = []
for p, start in self.committed.items():
for i, record in enumerate(self.log.partitions[p][start:]):
batch.append((p, start + i, record))
return batch
def commit(self, partition, offset):
self.committed[partition] = offset + 1
def seek_to_beginning(self):
for p in self.committed:
self.committed[p] = 0
log = PartitionedLog(partition_count=2)
for key, value in [("order-1", "created"), ("order-2", "created"),
("order-1", "paid"), ("order-1", "shipped")]:
p, offset = log.append(key, value)
print(f"{key}/{value} -> partition {p}, offset {offset}")
consumer = Consumer(log, assigned_partitions=[0, 1])
for p, offset, (key, value) in consumer.poll():
print("handling", key, value, "from", p, offset)
consumer.commit(p, offset)
print("after commit, poll returns", len(consumer.poll()), "records")
consumer.seek_to_beginning()
print("after replay, poll returns", len(consumer.poll()), "records")The three order-1 events always land in one partition and appear in the order created, paid, shipped. After the commits, poll returns nothing new. After seek_to_beginning, the same four records come back. A queue broker cannot do that once messages are acknowledged.
Rebalancing
When a consumer joins a group, leaves, or stops sending heartbeats, the broker reassigns partitions among the remaining members. This is a rebalance. During it, consumers may pause. A partition that moves resumes from its last committed offset, so any messages processed but not yet committed are processed again.
Keep processing idempotent, and commit often enough that a rebalance does not replay too much. Slow handlers are a common cause of unwanted rebalances, because the broker may decide the consumer is dead.
Retries and dead letters in a log
A log has no per-message acknowledgement, so it has no built-in per-message dead-letter queue. If a consumer cannot process the message at offset 41, it cannot skip it and commit 42 without deciding that the message is dropped. If it keeps retrying, the whole partition stalls behind it. This is head-of-line blocking.
Common approaches:
- Retry a few times in the consumer, then publish the failed message to a separate "dead letter" topic and commit past it.
- Publish failures to a retry topic with a delay, and let the main partition continue.
- Stop and alert, when ordering matters more than progress.
The first two give up strict order for the failed message. Choose deliberately.
Retention and compaction
Retention is time-based or size-based deletion of old segments of the log. A consumer that falls behind by more than the retention period finds its offset no longer exists and must jump forward or restart from the oldest available message. Lag monitoring, covered in a later chapter, warns before this happens.
Some brokers also offer log compaction. Compaction keeps only the latest message for each key and removes older ones. This suits a topic that represents current state, such as "latest address for user 7", instead of a history of events.
Queue broker or log broker
| Aspect | Queue broker (for example RabbitMQ) | Log-based broker (for example Kafka) |
|---|---|---|
| Message after consumption | Deleted on acknowledgement | Kept until retention removes it |
| Replay | Not normally possible | Reset the offset |
| Acknowledgement | Per message | Offset commit for a range |
| Parallelism limit | Number of consumers | Number of partitions |
| Ordering | Per queue, weakened by multiple consumers | Per partition |
| Dead-letter handling | Built in | Built by you |
| Routing flexibility | Rich exchanges and bindings | Topic and key only |
Summary
A log-based broker keeps messages in partitioned, append-only logs. Consumers track offsets, so many groups can read the same data and any group can replay it. Order holds within a partition, parallelism is capped by the partition count, and you build failure handling such as dead-letter topics yourself.
Exercise
A topic has 4 partitions. Consumer group "billing" has 6 consumers. Messages use the customer ID as the key. (a) How many consumers in the group do useful work? (b) A consumer processes the message at offset 10 of a partition, then crashes before committing. What happens after the restart, and what must the consumer code tolerate?
Show answer
(a) Four. Each partition is assigned to exactly one consumer in the group, so two consumers sit idle. (b) The consumer resumes from the last committed offset, which is at or before 10, so it reads and processes the message at offset 10 again. The consumer must be idempotent, for example by recording processed message IDs in the same transaction as the side effect.
Exercise
Your team raises a topic from 3 to 6 partitions while producers use the order ID as the key. Name one risk this creates and one way to reduce it.
Show answer
The hash modulo result changes, so some order IDs map to a different partition than before. Events for one order can then be split across two partitions and be processed out of order during the transition. To reduce the risk, choose a generous partition count up front, or drain the old events before switching, or create a new topic with the new count and migrate producers and consumers to it.