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

Compare

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.

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.

Which managed messaging service, asking who must receive each messageIf one worker should do each job, use a queue. If every interested service should hear about an event, use a topic. If a subscriber may be slow or offline, give it its own queue behind the topic. If consumers must replay history or you need high-volume ordered streams, use a managed log such as Kafka.one worker does the jobevery interested servicenoyesmany readers, replay,ordered high volumeWho receiveseach message?QueueCan a subscriber beslow or offline?Topic, pushTopic, a queueper subscriberManaged log:Kafka, Kinesis
Which managed messaging service, asking who must receive each messageIf one worker should do each job, use a queue. If every interested service should hear about an event, use a topic. If a subscriber may be slow or offline, give it its own queue behind the topic. If consumers must replay history or you need high-volume ordered streams, use a managed log such as Kafka.one worker does the jobevery interested servicenoyesmany readers, replay,ordered high volumeWho receiveseach message?QueueCan a subscriber beslow or offline?Topic, pushTopic, a queueper subscriberManaged log:Kafka, Kinesis
Which managed messaging service? Ask who must receive each message
ConceptAWS (Amazon Web Services)AzureGCP (Google Cloud Platform)
QueueSQS (Simple Queue Service)Service Bus queues, Storage QueuesPub/Sub pull subscription, Cloud Tasks
Topic, fan-outSNS (Simple Notification Service), EventBridgeService Bus topics, Event GridPub/Sub
Managed logMSK (Managed Streaming for Apache Kafka), KinesisEvent Hubs, with a Kafka APIManaged Service for Apache Kafka
Messages that keep failingDLQ (dead-letter queue)Dead-letter subqueuePub/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());
    }
}
Spring Cloud AWS: send to a queue, and consume it; a normal return deletes the message
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"] })
}
Fan-out: one topic, a queue per subscriber, a filter and a dead-letter queue
@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     }
}
Delivery is at least once: a redelivered message must not charge twice
Visibility timeout, retries and the dead-letter queueA consumer receives message m1, which becomes invisible to other consumers for 60 seconds. The consumer crashes before deleting it, so m1 becomes visible again and is received again. After the fifth failed receive, the queue moves m1 to the dead-letter queue, where an alarm fires and a person inspects it.billing-dlqConsumerbilling queue... up to 5 receivesm1 (invisible for 60 s)crashes, never deletes m1m1 again, receive count 2m1 moved after the 5th failurealarm, a person inspects
Visibility timeout, retries and the dead-letter queueA consumer receives message m1, which becomes invisible to other consumers for 60 seconds. The consumer crashes before deleting it, so m1 becomes visible again and is received again. After the fifth failed receive, the queue moves m1 to the dead-letter queue, where an alarm fires and a person inspects it.billing-dlqConsumerbilling queue... up to 5 receivesm1 (invisible for 60 s)crashes, never deletes m1m1 again, receive count 2m1 moved after the 5th failurealarm, a person inspects
Visibility timeout, retries and the dead-letter queue

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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());
}
Publish once, with the attribute the filters read; the publisher knows no subscriber

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.

See it in the infographic: Queue vs pub/sub fan-out

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.

See it in the infographic: Queue vs pub/sub fan-out

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.

See it in the infographic: Queue vs pub/sub fan-out

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

1. Billing, email and analytics must all react to each placed order. Which design delivers every order to each of them?
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.
2. A new search service must index every order placed in the last 7 days. Which managed service lets it read them?
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.