AlgoViz

Amazon SQS

easy 25 min

Amazon SQS is a managed queue: producers send messages over HTTPS, consumers poll for them, and a message is hidden, not removed, while somebody works on it.

Video lesson · Chapter 1 of 5

Receiving a job does not remove it

0:00 / 3:37

Visibility timeout in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Amazon Simple Queue Service (SQS) is a managed message queue on AWS. One program puts a message in, another takes it out later. There are no servers, disks or partitions for you to size, and no limit on how many messages may wait.

Consumers pull. They call ReceiveMessage, do the work, and call DeleteMessage. Between those two calls the message stays in the queue but is invisible to everybody else. That hidden period is the visibility timeout, and most SQS bugs are a misunderstanding of it.

There are two kinds of queue. A standard queue has nearly unlimited throughput, may deliver a message more than once and may change the order. A FIFO queue keeps order inside a message group and removes duplicate sends, with a throughput quota.

Why it exists

A web request should not wait for a slow job, and a burst should not knock over the service behind it. A queue stores the work until somebody has time. The general ideas (decoupling, competing consumers, at-least-once) belong to queues. This page is about the product.

The reason to choose SQS is mostly what you do not do: no cluster, no replication settings, no disk alarms at night. AWS stores the messages redundantly across Availability Zones. You pay per request instead.

The price of that simplicity is a small feature set. There is no replay, no broadcast and no routing inside the queue. If you need those, you combine SQS with another service or choose another product.

A short history

  1. Late 2004

    AWS announces the first beta of SQS as a hosted queue for buffering messages.

  2. July 2006

    SQS reaches production, with items up to 8 KB.

  3. 2012 to 2014

    Long polling (2012), payloads up to 256 KB (2013) and dead-letter queues (2014) are added.

  4. November 2016

    FIFO queues arrive, with 300 calls per second per action, or 3,000 messages with batches of ten.

  5. 2018

    SQS can invoke AWS Lambda functions.

  6. August 2025

    The largest message grows from 256 KiB to 1 MiB for both queue types.

Words to know

Visibility timeout
How long a received message stays hidden from other consumers. 30 seconds by default, 12 hours at most.
Receipt handle
The ticket you get with one receive. You need it to delete the message or to change its timeout.
In flight
Received but not deleted yet.
Dead-letter queue
Another queue that gets messages which were received too often without being deleted.
Message group
In a FIFO queue, the label inside which order is kept. In a standard queue, only a tenant label for fairness.
Long polling
A receive call that waits up to 20 seconds for a message instead of answering empty.
Redrive
Moving messages from a dead-letter queue back to work.

How it works

Step through the idea, or press Play.

Step 1 of 3

Send. A producer stores a message, SQS keeps copies in several zones

Understand it

Start here

The shoe-shine stall

Imagine a stall where people leave their shoes and put a numbered token on the counter. A helper who takes a pair puts a cup over the token, so nobody else starts on the same shoes. The token is still on the counter. It is only hidden. When the shoes shine, the token goes into the box marked Done.

Tokens under a cup
Shoe shineDoneAsk123Three tokens wait

Hidden is not gone. Only the Done box ends a token.

What you get

Why teams choose it

  • Nothing to run

    No brokers, disks or upgrades. A queue is one API call.

  • Durable

    Copies are kept across several servers and Availability Zones.

  • No backlog limit

    The number of waiting messages is unlimited, for up to 14 days each.

  • Safe retries

    A dead worker needs no detection. The timeout brings the work back.

  • Fits AWS

    Lambda, SNS, S3 events, IAM policies and CloudWatch connect without glue code.

  • Pay per request

    An idle queue costs little. Batches and long polling lower the bill.

A work queue

A web application sends jobs to the orders queue inside an AWS Region. Two workers poll the queue and delete finished messages. Messages that fail too often go to a dead-letter queue, which raises an alarm.
The thick boxes are machines you run. The queue is a managed service: you see an address, not its servers.

Inside

The life of one message

Send, hide, delete

The receipt handle belongs to one receive, not to the message. A later receive gives a new one.

States of a message

A delay hides a message before the first receive. The visibility timeout hides it after one.

The numbers

SettingDefaultRange
Visibility timeout30 seconds0 seconds to 12 hours
Retention4 days1 minute to 14 days
Message size1 MiB at mostfrom 1 byte
Receive wait time0 (short polling)up to 20 seconds
Messages per call1 to 10batches of at most 10
Delivery delay0up to 15 minutes
In flight, standardabout 120,000can be raised on request
In flight, FIFO120,000can be raised on request
Bigger payloads go to object storage with a pointer in the message. The Extended Client Library (Java and Python) does that for up to 2 GB.

The key idea

Choosing the visibility timeout

