Lesson 2 of 3 Amazon SQS

Processing Messages Reliably with Visibility Timeouts and Dead-Letter Queues

This lesson explains how consumers receive, process and then delete messages, and how a few queue settings control when messages are redelivered, how much polling costs and what happens to messages that keep failing.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the lifecycle of a message from receipt to deletion.
  • Explain how the visibility timeout, receive wait time, delivery delay and retention period affect processing.
  • Explain how a dead-letter queue and maxReceiveCount isolate messages that keep failing.
  • Identify the CloudWatch metrics that show a queue is falling behind.

The message lifecycle

Each SQS message passes through a defined lifecycle from receipt to deletion. The lifecycle proceeds as follows.

  1. Receive

    A consumer receives a message. It becomes invisible to other consumers for the visibility timeout.

  2. Process and delete

    The consumer processes the message and calls DeleteMessage.

  3. Reappear if not deleted

    If the message is not deleted before the timeout expires, it becomes visible again and is processed a second time.

resp = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=20)
for msg in resp.get("Messages", []):
    process(msg["Body"])
    sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=msg["ReceiptHandle"])

The following diagram shows the states a message passes through and what happens if it is not deleted.

The life of an SQS message. A producer sends it and it waits, visible, in the queue. A consumer receives it, and it is hidden from other consumers for the visibility timeout. If the consumer deletes it in time, it is gone; if not, it becomes visible again and its receive count rises, and after maxReceiveCount receives a redrive policy moves it to a dead-letter queue.
The consumer, not SQS, ends a message's life by deleting it, so a consumer that crashes or runs past the visibility timeout leads to the message being processed again.

Queue settings

SQS does not push messages to consumers or delete them when they are read. A consumer receives messages, processes them and then deletes each one explicitly. Four queue settings control this cycle.

The visibility timeout is how long a received message stays hidden from other consumers. If the consumer deletes the message within that time, processing is complete; if it crashes or takes longer, the message becomes visible again and another consumer receives it. The timeout should therefore exceed the longest processing time, and a consumer that needs more time can extend it for one message with ChangeMessageVisibility. The receive wait time enables long polling: instead of returning immediately when the queue is empty, a receive request waits up to 20 seconds for a message to arrive, which reduces the number of empty responses and therefore cost.

The delivery delay keeps new messages hidden for up to 15 minutes after they are sent, for example to give a related database write time to complete. The retention period is how long an unprocessed message is kept before SQS deletes it. Messages that repeatedly fail are moved to a dead-letter queue once their receive count exceeds the maxReceiveCount in the queue's redrive policy. The following table summarises the settings.

SettingDefaultRangePurpose
Visibility timeout30 seconds0 seconds to 12 hoursHow long a received message stays hidden; extend one message with ChangeMessageVisibility
Receive wait time (long polling)0 secondsUp to 20 secondsWait for messages instead of returning empty, reducing cost
Delivery delay (delay queue)0 secondsUp to 15 minutesPostpone delivery of new messages
Retention period4 days1 minute to 14 daysHow long unprocessed messages are kept

Example. A Lambda consumer has a 30-second timeout, so the visibility timeout should be at least 6 × 30 = 180 seconds. Otherwise a message can reappear while a slow invocation is still working on it.

30s

Default visibility timeout

12hours

Maximum visibility timeout

20s

Maximum long-polling wait

15min

Maximum delivery delay

Dead-letter queues

A dead-letter queue (DLQ) catches messages that fail repeatedly. Once a message has been received more times than the maxReceiveCount in the redrive policy, SQS moves it to the DLQ, where it no longer blocks processing.

  • A standard queue needs a standard DLQ; a FIFO queue needs a FIFO DLQ.
  • Give the DLQ a longer retention period than the source queue, so messages do not expire before you investigate.
  • After fixing the problem, use DLQ redrive to move messages back to the source queue.

Example. Set the visibility timeout, long polling and a DLQ after five failed receives:

aws sqs set-queue-attributes --queue-url "$QUEUE_URL" --attributes '{
  "VisibilityTimeout": "180",
  "ReceiveMessageWaitTimeSeconds": "20",
  "RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:eu-west-1:111122223333:orders-dlq\",\"maxReceiveCount\":\"5\"}"
}'
Sort into groups

Which queue setting?

Exam skills 1.1.3 · 4.3.3

Match each symptom with the SQS setting that addresses it.

Log in to try this activity Interactive activities are free with an account.

Monitoring

CloudWatch metrics show whether an SQS queue is being processed correctly. The following list describes the key metrics to monitor.

  • A rising ApproximateAgeOfOldestMessage shows consumers are falling behind.
  • ApproximateNumberOfMessagesVisible on the DLQ shows messages are failing.
True or false

Queue behaviour

Exam skills 1.1.3 · 4.1.2

Check four facts about how SQS delivers and keeps messages.

Log in to try this activity Interactive activities are free with an account.
Worked example

A poison message and a growing bill

A queue's consumer keeps failing on one malformed message. It is received, fails, reappears after the visibility timeout, and fails again, thousands of times. Meanwhile, consumers polling an empty queue with short polling make millions of empty requests.

ProblemFix
The malformed message loops foreverRedrive policy: move it to a dead-letter queue after 5 receives
Nobody notices failed messagesCloudWatch alarm on the DLQ's ApproximateNumberOfMessagesVisible above 0
Empty receives drive up costLong polling: ReceiveMessageWaitTimeSeconds = 20
After fixing the bug, failed messages must be processedDLQ redrive back to the source queue

The DLQ turns an endless retry into a visible, recoverable problem, and long polling cuts empty requests dramatically while also reducing latency.

Check yourself

Processing a message takes 2 minutes, and the queue's visibility timeout is 30 seconds. What happens?

Show answer

The message becomes visible again before processing finishes and is processed a second time. The visibility timeout must exceed the processing time; for a Lambda trigger, at least six times the function timeout.

Exam Tips

Remember for the exam

  • Messages processed twice call for a longer visibility timeout or idempotent processing.
  • To reduce empty receives and API cost, enable long polling.
  • To isolate messages that keep failing, add a dead-letter queue with a maxReceiveCount.
  • To move fixed messages back for processing, use DLQ redrive.
  • Consumers falling behind show up as a rising ApproximateAgeOfOldestMessage.