TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท aws ยท messaging ยท queues ยท pub/sub

Amazon SQS and SNS

AWS's managed messaging pair. SQS is a queue that consumers poll, where each message is processed and then deleted; SNS is a pub/sub topic that pushes a copy of every message to each subscriber, and the two combine into fan-out.

14 min6 animations

๐Ÿ“š Builds on๐Ÿ”˜ Idempotency

๐Ÿ–จ๏ธ Cheat sheet

A rack of baskets

A laundrette takes orders all day, but washing is slow work. So the front desk doesn't wait for each load to be washed. It puts each customer's laundry in a numbered basket and sets it on a rack. That rack is the queue.

Attendants come to the rack and ask "any work for me?". The desk lets them take one basket. When the attendant has finished the wash, they tick the basket off the list and the laundrette stops tracking it. Its job is done.

If the rack is empty, an attendant doesn't have to walk off and keep coming back. They can stand by the rack for a little while, and the desk hands them the next basket the moment it arrives.

The front desk and the attendants never talk. If orders pour in faster than attendants can wash, baskets simply pile up on the rack until someone catches up.

What SQS is

Amazon Simple Queue Service (SQS) is a fully managed message queue. It decouples a producer from a consumer: the producer calls SendMessage and moves on, and the consumer pulls work when it's ready.

StepAPI callWhat happens
SendSendMessageThe message is stored durably in the queue
ReceiveReceiveMessageUp to 10 messages (MaxNumberOfMessages, default 1) are returned, each with a receipt handle
DeleteDeleteMessageThe consumer passes the receipt handle once processing succeeds

Consumers poll: SQS never pushes to them. With the default ReceiveMessageWaitTimeSeconds of 0 a receive returns at once, often empty (short polling). Set WaitTimeSeconds up to 20 and the call waits until a message arrives or the time runs out (long polling), which cuts empty responses and cost.

Messages are kept until deleted or until the queue's retention period expires: 4 days by default, configurable from 1 minute to 14 days. A message body can be up to 1 MiB; larger payloads go to S3, with a reference in the message. The queue absorbs bursts: if producers outrun consumers, the backlog grows and you add consumers.

Send, receive, delete5 steps
๐Ÿงบ Basket rack๐Ÿ’Front desk๐Ÿง‘โ€๐Ÿ”งAttendant Kim
Press play and watch it happen!

In the machine

When an attendant takes a basket, it doesn't leave the laundrette's books. It goes into a machine with a timer set to half a minute, and the basket is marked "being washed" so no other attendant picks it up. That waiting time is the visibility timeout.

If the attendant ticks the basket off in time, it's done with. If the attendant trips and never comes back, the timer runs out, the basket goes back on the rack, and another attendant takes it. Nothing is lost.

Now and then the same basket gets washed twice, for example when a slow attendant finishes just after the timer ran out. So careful attendants check "has this one already been washed?" before starting.

Visibility timeout and at-least-once delivery

Receiving a message doesn't remove it. It becomes in flight: hidden from other consumers for the queue's visibility timeout, 30 seconds by default and up to 12 hours. The consumer must call DeleteMessage before the timeout ends. If it crashes or is too slow, the message becomes visible again and is delivered to another consumer.

A consumer that needs longer calls ChangeMessageVisibility to extend the timeout for a message it holds. Set the timeout comfortably above your normal processing time; too short and messages are processed twice while the first attempt is still running.

Standard queues give at-least-once delivery and best-effort ordering. A message can occasionally be delivered more than once, and messages can arrive out of order. Consumers must therefore be idempotent, for example by recording processed message or order ids, so a redelivery does no harm.

The visibility timeout6 steps
๐Ÿงบ Basket rack๐Ÿงบ Basket 1๐Ÿง‘โ€๐Ÿ”งAttendant Kim๐Ÿ™‹Attendant Lee
Press play and watch it happen!

The problem shelf

Some baskets can never be washed: a jammed zip, a stain that won't lift, a "dry clean only" label. Attendants keep taking one, giving up and leaving it, and it keeps going back on the rack, getting in everyone's way.

So the laundrette counts how many times each basket has been taken. After, say, three tries, it moves the basket to the problem shelf, a separate shelf where the manager can look at it later and work out what went wrong. The other baskets keep flowing. Once the problem is fixed, the baskets can be put back on the rack to try again.

Dead-letter queues