Too short, and a second worker starts while the first is still busy. Too long, and a crashed worker's message stays hidden for that whole time. Two good answers exist.

  1. 1

    You know the time

    Set the timeout to the longest time that processing and deleting can take, with some margin.

  2. 2

    You do not know it

    Start with a short timeout, for example 2 minutes, and let the worker extend it by 2 minutes every minute while it is alive. This is a heartbeat with ChangeMessageVisibility.

  3. 3

    You failed and you know it

    Set the remaining timeout to 0 and the message is visible at once. Set it to a larger number to wait before the retry.

How many messages are in flight?

L=λ×t1,000 msgs×30 s=30,000L = \lambda \times t \qquad 1{,}000\ \tfrac{msg}{s} \times 30\ s = 30{,}000
λ\lambda is the receive rate and tt the time from receive to delete. With 120,000 allowed in flight and 30 seconds of work, the ceiling is 4,000 messages per second per queue. At the limit, short polling gets an OverLimit error and long polling gets no messages and no error.

Delivery

At least once, so make it idempotent

SQS stores copies on several servers. Rarely, a server that holds a copy is unavailable while you receive or delete, and you may get that message again later. Also, a worker can finish the work and die before the delete. Both end the same way: the work runs twice.

Safe to repeat

  • Use a business id as the key, for example order 42
  • Insert with a unique constraint, or an upsert
  • Commit the result first, delete the message last
  • Keep the seen ids at least as long as retries can happen

Looks safe, is not

  • Delete first, then work: a crash loses the job
  • Use the SQS message id: a producer retry makes a new id
  • Trust the visibility timeout as a lock
  • Assume FIFO means the side effect happens once

The pattern itself has its own page: idempotency.

Two kinds

Standard or FIFO

StandardFIFO
OrderBest effortStrict inside a message group
DuplicatesPossibleDuplicate sends removed for 5 minutes
ThroughputNearly unlimited300 calls per second per action, 3,000 messages with batches
High throughput modeNot needed2,400 to 70,000 calls per second, by Region
NameAnyEnds in .fifo
Message groupOptional, for fairnessRequired, for order
Type can change laterNoNo
With batches of ten, the highest Regions (N. Virginia, Oregon, Ireland) reach up to 700,000 messages per second in high throughput mode.

A group is served in order, groups in parallel

While a is in flight, b and c are not given out. Another group is not affected.

One receive may return several messages of the same group, in order, up to ten. After that the group waits until they are deleted or visible again. A single failing message therefore blocks its group, which is what order means.

Polling

Short, long and batched

Long polling

  • Asks all servers
  • Answers when a message is there, or after up to 20 s
  • Few empty answers
  • Set ReceiveMessageWaitTimeSeconds to 20 on the queue

Short polling (the default)

  • Asks a sample of the servers
  • Answers at once, often empty
  • May miss messages that exist
  • Every empty answer is a request you pay for

What idle polling costs

10×86,4000.1=8,640,00010×86,40020=43,200\frac{10 \times 86{,}400}{0.1} = 8{,}640{,}000 \qquad \frac{10 \times 86{,}400}{20} = 43{,}200
Ten idle workers for one day. Left: a short poll every 0.1 seconds. Right: long polls of 20 seconds. The same readiness for 200 times fewer requests.

Batch calls send or delete up to ten messages in one request. Requests are also billed by size: each 64 KB of payload counts as one request, so one 1 MiB message counts as 16.

Failure

Dead-letter queues

A poison message fails every time. Without a limit it is tried until its retention ends. A redrive policy names another queue and a maxReceiveCount.

What happens to a failing message

Receives are counted, not errors. A worker that takes a message and forgets it also uses up a try.

Rules that save you later

  1. 1

    Same kind, same place

    A dead-letter queue of a FIFO queue is FIFO too. It lives in the same account and Region as its source.

  2. 2

    Longer retention

    For standard queues the age keeps counting from the first send. If the source keeps messages 4 days and the dead-letter queue also 4 days, a message that arrives after 1 day is deleted 3 days later. Use 14 days.

  3. 3

    An alarm on more than zero

    A dead-letter queue nobody watches is a slow way to lose data.

  4. 4

    Fix first, then redrive

    StartMessageMoveTask moves messages back to the source, or to a queue you choose.

  5. 5

    Think about order

    Moving one message aside breaks the order of a FIFO group. If later steps depend on it, stop the group instead.

Consumers

Lambda and your own workers

With an event source mapping, AWS polls for you and calls your function with a batch. When the function succeeds, the batch is deleted. By default one failure makes the whole batch visible again.

TopicAWS LambdaYour own workers
PollingDone for youYou write the loop
ScalingStarts with 5 concurrent batches, adds up to 300 per minute, up to 1,250You scale on backlog per worker
Protecting a databaseMaximum concurrency on the mappingA fixed number of workers
Partial failureReturn batchItemFailuresDelete what worked
Long workLimited by the function timeoutUp to 12 hours with heartbeats
AWS recommends a visibility timeout of at least six times the function timeout, plus the batching window, and a maxReceiveCount of at least 5. AWS Lambda has its own page.

