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.
| Step | API call | What happens |
|---|---|---|
| Send | SendMessage | The message is stored durably in the queue |
| Receive | ReceiveMessage | Up to 10 messages (MaxNumberOfMessages, default 1) are returned, each with a receipt handle |
| Delete | DeleteMessage | The 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.
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 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.
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).
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 SNS | Kafka | |
|---|---|---|
| Storage | A queue; a message is deleted once processed | A log; records stay until retention removes them |
| Several readers | One queue per reader, filled by SNS fan-out | Many consumer groups read one topic, each with its own offsets |
| Replay | Not possible once deleted | Rewind an offset and read again |
| Ordering | FIFO queues, per message group | Per partition |
| Delivery | SQS consumers poll; SNS pushes | Consumers poll |
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();23sqs.sendMessage(SendMessageRequest.builder()4.queueUrl(queueUrl)5.messageBody(orderJson)6.build());78ReceiveMessageRequest receive = ReceiveMessageRequest.builder()9.queueUrl(queueUrl)10.maxNumberOfMessages(10)11.waitTimeSeconds(20) // long polling12.build();1314while (true) {15for (Message m : sqs.receiveMessage(receive).messages()) {16ship(m.body());17sqs.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) {3ship(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.
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.