Pub/sub, work queues and Kafka

Topic 6 of 9 in Week 4: Caching, queues and content delivery11 min readIntermediateFree course

Overview

“Put it on a queue” can mean two quite different things. Sometimes you want a job done once by any available worker. Sometimes you want an event announced to every service that cares. This lesson separates the two models and then looks at Kafka, which combines them in a way that has become a backbone of modern architectures.

Work queue vs publish/subscribe

Work queue versus publish and subscribe. In a work queue with competing consumers, a producer adds messages M1 and M2 and each message goes to one of the workers; this suits jobs such as emails, resizing and payments. In pub/sub, a publisher sends to a topic and each message goes to every subscriber, such as an email service, analytics and a search indexer; this suits events such as OrderPlaced and UserSignedUp. Kafka does both: each consumer group gets every message, and inside a group, partitions are shared among members. Examples: SQS and RabbitMQ queues; SNS, Google Pub/Sub and Kafka topics.

Work queue (competing consumers)

Several workers read from the same queue, and each message is delivered to one of them. Adding workers increases throughput. This is how you share out tasks: send these 10,000 emails, resize these images, process these payments.

Publish/subscribe

A publisher sends a message to a topic; every subscription gets its own copy. The publisher doesn’t know who’s listening. This is how you broadcast events: OrderPlaced might be consumed by email, inventory, analytics and fraud services, each independently. New consumers can be added later without changing the publisher.

The two combine naturally: each subscriber service often has its own work queue fed by the topic, with several instances competing to process its copy (SNS topic → one SQS queue per service is a classic AWS pattern).

Commands vs events

A useful naming distinction:

  • A command asks for something to be done, and has one handler: SendWelcomeEmail, ResizeImage. Usually a work queue.
  • An event states that something happened, and can have any number of listeners: UserSignedUp, OrderShipped. Usually pub/sub.

Event-driven designs reduce coupling, but make the overall flow harder to see, so document which services consume which events.

Kafka: a partitioned log

A partitioned log in Kafka. A topic has partitions 0, 1 and 2, each an ordered sequence of messages with offsets 0, 1, 2 and so on, with new messages appended at the end. In the consumer group billing, consumer A reads partition 0 and is at offset 5, and consumer B reads partitions 1 and 2. A key such as order_id always maps to the same partition, so its messages stay in order. Each partition is read by one consumer per group, so partitions are the unit of parallelism. Consumers track their own offset, so they can replay old messages after a bug fix. Other groups such as analytics and search read the same log independently at their own pace.

Kafka (and similar systems such as Amazon Kinesis, Redpanda and Apache Pulsar) doesn’t delete a message when it’s read. Each topic is split into partitions, and each partition is an append-only log kept for a retention period (days, or forever with compaction).

  • Every message has an offset, its position in the partition.
  • Producers choose the partition by key: all messages with key order-981 land in the same partition.
  • A consumer group is one logical subscriber. Kafka assigns each partition to exactly one consumer in the group; the group records how far it has read (its committed offset).
  • Different groups read the same topic independently: billing might be at the latest offset while analytics is an hour behind.

This gives you pub/sub between groups and competing consumers within a group.

Why it matters

  • Replay: after fixing a bug, reset a group’s offset and reprocess the last day of events. A new service can read history to build its own view.
  • High throughput: sequential appends and batching let a cluster handle millions of messages per second.
  • Ordering per key: messages for one key are processed in the order they were written.

Things to know

  • Parallelism is capped by partitions: a group can’t have more active consumers than the topic has partitions. Choose the partition count with growth in mind.
  • Hot partitions: a very busy key overloads one partition. Choose keys with many values.
  • Rebalancing: when consumers join or leave, partitions are reassigned, briefly pausing consumption.
  • Retention costs storage, but makes the log a source of truth for event-driven systems (event sourcing, change data capture).

Ordering

Strict global ordering across all messages is expensive and rarely needed. What usually matters is the order of events for one entity: an order’s statuses, a bank account’s transactions, a chat’s messages. So:

  • key messages by that entity’s ID,
  • process one partition sequentially,
  • make consumers tolerate the occasional duplicate or out-of-order delivery after retries (compare version numbers and ignore stale updates).

Traditional queues offer weaker ordering (SQS standard queues are best-effort; SQS FIFO and RabbitMQ single-consumer queues are ordered with throughput limits).

Choosing

Need Choose
Distribute jobs among workers, simple setup Work queue (SQS, RabbitMQ)
Broadcast events to several services Pub/sub (SNS, Google Pub/Sub, Kafka)
High-volume event streams, replay, per-key ordering Partitioned log (Kafka, Kinesis, Pulsar)
Per-message routing rules, priorities, delays RabbitMQ or a managed queue with those features

Recap

A work queue gives each message to one of several workers; pub/sub gives each message to every subscriber. Kafka-style partitioned logs keep messages after reading, let each consumer group track its own position and replay, and share partitions among a group’s consumers. Ordering holds within a partition, so key messages by the entity whose order matters, and size partitions for the parallelism you need.

Exercise

Design the event flow

A food-delivery platform emits an OrderStatusChanged event every time an order moves through placed → accepted → picked up → delivered. Three teams need these events: notifications (push messages to the customer), analytics (dashboards) and the driver-payout service. Peak is 20,000 events per second. (a) Would you use a work queue or pub/sub, and why? (b) If you use Kafka, how many topics, what message key, and how do the three teams consume? (c) How do you guarantee that a customer never gets 'delivered' before 'picked up'?

Text
(a)
(b)
(c)

Summary

  • In a work queue, each message goes to exactly one of several competing consumers: use it to share out jobs.
  • In publish/subscribe, each message goes to every subscriber: use it to broadcast events to many services.
  • Kafka stores messages in partitioned, append-only logs kept for a retention period; consumers track their own offsets and can replay.
  • Each consumer group receives every message; within a group, each partition is read by one consumer, so partitions limit parallelism.
  • Order is guaranteed only within a partition, so key messages by the entity whose order matters.