Time to drain a backlog

T=Bn/t−λ360,000400/0.5−600=1,800 sT = \frac{B}{n/t - \lambda} \qquad \frac{360{,}000}{400/0.5 - 600} = 1{,}800\ s
Assume an average of 200 messages per second, so a peak of 600, and 0.5 s per message. 300 busy workers only keep up. With n=400n = 400 workers, a backlog of 360,000 is gone in 30 minutes.

Combine

Broadcast, fairness and other add-ons

One message goes to one consumer group. To give the same event to several teams, put an SNS topic in front and give each team a queue.

One event, three queues

The order service publishes to an SNS topic. The topic copies the event to a billing queue, a stock queue and an email queue. Each queue has its own worker service.
A slow email service grows its own queue and slows nobody else. The pattern belongs to pub-sub.
  1. 1

    Fair queues

    In a standard queue, set the message group to a tenant id. When one tenant has far more messages in flight than others, SQS gives the others priority. It keeps no order, has no throughput limit and needs no change in consumers. It also does not cap the noisy tenant.

  2. 2

    Delay

    A queue-wide delay or a timer per message, up to 15 minutes. Timers on single messages are for standard queues. For later dates use EventBridge Scheduler or a task scheduler.

  3. 3

    Encryption and access

    Encryption at rest uses keys owned by SQS or by KMS. IAM and queue policies decide who may send, receive and delete.

  4. 4

    The dual write problem

    Saving to a database and sending a message are two actions. Use an outbox table or change data capture.

Operations

Running it

Shell
# a dead-letter queue that keeps messages for 14 daysaws sqs create-queue --queue-name orders-dlq \  --attributes MessageRetentionPeriod=1209600# the work queue: long polling, 2 minutes hidden, 5 triescat > attributes.json <<'JSON'{  "VisibilityTimeout": "120",  "ReceiveMessageWaitTimeSeconds": "20",  "RedrivePolicy": "{\"deadLetterTargetArn\":\"$DLQ_ARN\",\"maxReceiveCount\":\"5\"}"}JSON# replace $DLQ_ARN in the file, thenaws sqs create-queue --queue-name orders --attributes file://attributes.jsonaws sqs send-message --queue-url "$URL" --message-body '{"order": 42}'aws sqs receive-message --queue-url "$URL" --max-number-of-messages 10aws sqs delete-message --queue-url "$URL" --receipt-handle "$HANDLE"# after the fix: move the dead letters backaws sqs start-message-move-task --source-arn "$DLQ_ARN"
Only the dead-letter queue's ARN is needed for a redrive to the original source queues.

What to watch in CloudWatch

MetricTells youAct when
Age of the oldest messageHow late the work isIt passes your promise to users
Messages visibleThe backlogIt grows and does not shrink
Messages not visibleIn flightIt nears 120,000
Visible in the dead-letter queueFailed workAbove zero
Number of empty receivesWasted pollingHigh: turn on long polling
Noisy groups and quiet-group metricsFairness between tenantsQuiet groups get old too
Age is the best alarm. A backlog of a million short jobs may be fine, a backlog of ten that is an hour old is not. Counts are approximate.

Choose

When SQS, and when not

Choose SQS

  • Background jobs and buffering between services
  • You are on AWS and want nothing to operate
  • Spiky load in front of a slow or fragile system
  • One logical consumer per message
  • Order only inside small groups

Choose something else

  • Replay of old events: a log such as Kafka or Kinesis
  • Many independent readers: a topic, or a log
  • Routing rules, priorities, very low latency push: RabbitMQ
  • Work that must run on several clouds or on your own machines
  • Stateful stream computation: Flink or Spark

Neighbours

ProductShapePick it over SQS when
KinesisManaged sharded logSeveral readers need the same ordered records, or a replay
KafkaLog you run or rentEvent history is a product of its own
RabbitMQBroker with exchangesYou need routing, priorities or push
PulsarTopic with queue and stream readersYou want both models and can operate it
SNSPush topicBroadcast. Usually together with SQS

Summary

The whole topic in one minute.

A consumer receives a message, which hides it, works, and deletes it. If the delete does not come in time, the message becomes visible and somebody else gets it. So SQS does not lose work when a worker dies, and the same work may be done twice. The consumer must be idempotent.

Choose standard unless order inside a group really matters. Set the visibility timeout longer than the work (or extend it with a heartbeat), use long polling and batches, add a dead-letter queue with an alarm, and watch the age of the oldest message. For replay or many independent readers, use a log or put a topic in front.

  • Receive hides, delete removes, silence returns.
  • Set the visibility timeout above the work, or extend it with a heartbeat.
  • Standard is at-least-once and unordered, so consumers must be idempotent.
  • FIFO orders inside a group and removes duplicate sends for 5 minutes.
  • Long polling and batches of ten cut requests.
  • A dead-letter queue needs longer retention and an alarm.
  • Watch the age of the oldest message.

Sources