Symptom
An upstream system says it sent the event. S3 shows the object, SNS shows a successful publish, EventBridge shows a matched rule, but the function never processed it. Or it processed it hours later, or twice. Nothing appears in the function's error metric because the function never ran for that event.
This is almost always behaviour of the asynchronous invocation queue that sits between the caller and your function. The caller gets 202 Accepted as soon as Lambda queues the event. Everything after that is Lambda's retry logic, not the caller's.
How the async queue behaves
| Situation | What Lambda does |
|---|---|
| Function returns an error or times out | Retries up to MaximumRetryAttempts (0-2, default 2), with a delay between attempts |
| Function is throttled (concurrency) or hits a system error | Puts the event back in the queue and retries with backoff until MaximumEventAgeInSeconds (60 s to 6 h, default 6 h) |
| Retries exhausted or event too old | Sends the event to the on-failure destination or DLQ if one exists, otherwise drops it |
| Reserved concurrency set to 0 | Events are dropped (counted in AsyncEventsDropped) |
| Normal operation | At-least-once: an event can occasionally be delivered more than once |
Two consequences catch experienced teams:
- Throttling does not fail fast. A function capped by reserved concurrency during a burst quietly builds an internal backlog and processes events minutes or hours late.
- With no destination configured, an event that runs out of retries or age leaves no trace except a metric.
Step 1: read the async metrics
Lambda publishes three async-specific metrics in the AWS/Lambda namespace:
| Metric | What it tells you |
|---|---|
AsyncEventsReceived | Events Lambda successfully queued for the function |
AsyncEventAge | Time between queueing and invocation. Rising values mean retries or throttling |
AsyncEventsDropped | Events dropped without a successful run (retries or age exhausted, concurrency 0) |
Also check Throttles, Errors, DeadLetterErrors and DestinationDeliveryFailures.
FN=orders-ingest
START=$(date -u -d '-6 hours' +%Y-%m-%dT%H:%M:%SZ)
END=$(date -u +%Y-%m-%dT%H:%M:%SZ)
for M in AsyncEventsReceived AsyncEventsDropped Throttles Errors DestinationDeliveryFailures; do
echo "== $M"
aws cloudwatch get-metric-statistics --namespace AWS/Lambda --metric-name $M \
--dimensions Name=FunctionName,Value=$FN \
--start-time $START --end-time $END --period 300 --statistics Sum \
--query "sort_by(Datapoints,&Timestamp)[?Sum>\`0\`].[Timestamp,Sum]" --output text
done
aws cloudwatch get-metric-statistics --namespace AWS/Lambda --metric-name AsyncEventAge \
--dimensions Name=FunctionName,Value=$FN \
--start-time $START --end-time $END --period 300 --statistics Maximum \
--query "sort_by(Datapoints,&Timestamp)[].[Timestamp,Maximum]" --output text
How to read the pattern:
| Pattern | Likely cause |
|---|---|
AsyncEventsReceived lower than what the source sent | The source never delivered: check S3 notification config, SNS subscription, EventBridge FailedInvocations |
AsyncEventAge climbing with Throttles > 0 | Concurrency limit (reserved concurrency or account limit) is too low for the burst |
AsyncEventAge climbing with Errors > 0 | Function failing, events cycling through retries |
AsyncEventsDropped > 0 | Events are being lost. Configure a destination before anything else |
DestinationDeliveryFailures > 0 | The destination exists but Lambda can't write to it (permissions or KMS) |
Warning
AsyncEventsDroppedgreater than zero with no on-failure destination means the data is gone from Lambda's side. You have to replay from the source (S3 inventory, EventBridge archive, upstream logs).
Step 2: check the current async configuration
aws lambda get-function-event-invoke-config --function-name $FN
aws lambda get-function-configuration --function-name $FN \
--query "{Timeout:Timeout,DLQ:DeadLetterConfig.TargetArn,Role:Role}"
aws lambda get-function-concurrency --function-name $FN
get-function-event-invoke-config returns ResourceNotFoundException when nothing was ever set, which means defaults: 2 retries, 6 hours, no destination. Config can be set per version or alias with --qualifier. If EventBridge targets the live alias, configure the alias, not $LATEST.
Step 3: set retries, age and an on-failure destination
Choose the values on purpose:
- Retries: set
0if the function isn't idempotent or the error is deterministic (bad payload). Retrying a poison event twice only adds noise. Keep2for transient downstream failures. - Maximum event age: lower it when stale events are worse than missing ones (price updates, cache invalidation). Keep it high when every event matters and you'd rather process late.
aws lambda put-function-event-invoke-config \
--function-name $FN --qualifier live \
--maximum-retry-attempts 1 \
--maximum-event-age-in-seconds 3600 \
--destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:eu-west-1:111122223333:orders-ingest-failed"}}'
Use update-function-event-invoke-config to change one field later without resetting the others.
The function's execution role writes to the destination, so it needs sqs:SendMessage (or sns:Publish, events:PutEvents, lambda:InvokeFunction). If the queue uses a customer managed KMS key, the role also needs kms:GenerateDataKey and kms:Decrypt on that key. Missing KMS permissions are the usual cause of DestinationDeliveryFailures.
Tip
Prefer an on-failure destination over a DLQ. A DLQ receives only the original payload. A destination record also contains
requestContext.condition(RetriesExhaustedorEventAgeExceeded), the approximate invoke count and the function's error response, which tells you why the event failed.
Step 4: fix the cause of the throttling or errors
If Throttles drive the age up:
# Who else is using account concurrency?
aws cloudwatch get-metric-statistics --namespace AWS/Lambda --metric-name ConcurrentExecutions \
--start-time $START --end-time $END --period 60 --statistics Maximum \
--query "max_by(Datapoints,&Maximum).Maximum"
- Raise reserved concurrency on this function if a hard cap was set too low, or set reserved concurrency so a noisy neighbour can't starve it.
- If the downstream (database, third-party API) is the real constraint, keep the cap and accept the queueing, but make sure the event age limit is longer than your worst burst drain time.
- For large bursts that need ordering, flow control or visibility into the backlog, put an SQS queue between the source and the function. You can then see
ApproximateNumberOfMessagesVisibleinstead of guessing fromAsyncEventAge.
If Errors drive it, find the failing requests:
fields @timestamp, @requestStream, @message
| filter @message like /ERROR|Task timed out|Runtime.ExitError/
| sort @timestamp desc
| limit 50
Timeouts are common when the function's timeout is shorter than a slow downstream call. A timeout counts as an error and triggers a retry, which hits the same slow dependency again.
Step 5: make the handler idempotent
Because async delivery is at-least-once and retries re-run the whole function, side effects must be safe to repeat. A conditional write keyed on a stable event ID is enough for most cases:
import boto3
from botocore.exceptions import ClientError
ddb = boto3.client("dynamodb")
def handler(event, context):
# EventBridge events carry "id"; S3 records use the object key + sequencer
if "id" in event:
event_id = event["id"]
else:
obj = event["Records"][0]["s3"]["object"]
event_id = f'{obj["key"]}:{obj["sequencer"]}'
try:
ddb.put_item(
TableName="processed-events",
Item={"pk": {"S": event_id}},
ConditionExpression="attribute_not_exists(pk)",
)
except ClientError as e:
if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
return {"status": "duplicate"}
raise
process(event)
Add a TTL attribute to the table so the dedupe records expire.
Step 6: redrive failed events
On-failure records in SQS wrap the original event in requestPayload. Fix the bug first, then replay:
import boto3, json
sqs = boto3.client("sqs")
lam = boto3.client("lambda")
QUEUE = "https://sqs.eu-west-1.amazonaws.com/111122223333/orders-ingest-failed"
while True:
resp = sqs.receive_message(QueueUrl=QUEUE, MaxNumberOfMessages=10, WaitTimeSeconds=2)
msgs = resp.get("Messages", [])
if not msgs:
break
for m in msgs:
record = json.loads(m["Body"])
print(record["requestContext"]["condition"], record["requestContext"]["requestId"])
lam.invoke(FunctionName="orders-ingest:live", InvocationType="Event",
Payload=json.dumps(record["requestPayload"]).encode())
sqs.delete_message(QueueUrl=QUEUE, ReceiptHandle=m["ReceiptHandle"])
Caution
Replay in small batches and watch
ErrorsandThrottles. Redriving thousands of events into a function that still fails, or that shares concurrency with production traffic, can cause a second incident.
Other places events disappear
| Cause | Check |
|---|---|
| Recursive loop detection stopped a function that writes back to its own trigger (SQS, SNS, S3) | Look for a recursive-loop notice in AWS Health and the function's configuration; fix the loop rather than turning detection off |
| Payload larger than the async payload limit | Caller gets an error at invoke time; check current Lambda quotas |
| Resource policy missing for the source | S3/SNS/EventBridge can't invoke; check aws lambda get-policy |
Config set on $LATEST but source targets an alias | Re-run Step 2 with --qualifier |
Prevent it next time
- Configure an on-failure destination on every async function, with KMS permissions tested.
- Alarm on
AsyncEventsDropped> 0 and onAsyncEventAgep99 above your freshness target. - Set
MaximumRetryAttemptsandMaximumEventAgeInSecondsexplicitly in IaC so nobody relies on defaults. - Keep handlers idempotent and keep the redrive script in the runbook repository.
- Put SQS in front of functions that need back-pressure you can see and control.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get