Managed messaging
Mid-level Frequently asked 5 min
On this page
The question
What is the difference between a queue and a topic?
30-second answer
A queue is point-to-point: producers put messages in, and competing consumers take them out, each message processed by one consumer and then deleted. It spreads work and buffers bursts. A topic is publish-subscribe: each message is copied to every subscriber, so several services react to one event without the producer knowing them. Often you combine them: a topic fans out to a queue per subscriber, so each service gets every message and keeps it while it is down.
Understand it
Queue vs pub/sub fan-out
CompareA queue: three copies of one service compete for messages, and each message is processed by exactly one of them. Add workers to go faster.
View as text
A producer sends three messages, m1 to m3, to a broker, which delivers them to three consumers; each consumer shows what it received. Four facts follow: who gets each message, what happens when a consumer is down, ordering and replay.
Queue: worker 1 gets m1, worker 2 gets m2, worker 3 gets m3. A queue: three copies of one service compete for messages, and each message is processed by exactly one of them. Add workers to go faster.
Pub/Sub: billing gets m1 m2 m3, email gets m1 m2 m3, analytics gets down: m3 lost. A topic: every subscriber gets its own copy of each message, so billing, email and analytics all react. A subscriber down too long misses messages.
Topic + queues: billing gets m1 m2 m3, email gets m1 m2 m3, analytics gets down: m3 waits. Fan-out with a queue per subscriber, such as SNS to SQS: every service still gets every message, and one that is down catches up from its own queue.
Kafka log: billing gets offset 3 of 3, email gets offset 3 of 3, new search gets replays from 0. A managed log, such as managed Kafka: messages stay for the retention period, each consumer group reads at its own offset, and a new service can replay history.
A producer sends three messages, m1 to m3, to a broker, which delivers them to three consumers; each consumer shows what it received. Four facts follow: who gets each message, what happens when a consumer is down, ordering and replay.
Queue: worker 1 gets m1, worker 2 gets m2, worker 3 gets m3. A queue: three copies of one service compete for messages, and each message is processed by exactly one of them. Add workers to go faster.
Pub/Sub: billing gets m1 m2 m3, email gets m1 m2 m3, analytics gets down: m3 lost. A topic: every subscriber gets its own copy of each message, so billing, email and analytics all react. A subscriber down too long misses messages.
Topic + queues: billing gets m1 m2 m3, email gets m1 m2 m3, analytics gets down: m3 waits. Fan-out with a queue per subscriber, such as SNS to SQS: every service still gets every message, and one that is down catches up from its own queue.
Kafka log: billing gets offset 3 of 3, email gets offset 3 of 3, new search gets replays from 0. A managed log, such as managed Kafka: messages stay for the retention period, each consumer group reads at its own offset, and a new service can replay history.
Takeaway: A queue hands each message to one of many competing workers. A topic copies each message to every subscriber. Give each subscriber its own queue for durability, or use a log when consumers must replay.
| Concept | AWS (Amazon Web Services) | Azure | GCP (Google Cloud Platform) |
|---|---|---|---|
| Queue | SQS (Simple Queue Service) | Service Bus queues, Storage Queues | Pub/Sub pull subscription, Cloud Tasks |
| Topic, fan-out | SNS (Simple Notification Service), EventBridge | Service Bus topics, Event Grid | Pub/Sub |
| Managed log | MSK (Managed Streaming for Apache Kafka), Kinesis | Event Hubs, with a Kafka API | Managed Service for Apache Kafka |
| Messages that keep failing | DLQ (dead-letter queue) | Dead-letter subqueue | Pub/Sub dead lettering |
In code
@Service
class InvoiceJobs {
private final SqsTemplate sqs;
InvoiceJobs(SqsTemplate sqs) { this.sqs = sqs; }
void request(long orderId) {
sqs.send("invoice-jobs", new InvoiceJob(orderId));
}
// Each message reaches one of the running instances. While one works on it, the message is invisible
// to the others; if this method throws, it reappears after the visibility timeout and is retried.
@SqsListener("invoice-jobs")
void handle(InvoiceJob job) {
invoices.create(job.orderId());
}
}resource "aws_sns_topic" "order_placed" {
name = "order-placed"
}
resource "aws_sqs_queue" "billing_dlq" {
name = "billing-dlq"
}
resource "aws_sqs_queue" "billing" {
name = "billing"
visibility_timeout_seconds = 60
redrive_policy = jsonencode({
deadLetterTargetArn = aws_sqs_queue.billing_dlq.arn
maxReceiveCount = 5 # after 5 failed attempts, park it
})
}
resource "aws_sns_topic_subscription" "billing" {
topic_arn = aws_sns_topic.order_placed.arn
protocol = "sqs"
endpoint = aws_sqs_queue.billing.arn
raw_message_delivery = true
filter_policy = jsonencode({ country = ["DE", "FR"] })
}@SqsListener("payments-jobs")
void charge(OrderPlaced event) {
Wrong payments.charge(event.orderId(), event.amount());
}
@SqsListener("payments-jobs")
void chargeOnce(OrderPlaced event) {
Right if (processed.markIfNew(event.eventId())) { // a unique insert: false if already seen
Right payments.charge(event.orderId(), event.amount());
Right }
}Solve it
Send every placed order to billing, email and analytics, which is down each night
When an order is placed, billing must create an invoice, email must send a confirmation, and analytics must record it. Analytics is offline for an hour every night for maintenance, and email only cares about orders from Germany and France. The first draft calls the three services over HTTP, one after the other, from the orders service. Design it with managed messaging.
- Name the shape. One event, several independent reactions: that is publish-subscribe, not a queue. Orders should not know who listens, and a new subscriber should need no change in orders.
- Protect the offline subscriber. A plain topic retries and then drops, so give each subscriber its own queue behind the topic. Analytics’ messages wait in its queue for the hour and are consumed when it returns.
- Filter at the broker. A subscription filter on the email queue, country in DE or FR, means email never receives the rest. Publish the country as a message attribute so the filter can see it.
- Plan for failure and repeats. Each queue gets a dead-letter queue and an alarm, and each consumer is idempotent by event ID, because delivery is at least once. Choose a log instead only if someone must replay old events.
- Check. Stop analytics, place orders, restart it: it processes every one. Place a Spanish order: email’s queue stays empty. Make billing fail five times: the message lands in its dead-letter queue.
public void orderPlaced(Order order) throws JsonProcessingException {
String json = mapper.writeValueAsString(new OrderPlaced(UUID.randomUUID(), order.id(), order.total(), order.country()));
sns.publish(PublishRequest.builder()
.topicArn(orderPlacedTopicArn)
.message(json)
.messageAttributes(Map.of("country", MessageAttributeValue.builder()
.dataType("String")
.stringValue(order.country())
.build()))
.build());
}How to answer
- Queue means work distribution; topic means event notification.
- Consumers of a queue scale by adding instances; subscribers of a topic are different services.
- Delivery is usually at least once, so consumers must be idempotent.
- Products include SQS (Simple Queue Service) and SNS (Simple Notification Service), Service Bus, and GCP (Google Cloud Platform) Pub/Sub.
Common mistakes
- Expecting a queue to deliver each message to several services.
- Assuming exactly-once delivery and skipping idempotency.
Follow-up questions
SQS and SNS, Pub/Sub or Service Bus, or managed Kafka. How do you choose?
Managed queues and topics are serverless: no capacity to plan, pay per message, built-in dead-letter queues, delays and filters, and messages deleted once consumed. They suit commands, jobs and event notifications. Managed Kafka, such as MSK (Managed Streaming for Apache Kafka), Event Hubs or Confluent Cloud, is a retained, partitioned log: high throughput, ordering per key, replay and stream processing, with partitions and consumer groups to design. Choose Kafka when consumers need history or very high volume.
- Service Bus adds sessions, transactions and duplicate detection, closer to a traditional broker.
- Kafka keeps data after reading; queues forget it.
- Cost differs, per request against cluster hours or throughput units.
How do managed queues handle a consumer that crashes in the middle of a message?
A received message is not deleted, only hidden for a visibility timeout, or locked on Service Bus. The consumer deletes or completes it when done. If it crashes or the timeout passes, the message becomes visible again and is redelivered, so delivery is at least once. After a set number of attempts, the maxReceiveCount on SQS, the message moves to a DLQ (dead-letter queue), so one poison message does not block or loop forever.
- Set the visibility timeout above the longest processing time, or extend it while working.
- FIFO (first in, first out) queues keep order per message group and remove duplicates within five minutes.
- Alarm on dead-letter queue depth and redrive after fixing the bug.
Why put a queue behind each subscription of a topic instead of subscribing services directly?
Because a topic pushes and does not store. If an HTTP subscriber is down or slow, the topic retries for a while and then drops or dead-letters the message, and a burst hits every subscriber at full speed. A queue per subscriber keeps that service's copy until it is ready, lets it consume at its own pace and scale workers on queue depth, and gives each service its own retries and dead-letter queue, isolated from the others.
- The producer publishes once; adding a subscriber is adding a queue and a subscription.
- Subscription filters send each queue only the messages its service wants.
- Each queue's consumer still must be idempotent.
GCP Pub/Sub has only topics. How do you build a work queue with it?
With one subscription shared by several consumers. Each subscription receives every message, but the consumers pulling from the same subscription compete, so each message goes to one of them, like a queue. Give each interested service its own subscription for fan-out, and share one subscription between the instances of a service for load sharing.
Check yourself
Show answers
- A topic with a queue per service: Correct. Every service gets its own durable copy of each message.
- One queue that the three services all consume: Incorrect. Competing consumers split the messages; each service sees only some.
- The orders service calls the three over HTTP in sequence: Incorrect. It works until one is down, and couples orders to all three.
Show answers
- A managed Kafka log with a 7-day retention: Correct. A new consumer group can start at the oldest offset and replay.
- An SQS queue: Incorrect. Consumed messages are deleted; nothing remains to replay.
- An SNS topic: Incorrect. A topic pushes to current subscribers and keeps nothing.