Message queues vs pub/sub in system design
A message queue delivers each message to exactly one of its consumers, which makes it a way to share work among workers. Publish/subscribe delivers each message to every subscriber, which makes it a way to tell many independent services that something happened. Log-based brokers such as Kafka do both: consumers in the same group split the messages, while separate groups each get all of them. Pick by asking whether a message is a task for someone to do or an event that several parties care about.
By Evin JohnPublished 6 min read
1. Queues and pub/sub, defined
Both put a broker between producers and consumers so the producer does not wait for the work to finish and does not need to know who handles it. The difference is who receives a message. In a queue (point-to-point), consumers compete: the broker hands each message to one of them, and once it is acknowledged it is gone. In pub/sub, a publisher sends to a topic, and each subscription receives its own copy. Adding a new subscriber does not change the publisher at all.
2. Why interviewers ask about it
Asynchronous messaging appears in most designs past the basics: sending notifications, processing uploads, updating search indexes, feeding analytics. Interviewers check whether you pick the right shape, and whether you can answer the hard follow-ups: what if a consumer crashes mid-message, what if the same message arrives twice, does order matter, and what happens when consumers fall behind.
3. Side by side
| Message queue | Pub/sub | Log-based (Kafka-style) | |
|---|---|---|---|
| Who gets a message | One consumer | Every subscription | One consumer per group; every group |
| After processing | Deleted once acknowledged | Deleted per subscription once acknowledged | Kept until retention expires; consumers track offsets |
| Replay old messages | No | Usually limited | Yes, by resetting the offset |
| Ordering | Often best effort; FIFO variants exist | Varies; often per key with options | Strict within a partition |
| Scaling consumers | Add workers freely | Each subscription scales on its own | Up to one active consumer per partition in a group |
| Typical use | Background jobs, task distribution | Notifications to many services | Event streams, CDC, analytics pipelines |
import zlib
from collections import defaultdict
class Topic:
def __init__(self, partitions: int):
self.parts = [[] for _ in range(partitions)]
self.offsets = defaultdict(int) # (group, partition) -> next offset
def publish(self, key: str, value: str) -> None:
p = zlib.crc32(key.encode()) % len(self.parts) # same key, same partition
self.parts[p].append((key, value))
def poll(self, group: str, partition: int):
off = self.offsets[(group, partition)]
batch = self.parts[partition][off:]
self.offsets[(group, partition)] = off + len(batch) # commit after handling
return batch
t = Topic(partitions=2)
for i, user in enumerate(["ana", "bo", "ana", "cy", "bo"]):
t.publish(user, f"event-{i}")
t.poll("billing", 0) # [('ana', 'event-0'), ('ana', 'event-2')]
t.poll("billing", 1) # [('bo', 'event-1'), ('cy', 'event-3'), ('bo', 'event-4')]
t.poll("email", 0) + t.poll("email", 1) # all five events again4. Delivery guarantees and ordering
| Guarantee | How you get it | Risk |
|---|---|---|
| At most once | Acknowledge before processing | A crash mid-processing loses the message |
| At least once | Acknowledge after processing | A crash after the work but before the ack causes a redelivery: duplicates |
| Effectively once | At least once plus idempotent consumers, or broker transactions that commit offsets and outputs together | Needs design work; "exactly once" claims usually cover only part of the path |
- Idempotent consumers. Store a processed-message ID, or make the effect naturally repeatable (set a status, upsert by key), so a duplicate does nothing.
- Visibility timeouts and acks. In queue services, a received message is hidden for a while; if not acknowledged in time it reappears for another worker. Set the timeout longer than the work, or extend it.
- Ordering by key. Put all messages for one account or one conversation under the same key so they land in one partition or one FIFO group. Global ordering across everything would limit you to one consumer.
- Retries and dead letters. Retry with backoff a few times, then move the message to a dead-letter queue for inspection, so one poison message does not block the rest.
5. Broker families
| Broker | Model | Notes |
|---|---|---|
| RabbitMQ | Queues with exchanges (direct, fanout, topic) for routing | Flexible routing; queues and pub/sub in one; messages removed when acknowledged |
| Amazon SQS and SNS | SQS is a queue; SNS is pub/sub | A common pattern publishes to SNS and subscribes several SQS queues for durable fan-out |
| Apache Kafka | Partitioned, replicated log with consumer groups | Retention and replay; high throughput; ordering per partition |
| Google Cloud Pub/Sub | Managed pub/sub with subscriptions | Each subscription can have many workers sharing its messages |
| Redis Streams | Append-only stream with consumer groups | Light option when Redis is already in the design |
6. Backpressure and consumer lag
A broker absorbs bursts: if producers send 10,000 messages a second for a minute and consumers handle 5,000, the backlog grows to 300,000 and drains after the burst. That is the point. But a backlog that only grows means consumers are under-provisioned or stuck. Watch queue depth or consumer lag, autoscale workers on it, and set a limit: retention for logs, maximum length or message age for queues, after which you shed or divert work. In a log-based broker, remember that a group cannot use more active consumers than there are partitions, so choose the partition count with growth in mind.
7. How it shows up in common prompts
| Prompt | Shape | Why |
|---|---|---|
| Notification system | Pub/sub to channel services, queues per channel | One event fans out to email, push and SMS, each with its own workers and retries |
| Job scheduler | Queue | Each due job goes to one worker |
| Web crawler | Queues partitioned by host | Politeness and even work distribution |
| Per-user or per-conversation ordering by key | Messages in a chat must arrive in order | |
| Search autocomplete | Log of query events | Aggregators and index builders read the same stream |
When messages describe business facts that several services react to, you are designing event-driven architecture. When a consumer must be the only one acting on a key, partitioning by key is often a cleaner answer than a distributed lock.
8. Mistakes to avoid
- Assuming exactly-once delivery. Plan for duplicates.
- Acknowledging before the work is durable. A crash loses the message.
- One global order. Order per key instead; global order kills parallelism.
- No dead-letter queue. A single malformed message can stall a partition forever.
- Using a queue when several services need the event. The second service will steal messages from the first.
- Too few partitions. You cannot scale a consumer group past the partition count.
9. How to talk about it in the interview
- Say whether each message is a task (queue) or an event (pub/sub), and name the broker family.
- State the delivery guarantee and how consumers handle duplicates.
- Give the ordering key and the partition count reasoning.
- Explain retries, dead letters and how you watch lag.
Fictional example
- Interviewer
- When an order is placed, we charge the card, reserve stock, email the customer and update analytics. How do the services talk?
- Candidate
- Charging the card stays synchronous, because the user is waiting for the answer. After it succeeds, the order service publishes OrderPlaced to a topic keyed by order ID.
- Candidate
- Inventory, email and analytics each have their own subscription or consumer group, so each sees every order and scales on its own. Inside the email group, several workers share the load.
- Interviewer
- What if the email worker crashes after sending?
- Candidate
- It gets the message again, so it records sent order IDs and skips duplicates. After five failed attempts a message goes to a dead-letter queue and we alert.
Practicing with Natively
Messaging questions test whether you can talk through failure cases in order, which is a skill you build by saying it out loud. In a mock interview, Natively transcribes what both of you say and can offer talking points for each follow-up, and reviewing the transcript afterwards shows whether you covered duplicates, ordering and dead letters. It can also read a screenshot of a prompt or a diagram you capture and explain it.
Questions people ask
What is the difference between a message queue and pub/sub?
A message queue delivers each message to one of its consumers, so workers share the load. Pub/sub delivers each message to every subscription, so several independent services can react to the same event.
Is Kafka a queue or pub/sub?
It is a partitioned log that can act as both. Consumers in the same group split the partitions between them, like a queue, while separate groups each read every message, like pub/sub. Messages stay for a retention period, so consumers can replay.
What does at-least-once delivery mean?
The broker redelivers a message until a consumer acknowledges it, so nothing is lost, but a consumer that crashes after doing the work and before acknowledging will see it again. Consumers must therefore handle duplicates.
How do you keep messages in order?
Order is usually guaranteed only within a partition or FIFO group. Give all messages for one entity, such as an account or conversation, the same key so they land in the same partition and are processed in sequence.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