A message that fails every time (a poison message) would otherwise be redelivered until retention expires, wasting consumers and hiding real failures. SQS tracks each message's ApproximateReceiveCount. A redrive policy on the source queue names a dead-letter queue (DLQ) and a maxReceiveCount: once its receive count exceeds that limit without the message being deleted, SQS moves it to the DLQ.

A DLQ is an ordinary queue of the same type (a FIFO queue's DLQ must be FIFO). Alarm on its depth, inspect the messages, fix the bug, then use DLQ redrive to move them back to the source queue. Give the DLQ a longer retention period than the source, so moved messages don't expire before anyone looks.

A dead-letter queue5 steps
๐Ÿงบ Basket rack๐Ÿ—„๏ธ Problem shelf๐Ÿงบ Jammed basket๐Ÿงบ Basket 10๐Ÿง‘โ€๐Ÿ”งAttendant Kim๐ŸงManager
Press play and watch it happen!

The strict rail

The ordinary rack is fast, but baskets can come off it slightly out of order, and once in a while twice. For Ana's order that's a problem: "wash my shirt" must be handled before "cancel my shirt".

So the laundrette also has a strict rail. Baskets with the same name tag come off it in exactly the order they went on, and an attendant gets Ana's next basket only after ticking off the one before. The desk also remembers every order slip from the last five minutes, so if the same slip is handed in twice, the second one is quietly thrown away. The strict rail is slower, so use it only when order matters.

FIFO queues

A FIFO queue (its name must end in .fifo) adds ordering and deduplication:

  • Ordering per message group. Every message carries a MessageGroupId. Messages in one group are delivered in the order they were sent, and while one is in flight, later messages of that group are held back. Different groups are processed in parallel, so use something like the order or customer id as the group id.
  • Deduplication. Each message has a MessageDeduplicationId, set by you or derived from a SHA-256 hash of the body when content-based deduplication is on. A message sent again with the same id within the 5-minute deduplication interval is accepted but not added to the queue, so producer retries don't create duplicates.

AWS calls this exactly-once processing, but it covers duplicates entering the queue. A consumer that fails to delete before the visibility timeout still gets the message again, so idempotent handling is still wise. FIFO queues also have lower throughput limits than standard queues (batching and high-throughput mode raise them).

A FIFO queue5 steps
๐Ÿ—‚๏ธ Strict rail๐Ÿ’Front desk๐Ÿง‘โ€๐Ÿ”งAttendant Kim๐Ÿ™‹Attendant Lee
Press play and watch it happen!

The slip copier

The rack has one problem: each basket is taken by one attendant and then it's done. But a new order matters to the washing team, to the ironing team and to the customer, who'd like a text when it's ready.

So next to the racks is a slip copier. Anyone who wants to know about orders signs up. When the front desk feeds it an order slip, the copier prints one for every name on its list and delivers them straight away: one onto the washing rack, one onto the ironing rack, one to the customer's phone. Nobody has to come and ask.

Each team now has its own rack with its own copy. The washing team finishing its copy doesn't touch the ironing team's.

Once a copy is ticked off, it's gone for good, so the laundrette can't hand out last week's orders again.

SNS topics and fan-out

Amazon Simple Notification Service (SNS) is managed publish/subscribe. A publisher calls Publish on a topic, and SNS pushes a copy to every subscription. Supported endpoints include SQS queues, Lambda functions, HTTP/S endpoints, email, SMS, mobile push and Data Firehose. A filter policy on a subscription delivers only the messages whose attributes (or body) match it.

SNS doesn't keep messages for later readers (FIFO topics can optionally archive messages for replay; standard topics can't). It retries failed deliveries according to the endpoint's delivery policy, and a subscription can have its own dead-letter queue, but a subscriber of a standard topic that wasn't subscribed when a message was published never sees it.

The fan-out pattern subscribes several SQS queues to one topic. Each service gets a durable copy in its own queue and consumes it at its own pace, with its own retries and DLQ. The queue's access policy must allow the topic to send to it, and enabling raw message delivery on the subscription passes the original body instead of SNS's JSON envelope. SNS also offers FIFO topics, which deliver only to SQS queues; subscribe FIFO queues to keep order and deduplication end to end.

