Sub topic 20
Monitoring queue depth, message age, and dead-letter queues
This chapter assumes you can create SQS queues, send and receive messages, and have configured a dead-letter queue (DLQ) with a redrive policy. You should also know the basics of CloudWatch (metrics, namespaces, dimensions, alarms) and have boto3 installed with credentials that can call CloudWatch and SQS.
What to watch and why
A queue hides problems well. Producers keep sending successfully while consumers fall behind or fail, and nothing errors on the producer side. SQS publishes metrics to CloudWatch in the AWS/SQS namespace, with one QueueName dimension per queue. Three questions cover most operational needs:
- Is work piling up? (queue depth)
- Is work waiting too long? (message age)
- Is work failing? (DLQ contents)
SQS metrics are reported at 1-minute granularity for standard and FIFO queues. A queue with no activity may report no data points at all. This matters when you build alarms, as shown below.
The core metrics
| Metric | What it counts | Typical use |
|---|---|---|
| `ApproximateNumberOfMessagesVisible` | Messages ready to be received | Queue depth, backlog alarms |
| `ApproximateNumberOfMessagesNotVisible` | Messages in flight (received, not yet deleted, within the visibility timeout) | Detect stuck or slow consumers |
| `ApproximateNumberOfMessagesDelayed` | Messages not yet available because of a delay or message timer | Explain a "missing" backlog |
| `ApproximateAgeOfOldestMessage` | Age in seconds of the oldest message that has not been deleted | Latency and SLA alarms |
| `NumberOfMessagesSent` | Messages added to the queue | Producer throughput |
| `NumberOfMessagesReceived` | Messages returned by receive calls | Consumer throughput |
| `NumberOfMessagesDeleted` | Messages deleted | Successful completions |
| `NumberOfEmptyReceives` | Receive calls that returned nothing | Polling waste |
The word "approximate" is literal. SQS is a distributed system, so these counts can lag slightly behind reality. Use them for trends and thresholds, not for exact accounting.
Depth versus age
Depth and age answer different questions, and you usually want both.
- A depth of 50,000 is harmless if consumers drain it in seconds. A burst from a batch job is normal.
- A depth of 20 can be serious if the age of the oldest message keeps climbing. That pattern often means one message keeps failing and being retried, or consumers have stopped.
For this reason, alarm on age for user-facing latency goals, and on depth for capacity planning or cost spikes.
Reading the in-flight count
ApproximateNumberOfMessagesNotVisible rising toward the in-flight limit (about 120,000 for standard queues) means consumers receive messages but do not delete them. Common causes are a visibility timeout shorter than processing time, consumers that crash after receiving, or code that forgets to call delete_message. If a queue reaches the limit, receive calls can fail with an OverLimit error.
Reading metrics with boto3
The following script fetches the last 15 minutes of depth and age for one queue. It prints the maximum of each metric per minute.
from datetime import datetime, timedelta, timezone
import boto3
cloudwatch = boto3.client("cloudwatch")
def metric_query(query_id, metric_name, queue_name):
return {
"Id": query_id,
"MetricStat": {
"Metric": {
"Namespace": "AWS/SQS",
"MetricName": metric_name,
"Dimensions": [{"Name": "QueueName", "Value": queue_name}],
},
"Period": 60,
"Stat": "Maximum",
},
}
end = datetime.now(timezone.utc)
start = end - timedelta(minutes=15)
resp = cloudwatch.get_metric_data(
MetricDataQueries=[
metric_query("depth", "ApproximateNumberOfMessagesVisible", "orders"),
metric_query("age", "ApproximateAgeOfOldestMessage", "orders"),
],
StartTime=start,
EndTime=end,
)
for result in resp["MetricDataResults"]:
print(result["Id"])
for ts, value in zip(result["Timestamps"], result["Values"]):
print(f" {ts:%H:%M} {value:.0f}")Alarming on backlog and age
An alarm turns a metric into a notification. The next script creates an alarm that fires when the oldest message in orders is older than 5 minutes for three consecutive minutes, and publishes to an SNS topic. This reuses the SNS knowledge from earlier chapters: the alarm is just another publisher.
import boto3
cloudwatch = boto3.client("cloudwatch")
sns = boto3.client("sns")
alert_topic_arn = sns.create_topic(Name="ops-alerts")["TopicArn"]
cloudwatch.put_metric_alarm(
AlarmName="orders-oldest-message-age",
Namespace="AWS/SQS",
MetricName="ApproximateAgeOfOldestMessage",
Dimensions=[{"Name": "QueueName", "Value": "orders"}],
Statistic="Maximum",
Period=60,
EvaluationPeriods=3,
DatapointsToAlarm=3,
Threshold=300,
ComparisonOperator="GreaterThanThreshold",
TreatMissingData="notBreaching",
AlarmActions=[alert_topic_arn],
)TreatMissingData="notBreaching" handles idle queues. An empty queue may publish no data, and the default behavior (missing) can leave the alarm in INSUMFFICIENT_DATA. Treating gaps as healthy avoids false alarms for queues that are legitimately quiet.
Choose thresholds from your own requirements. If a message must be handled within two minutes, an age alarm at 300 seconds is too late. Pick a threshold below your service-level target so there is time to react.
Monitoring the dead-letter queue
A DLQ is an ordinary queue, so it has the same metrics. Its most important signal is simple: any message at all means something failed maxReceiveCount times.
Alarm on ApproximateNumberOfMessagesVisible greater than 0 for the DLQ. This alarm should be sensitive, because a message in a DLQ is a failure that needs a person or a redrive.
import boto3
cloudwatch = boto3.client("cloudwatch")
cloudwatch.put_metric_alarm(
AlarmName="orders-dlq-not-empty",
Namespace="AWS/SQS",
MetricName="ApproximateNumberOfMessagesVisible",
Dimensions=[{"Name": "QueueName", "Value": "orders-dlq"}],
Statistic="Maximum",
Period=60,
EvaluationPeriods=1,
Threshold=0,
ComparisonOperator="GreaterThanThreshold",
TreatMissingData="notBreaching",
AlarmActions=["arn:aws:sns:us-east-1:123456789012:ops-alerts"],
)Replace the account ID and Region in the topic ARN with your own, or reuse the alert_topic_arn value from the previous script.
Retention trap in the DLQ
Message age in a DLQ is measured from the original enqueue time, not from the time the message moved. The DLQ's retention period therefore counts from when the message first entered the source queue. If the source queue keeps messages for 4 days and the DLQ for 4 days, a message that fails on day 3 has only about one day left in the DLQ. Set DLQ retention longer than the source queue, commonly 14 days, so people have time to investigate.
Alarm on the DLQ's age too
A DLQ with one message that nobody noticed becomes a data-loss risk when retention expires. Add an age alarm on the DLQ (for example, older than 3 days) as a second line of defense.
Putting it together
Reading the signals together
The same metrics tell different stories depending on which combine.
| Pattern | Likely cause | First action |
|---|---|---|
| Depth up, age up, in-flight low | Consumers stopped or are too few | Check consumer health and scaling |
| Depth up, age up, in-flight high | Consumers slow or timing out | Check processing time against visibility timeout |
| Depth flat, age up steadily | One message keeps failing and returning | Inspect the oldest message, check DLQ settings |
| Depth zero, DLQ depth rising | Poison messages routed to DLQ | Read DLQ messages, fix the bug, redrive |
| Depth zero, delayed count high | Delay queue or message timers in use | Expected behavior, no action |
| Many empty receives | Short polling or too many idle pollers | Enable long polling |
Scaling consumers from metrics
Depth can drive auto scaling, but raw depth is a poor target because it ignores consumer speed. A better signal is "backlog per consumer": depth divided by the number of running consumers, compared against the backlog a single consumer can clear within your latency target. Publish that as a custom metric or use target tracking on it. For Lambda consumers, the service scales pollers for you, so focus on age and DLQ alarms instead.
Common mistakes
- Alarming only on depth. A stuck message at depth 1 never trips a depth threshold. Add an age alarm.
- Ignoring missing data. Idle queues report nothing, so set
TreatMissingDatadeliberately. - No DLQ alarm. A DLQ nobody watches silently becomes a place where messages expire.
- Using exact counts. The metrics are approximate. Do not build billing or reconciliation on them.
- Wrong dimension. The
QueueNamedimension takes the name, not the URL or ARN. For FIFO queues the name includes the.fifosuffix. - Mixing up Region. Metrics live in the queue's Region. Create alarms in that same Region.
Exercise
A queue named invoices shows ApproximateNumberOfMessagesVisible of 3 for the last hour, but ApproximateAgeOfOldestMessage has climbed from 60 to 3,600 seconds. Consumers are running and the DLQ is empty. What is the most likely explanation, and which setting would you check?
Show answer
Probably one or a few messages are failing repeatedly and returning to the queue without reaching the DLQ. The age keeps rising because the oldest message is never deleted. Check the redrive policy: the DLQ may be missing or maxReceiveCount may be set very high. Also check whether the visibility timeout is long, which would make each retry slow.
Exercise
Why should the DLQ's retention period be longer than the source queue's retention period?
Show answer
A message's age is counted from its original enqueue time, even after it moves to the DLQ. If both queues have the same retention, a message that fails late in its life expires from the DLQ soon after arriving, leaving little time to investigate or redrive it.