Queues, topics and logs
Compare the two basic shapes of messaging, the work queue and the partitioned log, by what happens to a message after it is read: who gets it, how long it is kept, whether it can be replayed and how ordering works. Run a tiny model of both, then choose a shape for a workload.
Contentsand lesson path
On this page
- Why it matters
- Work queues: each message goes to one worker
- Logs: messages stay, readers keep a position
- Run both models side by side
- Choosing a shape for a workload
- 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
- Compare work queues, pub/sub topics and partitioned logs (RabbitMQ-style versus Kafka-style streams) by ordering, retention, replay and fan-out, and choose one for a workload.
01. Why it matters
Most systems grow to a point where one part should not wait for another. A web shop accepts an order in a few milliseconds, but charging the card, reserving stock and sending a confirmation email take longer and sometimes fail. A message broker sits between the parts: a producer sends a message (a small record, often JSON) to the broker, and one or more consumers read it later, at their own pace. If a consumer is slow or down, messages wait in the broker instead of being lost.
"Message queue" is used loosely for very different products. RabbitMQ, Amazon SQS and Kafka can all carry an order event, but they disagree about the most important question: what happens to a message after somebody has read it? A work queue deletes it once one consumer confirms it. A log keeps it, and each reader only remembers how far it has read. That single difference decides who receives each message, whether a new service can read old messages, and how ordering and scaling work.
Pick the wrong shape and the problems appear later, in production. Some examples: a team that needs to rebuild a report finds the events already deleted; a job system processes slow jobs in strict order and stalls; two services that should both see every event each see only half. This lesson gives you the vocabulary to avoid those mistakes. Later lessons in this skill add delivery guarantees, partitions and failure handling.
02. Work queues: each message goes to one worker
A work queue (also called a point-to-point queue) holds tasks. Each message is delivered to exactly one of the consumers reading the queue. Several consumers on one queue are called competing consumers: they share the work, so adding a worker raises throughput, and the broker spreads messages over whoever is free.
The consumer confirms each message with an acknowledgement (ack) after it has finished the work. Only then does the broker delete the message. If the consumer disconnects or crashes before acking, the broker puts the message back and delivers it to another consumer. Because each message is acked on its own, a slow message holds up only the worker that has it; the other workers keep taking new messages. That makes queues a good fit for background jobs whose duration varies a lot, such as generating PDFs or resizing images.
Work queues usually offer per-message features that a log does not. A message can be rejected and sent to a dead-letter queue, delayed, or given a priority, so that urgent jobs overtake normal ones (RabbitMQ supports this with the x-max-priority queue argument). The price is that a delivered and acked message is gone. Nobody can read it again, and a new consumer only sees messages that arrive from now on, plus any still waiting.
To send one event to several services with queues, the broker copies it into one queue per service. In RabbitMQ a fanout exchange does this, and this is how queue brokers implement publish/subscribe (pub/sub): every subscriber gets its own copy, and each copy is deleted independently.
03. Logs: messages stay, readers keep a position
A log is an append-only list of records. Producers add records to the end, and each record gets a number called its offset. Reading does not remove anything. Records are kept for a configured retention period, for example seven days or a size limit, and then deleted in bulk, whether or not anyone has read them. Kafka, Amazon Kinesis, Apache Pulsar and RabbitMQ streams work this way.
A reader of a log stores only one thing: the offset of the next record it wants. In Kafka, readers that share a name form a consumer group, and the group stores its committed offsets in the broker. Two different groups have independent positions, so each group receives every record. That gives pub/sub without copying the data. Inside one group, the work is shared, as with competing consumers, but at the level of partitions: Kafka splits a topic into partitions, and each partition is read by one member of the group at a time. Order is kept within a partition, not across the whole topic.
Because records stay, a group can replay: move its offset back and read again. A new service can start from the oldest retained record, and a team that fixed a bug can reprocess last week. The cost is that progress is a single position per partition. If one record cannot be processed, the reader cannot simply skip ahead and come back later, as it could with per-message acks, so the application must handle failures itself (lesson 4 builds this).
04. Run both models side by side
The model below has no network and no broker: two short Python classes that keep messages in memory. The work queue tracks unacked messages per consumer; the log keeps every record and a position per group. Save both files in an empty folder. Any Python 3.9 or newer works, and nothing needs to be installed.
"""Two tiny in-memory brokers: a work queue and a log. No network, no threads."""
from collections import deque
class WorkQueue:
"""Each message goes to one consumer and is deleted when that consumer acks it."""
def __init__(self):
self.ready, self.unacked = deque(), {}
def publish(self, msg):
self.ready.append(msg)
def receive(self, consumer):
msg = self.ready.popleft()
self.unacked[msg] = consumer
return msg
def ack(self, msg):
del self.unacked[msg] # gone for good: nobody can read it again
def consumer_died(self, consumer):
for msg, owner in list(self.unacked.items()):
if owner == consumer: # unacked work goes back to the front
del self.unacked[msg]
self.ready.appendleft(msg)
class Log:
"""Messages are appended and kept; each group only stores how far it has read."""
def __init__(self):
self.records, self.offsets = [], {}
def publish(self, msg):
self.records.append(msg)
def poll(self, group, max_records=10):
start = self.offsets.get(group, 0)
return self.records[start:start + max_records]
def commit(self, group, next_offset):
self.offsets[group] = next_offset
def seek(self, group, offset): # replay: move the group's position back
self.offsets[group] = offsetfrom brokers import Log, WorkQueue
jobs = WorkQueue()
for n in range(1, 6):
jobs.publish(f"job-{n}")
a, b = jobs.receive("worker-a"), jobs.receive("worker-b")
print("queue: worker-a got", a, "and worker-b got", b)
jobs.ack(a)
jobs.consumer_died("worker-b") # b crashed before acking job-2
print("queue: ready again ->", list(jobs.ready))
print("queue: job-1 can be read again?", "job-1" in jobs.ready)
orders = Log()
for n in range(1, 6):
orders.publish(f"order-{n}")
for group in ("billing", "email"): # two groups, each sees every record
batch = orders.poll(group)
orders.commit(group, len(batch))
print(f"log: {group} read", batch)
orders.seek("analytics", 0) # a new group starts from the beginning
print("log: analytics replays", orders.poll("analytics", 3))
print("log: records still stored:", len(orders.records))python3 demo.pyqueue: worker-a got job-1 and worker-b got job-2
queue: ready again -> ['job-2', 'job-3', 'job-4', 'job-5']
queue: job-1 can be read again? False
log: billing read ['order-1', 'order-2', 'order-3', 'order-4', 'order-5']
log: email read ['order-1', 'order-2', 'order-3', 'order-4', 'order-5']
log: analytics replays ['order-1', 'order-2', 'order-3']
log: records still stored: 5Read the output line by line. In the queue, worker-b crashed while holding job-2, so the broker put it back at the front of the ready list, and the next free worker will get it. job-1 was acked and is gone for good. In the log, billing and email each read all five orders, because each group has its own position. analytics joined later and still read from the start, because nothing had been deleted. The real products add durability, networking and many details, but they keep this core behaviour.
05. Choosing a shape for a workload
Compare the two shapes on four questions:
- Ordering. A queue roughly keeps arrival order, but redelivery and several workers break it. A log keeps strict order inside each partition, so related messages can be kept in sequence by sending them to the same partition.
- Retention. A queue keeps a message until it is acked. A log keeps records for a time or size limit, read or not.
- Replay. A queue cannot replay acked messages. A log can, for as long as retention allows.
- Fan-out. A queue needs one copy per subscriber. A log serves any number of groups from one copy.
A log suits streams of facts that several teams read, and that you may need to reprocess: order events, change-data-capture streams, clickstreams. A queue suits tasks: units of work where only completion matters, durations vary, and failed items are retried or parked one at a time. Many systems use both, for example a log of order events and a task queue inside the email service.
The boundary is moving. RabbitMQ streams give RabbitMQ a log with replay. Kafka 4.2 made share groups production-ready: members of a share group can receive records from the same partition, acknowledge or release each record, and the broker counts delivery attempts, which gives queue-style work sharing on a Kafka topic. Check that your broker and client versions support these features before you design around them; the labs in this skill use Kafka 3.7.2, which has consumer groups only.
06. Check your understanding
07. Apply it
The skill practice asks you to run a broker locally and build a consumer group for order events. Before you write code, write down your choice of shape for two flows in your project: the order events that billing, email and a future analytics service read, and one internal task, such as sending receipts. For each, answer the four questions from this lesson (ordering, retention, replay, fan-out) in one sentence, and name the broker feature you would use: a queue with acks, a fanout exchange, a log topic with consumer groups, or a share group.
08. Review prompt
Without looking back, explain: what a broker does for a producer and a consumer; what an ack is and what happens to an unacked message when a consumer crashes; what an offset is and why two consumer groups can both read every record; why a log can replay and a queue cannot; how queue brokers implement pub/sub; and one workload that suits each shape.
References
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.