Choosing Between Synchronous, Asynchronous and Event Source Mapping Invocations
This lesson explains the three ways a Lambda function is invoked and how to choose between them. The invocation model decides who retries a failed event and where that event ends up, so many exam scenarios depend on recognising it.
Learning outcomes
After completing this lesson, you will be able to:
- Identify whether an event source invokes a function synchronously, asynchronously or through an event source mapping.
- Explain which party retries a failed invocation under each model.
- Choose between an on-failure destination, a dead-letter queue and partial batch responses for capturing failed events.
- Explain why each invocation model can deliver the same event more than once.
The three invocation models
Lambda functions are invoked in one of three ways, and the invocation model determines which party retries a failed invocation and where failures are recorded. The following table compares the three models.
| Model | Used by | Who retries | Where failures go |
|---|---|---|---|
| Synchronous | API Gateway, ALB, function URLs, SDK with RequestResponse | The caller. Lambda does not retry. | The error is returned to the caller |
| Asynchronous | S3, SNS, EventBridge, SDK with Event | Lambda: 2 retries (3 attempts in total) | On-failure destination or dead-letter queue |
| Event source mapping | SQS, Kinesis, DynamoDB Streams, Amazon MSK | Lambda's poller retries the batch | SQS: the queue's redrive policy. Streams: an on-failure destination |
Use synchronous invocation when the caller needs the result straight away, asynchronous when it only needs to hand the event over, and an event source mapping for high-volume queues and streams.
Synchronous invocations
In a synchronous invocation, the caller sends the event and waits while the function runs. It then receives either the function's result or an error. Lambda does not retry a failed synchronous invocation: the error goes straight back to the caller, which decides whether to try again. AWS SDKs and the CLI retry some errors, such as throttling, automatically, but a function error is left to the application.
A synchronous caller can receive two kinds of error, and they call for different fixes. An invocation error happens before the code runs, such as throttling (429) when no concurrency is available, or a payload that is too large (413). A function error comes from the code or the runtime, such as an unhandled exception or a timeout. The caller's own timeout also matters: API Gateway stops waiting after 29 seconds by default, so a function behind it that runs longer fails from the client's point of view even if it finishes successfully.
Example. Invoke a function synchronously from the CLI and print its result. RequestResponse is the default invocation type.
aws lambda invoke --function-name orders-api \
--invocation-type RequestResponse \
--cli-binary-format raw-in-base64-out \
--payload '{"orderId": "1234"}' \
response.json && cat response.jsonAsynchronous invocations
With an asynchronous invocation, Lambda places the event on an internal queue and returns a success response to the caller immediately; the caller never learns whether the function later succeeded. A separate process reads the queue and runs the function. If the function returns an error, Lambda retries it, waiting about one minute before the first retry and about two minutes before the second. If the function is throttled, or the service has an internal error, the event goes back on the queue and Lambda keeps retrying until the maximum event age is reached. The following list describes the settings that control this behaviour.
- Retry attempts: 0 to 2 (default 2).
- Maximum event age: 60 seconds to 6 hours (default 6 hours). Older events are discarded.
- Failure handling: send events that still fail to an on-failure destination or a dead-letter queue.
Without failure handling, an event that exhausts its retries is silently discarded. Two mechanisms keep it. A dead-letter queue (DLQ) is an SQS queue or SNS topic configured on the function that receives the original event only, so the cause of the failure must be found in the logs. A destination receives an invocation record that contains the event together with the error message, the number of attempts and the function's response. Destinations can also be configured for successful invocations, which lets a function pass its result to the next step without calling another service in its own code.
The following table summarises the differences between the two mechanisms.
Prefer destinations: they capture more context and can also route successful results.
Example. Turn off retries, discard events older than an hour and send failures to an SQS queue:
aws lambda put-function-event-invoke-config \
--function-name resize-image \
--maximum-retry-attempts 0 \
--maximum-event-age-in-seconds 3600 \
--destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:eu-west-1:111122223333:resize-failures"}}'Event source mappings
An event source mapping is a poller managed by Lambda. It reads records from a queue or stream, groups them into batches and invokes your function synchronously with each batch, scaling the pollers automatically. The batch size and the batching window control how many records each invocation receives and how long Lambda waits to fill a batch. Because the function processes a whole batch at once, retry behaviour depends on how the source stores its records.
Amazon SQS
Lambda receives messages from the queue, which hides them for the queue's visibility timeout. If the function succeeds, Lambda deletes the messages. If it fails, Lambda does not delete them, and they become visible again when the visibility timeout expires, so the whole batch is retried, including messages that were processed successfully. Setting ReportBatchItemFailures lets the function return only the IDs of the failed messages. Each receive increases a message's receive count, and when it exceeds the maxReceiveCount of the queue's redrive policy, SQS moves the message to a dead-letter queue. AWS recommends a visibility timeout of at least six times the function timeout, so that a message is not delivered again while a slow or throttled invocation is still running.
Kinesis Data Streams and DynamoDB Streams
Stream records are not deleted when they are read; they remain in the shard until the retention period ends, and Lambda processes each shard in order. If a batch fails, Lambda retries the same batch, and later records in that shard wait behind it. A single bad record can therefore stop a shard until the record expires, which appears as a rising IteratorAge metric. BisectBatchOnFunctionError splits a failing batch in two to isolate the bad record, a maximum retry count and maximum record age limit how long Lambda keeps trying, and an on-failure destination records details of the batch that was skipped.
The following table summarises the retry behaviour and the settings that control it.
| Source | How retries work | Settings to know |
|---|---|---|
| SQS | Failed messages become visible again after the visibility timeout; the queue's redrive policy moves them to a DLQ | Visibility timeout at least 6 × the function timeout; ReportBatchItemFailures |
| Kinesis, DynamoDB Streams | A failing batch blocks its shard until it succeeds or the records expire | BisectBatchOnFunctionError, maximum retry attempts, maximum record age, on-failure destination |
Example. With ReportBatchItemFailures enabled, the handler returns only the IDs of messages it could not process. Lambda deletes the rest, so only the failed messages are retried.
def handler(event, context):
failures = []
for record in event["Records"]:
try:
process(record["body"])
except Exception:
failures.append({"itemIdentifier": record["messageId"]})
return {"batchItemFailures": failures}Duplicate events
In every model an event can be delivered or retried more than once, so handlers should be idempotent. See the lesson Making Functions Idempotent to Handle Duplicate Events.
Where did the failed events go?
A team has three functions that sometimes fail. Each is invoked differently, so failures are handled in three different places:
| Function and trigger | Invocation model | What happens on failure | Where to look |
|---|---|---|---|
get-order behind API Gateway | Synchronous | The error returns to the client at once; nothing is retried by Lambda | The client's response and the function's logs |
resize-image on S3 uploads | Asynchronous | Lambda retries twice, then sends the event to the on-failure destination if one is set | The SQS or SNS destination; otherwise the event is lost |
process-payments on an SQS queue | Event source mapping (polling) | The batch is retried until it succeeds or the message reaches the queue's maxReceiveCount | The queue's dead-letter queue |
The developer discovers that failed images were silently lost: the asynchronous function had no destination. Adding an on-failure destination fixes that. For the SQS consumer, they enable ReportBatchItemFailures, so one bad payment no longer forces the nine good ones in the same batch to be processed again. Because every model can deliver an event more than once, all three functions are made idempotent.
An S3 event notification invokes a function that fails on every attempt. How many times does Lambda run the function for that event, and how can the failed event be kept?
Show answer
Three times: the first attempt and two retries, because S3 invokes functions asynchronously. An on-failure destination or a dead-letter queue captures the event after the last attempt.
Exam Tips
Remember for the exam
- Lambda never retries a synchronous invocation; the caller must handle retries.
- Asynchronous invocations are retried twice by default. Lower the retry count or maximum event age if stale events should be dropped.
- Prefer on-failure destinations to dead-letter queues: they include error details and can also record successes.
- For an SQS trigger, set the queue's visibility timeout to at least six times the function timeout.
- Enable
ReportBatchItemFailuresso only the failed SQS messages in a batch are retried. - One bad record blocking a stream shard is fixed with
BisectBatchOnFunctionError, a retry limit and an on-failure destination.