SQS for Developers
Overview
Amazon SQS is a managed message queue that lets one part of your application hand work to another without waiting. Producers send messages; consumers poll and process them at their own pace, so spikes are absorbed and failures are isolated.
Imagine a post box outside a workshop. Customers drop in job slips whenever they like, and workers take a slip, do the job and only then throw it away. If a worker walks away mid-job, the slip is put back for someone else after a while. That "put back" delay is the visibility timeout.
For developers, the details matter: how to poll efficiently, how to delete correctly, how to handle duplicates and poison messages, and how to pick between standard and FIFO queues.
Key Concepts
- Standard queue: nearly unlimited throughput, at-least-once delivery, best-effort ordering. FIFO queue: ordering per message group ID and exactly-once processing via deduplication.
- A received message stays invisible for the visibility timeout (default 30 s, max 12 h); delete it with its receipt handle after success.
- Long polling (
WaitTimeSecondsup to 20) lowers cost and empty responses; prefer it to short polling. - Dead-letter queue with
maxReceiveCountisolates poison messages; DLQ redrive moves them back after fixing. - Retention is 60 seconds to 14 days (default 4 days); message size up to 1 MiB; batches of up to 10 messages.
- Delay queues (up to 15 min) and message timers postpone processing.
- ChangeMessageVisibility extends processing time for long tasks.
- Use message attributes for metadata and the Extended Client Library for large payloads via S3.
Detailed Notes
Producer and consumer in Python
import boto3, json
sqs = boto3.client("sqs")
url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
sqs.send_message(
QueueUrl=url,
MessageBody=json.dumps({"orderId": 42}),
MessageAttributes={"type": {"DataType": "String", "StringValue": "new"}},
)
while True:
resp = sqs.receive_message(
QueueUrl=url, MaxNumberOfMessages=10,
WaitTimeSeconds=20, VisibilityTimeout=60,
MessageAttributeNames=["All"],
)
for m in resp.get("Messages", []):
try:
handle(json.loads(m["Body"]))
sqs.delete_message(QueueUrl=url, ReceiptHandle=m["ReceiptHandle"])
except Exception:
pass # becomes visible again after the visibility timeout
The consumer must delete only after successful processing. If the work might outlast the timeout, extend it with change_message_visibility.
Standard vs FIFO
| Feature | Standard | FIFO |
|---|---|---|
| Ordering | Best effort | Strict within a message group |
| Delivery | At least once | Exactly-once processing |
| Throughput | Nearly unlimited | 300 msg/s per API (3,000 with batching), higher with high throughput mode |
| Deduplication | None | 5-minute window via MessageDeduplicationId or content hash |
| Name | any | must end .fifo |
In FIFO, one slow message in a group blocks later messages in that group, so choose group IDs (for example customer ID) to balance order and parallelism.
Dead-letter queue
aws sqs create-queue --queue-name orders-dlq
aws sqs create-queue --queue-name orders --attributes '{
"VisibilityTimeout":"60",
"ReceiveMessageWaitTimeSeconds":"20",
"RedrivePolicy":"{\"deadLetterTargetArn\":\"arn:aws:sqs:eu-west-1:111122223333:orders-dlq\",\"maxReceiveCount\":\"5\"}"
}'
A FIFO queue requires a FIFO DLQ, standard requires standard. Set DLQ retention longer than the source queue, because retention is measured from the original enqueue time.
Choosing timeouts
| Setting | Guideline |
|---|---|
| Visibility timeout | Greater than worst-case processing time (Lambda: >= 6x function timeout) |
| Long polling | 20 seconds |
| Retention | Long enough for outages and DLQ analysis |
| maxReceiveCount | 3-5 to avoid endless retries |
Short vs long polling
Short polling samples a subset of servers and can return empty responses; long polling queries all servers and waits. Long polling saves cost and reduces latency of message arrival.
Idempotent processing
At-least-once delivery means duplicates happen. Use idempotency keys (for example the order ID in a conditional DynamoDB write) so replays are harmless.
Security
- IAM policies and queue resource policies (needed for SNS, S3, cross-account senders).
- SSE-SQS by default, or SSE-KMS; if the sender is a service using a KMS key, the key policy must allow it.
- VPC endpoints keep traffic off the internet.
Scaling consumers
Scale EC2 or ECS workers on backlog per instance (ApproximateNumberOfMessagesVisible / running tasks). Lambda scales automatically with up to 1,250 more concurrent invocations per minute for standard queues, bounded by maximum concurrency if set.
Large messages
SQS Extended Client Library: body stored in S3, pointer message sent through SQS (up to 2 GB).
Queue settings that matter
| Setting | Default / range | Guidance |
|---|---|---|
| Visibility timeout | 30 s (0 s to 12 h) | At least 6x the consumer timeout; extend with ChangeMessageVisibility for slow jobs |
| Message retention | 4 days (1 minute to 14 days) | Keep DLQ retention longer than the source queue |
| Delivery delay | 0 to 15 minutes | Delay processing of every message |
| Long polling | WaitTimeSeconds up to 20 | Cuts empty receives and cost |
| Maximum message size | 1 MiB | Larger payloads use S3 pointers |
| maxReceiveCount (redrive policy) | Your choice | Moves poison messages to a DLQ |
import boto3
sqs = boto3.client("sqs")
while True:
resp = sqs.receive_message(QueueUrl=URL, MaxNumberOfMessages=10, WaitTimeSeconds=20,
MessageAttributeNames=["All"])
for m in resp.get("Messages", []):
try:
process(m["Body"])
sqs.delete_message(QueueUrl=URL, ReceiptHandle=m["ReceiptHandle"])
except Exception:
pass # becomes visible again after the visibility timeout
FIFO specifics
FIFO queues (names end in .fifo) guarantee order per MessageGroupId and exactly-once processing through deduplication (the content hash or MessageDeduplicationId) within a five-minute window. Throughput is 300 messages per second per API action (3,000 with batching), and higher in high-throughput mode. Use many message groups so consumers can work in parallel, because a group is processed by one consumer at a time. An SNS FIFO topic can feed SQS FIFO queues to keep ordering across fanout.
Redrive and monitoring
Use a DLQ redrive (console or start-message-move-task) to move messages back after fixing a bug. Alarm on ApproximateNumberOfMessagesVisible and ApproximateAgeOfOldestMessage, and scale consumers on queue depth per instance.
Real World Example
A logistics firm receives shipment updates from thousands of scanners. The API writes each update to an SQS standard queue and responds immediately. A pool of ECS tasks consumes with long polling and deletes messages after writing to the database. Messages that fail five times go to a DLQ; an alarm on ApproximateNumberOfMessagesVisible for the DLQ alerts the team. A bad deployment that broke parsing pushed only a few thousand messages to the DLQ, which were redriven after the fix with no data loss.
Architecture Diagram
Messages are durable until deleted; failures drain to a DLQ.
- 1The producer sends a message to the queue.
- 2A consumer receives it; it becomes invisible for the visibility timeout.
- 3On success the consumer deletes it using the receipt handle.
- 4On repeated failure the message moves to the DLQ.
Best Practices
- ✓Use long polling and batch send/receive/delete.
- ✓Set visibility timeout above processing time and extend when needed.
- ✓Configure a DLQ and alarm on its depth.
- ✓Design consumers to be idempotent.
- ✓Scale workers on queue backlog per worker.
Common Interview Questions
Exam Tips
DVA-C02 focus
- Duplicate processing with a long task -> increase visibility timeout.
- Decouple tiers and absorb spikes -> SQS; scale on queue depth.
- Ordering + dedup -> FIFO with MessageGroupId.
- Cutting empty responses and cost -> long polling.
Finished this lesson?
0 of 46 lessons done · 0% of the course