SQS and SNSKafka
StorageA queue; a message is deleted once processedA log; records stay until retention removes them
Several readersOne queue per reader, filled by SNS fan-outMany consumer groups read one topic, each with its own offsets
ReplayNot possible once deletedRewind an offset and read again
OrderingFIFO queues, per message groupPer partition
DeliverySQS consumers poll; SNS pushesConsumers poll
Fan-out from SNS to SQS5 steps
๐Ÿ’Front desk๐Ÿ–จ๏ธSlip copier๐ŸงบWashing rack๐ŸงบIroning rack๐Ÿ“ฑAna's phone๐ŸงผWashing attendantโ™จ๏ธIroning attendant
Press play and watch it happen!

SQS in a Java app

In a Java program, the plain way is to write the attendant's routine yourself: stand by the rack, take a basket, wash it, tick it off, repeat.

With Spring you can skip the routine. You write the "wash one basket" part and put a label on it, @SqsListener. Spring sends an attendant to stand by the rack, calls your code for each basket, and ticks the basket off only if your code finished without a problem. If it failed, the basket goes back on the rack when its timer runs out.

SQS from Java

With the AWS SDK for Java 2.x you run the long-polling loop yourself, deleting each message after it's processed:

1SqsClient sqs = SqsClient.create();2 3sqs.sendMessage(SendMessageRequest.builder()4        .queueUrl(queueUrl)5        .messageBody(orderJson)6        .build());7 8ReceiveMessageRequest receive = ReceiveMessageRequest.builder()9        .queueUrl(queueUrl)10        .maxNumberOfMessages(10)11        .waitTimeSeconds(20)      // long polling12        .build();13 14while (true) {15    for (Message m : sqs.receiveMessage(receive).messages()) {16        ship(m.body());17        sqs.deleteMessage(DeleteMessageRequest.builder()18                .queueUrl(queueUrl)19                .receiptHandle(m.receiptHandle())20                .build());21    }22}

If ship throws, the message isn't deleted and comes back after the visibility timeout. Publishing to SNS is one call: sns.publish(PublishRequest.builder().topicArn(topicArn).message(orderJson).build()).

Spring Cloud AWS (3.0 and later) wraps the loop in a listener container:

1@SqsListener("orders")2public void onOrder(String body) {3    ship(body);4}

The container long-polls, calls the method for each message and, with the default acknowledgement mode ON_SUCCESS, deletes the message only when the method returns normally. An exception leaves it in the queue to be retried after the visibility timeout, and eventually moved to the DLQ by the redrive policy.

๐Ÿ”ง Going deeper

Batching: SendMessageBatch and DeleteMessageBatch take up to 10 entries per call, which cuts request count and cost at volume. Check each entry's result: a batch call can succeed while individual entries fail.

Lambda as the consumer: with an SQS event source mapping, Lambda does the polling and deletes a batch when the function succeeds. Turn on partial batch responses so one bad message doesn't make the whole batch retry.

@SqsListener in Spring5 steps
๐Ÿงบ Basket rack๐Ÿงบ Basket 1๐Ÿงบ Basket 2๐Ÿค–Spring's attendant๐Ÿง‘โ€๐Ÿ’ปYour washing routine
Press play and watch it happen!

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐ŸŽฏMission: checkout waits for emailMove a slow email sender behind a queue, so checkout answers in under 600 ms.10-minute mission
  • ๐Ÿ””Design a notification systemPush, SMS and email: OTPs in seconds, campaigns to millions.practice problem

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Amazon SQS and SNS, told the same way as the story.
  1. Attendant Kim takes a basket and then trips before ticking it off. What happens to the basket?
  2. One basket can never be washed and keeps coming back. What stops it clogging the rack?
  3. The washing and ironing teams both need every new order slip. How does the laundrette set that up?
  4. The desk hands the same order slip to the strict rail twice, a minute apart. What happens?
  5. A team wants last week's baskets washed again after fixing a mistake. Can the laundrette do that?
Answer every question to check.Passing marks Amazon SQS and SNS as done.
Got the hang of Amazon SQS and SNS? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

โ˜๏ธ AWS from zeroStep 7 of 12

โ† Previous on the path๐Ÿง‘โ€๐Ÿณ AWS Lambda and serverlessNext on the path โ†’๐Ÿ“Œ Amazon DynamoDB

๐Ÿ‘‰ Read next

  • ๐Ÿ“ฌApache KafkaA giant shared notebook. Some apps write notes in it, and others read them, each at their own speed.
  • ๐Ÿ“ขAmazon EventBridgeA school announcements office that reads each notice and sends it to whoever its rulebook names.
  • ๐ŸงฅMessage queues vs event streamsA coat-check pile, where each ticket is handled once, versus a guestbook anyone can reread from any page.