Lesson 2 of 12 AWS Lambda

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.

ModelUsed byWho retriesWhere failures go
SynchronousAPI Gateway, ALB, function URLs, SDK with RequestResponseThe caller. Lambda does not retry.The error is returned to the caller
AsynchronousS3, SNS, EventBridge, SDK with EventLambda: 2 retries (3 attempts in total)On-failure destination or dead-letter queue
Event source mappingSQS, Kinesis, DynamoDB Streams, Amazon MSKLambda's poller retries the batchSQS: 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.

The following diagram traces an event through each invocation model, from the source to the place where failures end up.

The three invocation models. Synchronous: the caller invokes the function, waits and receives the result or the error, and the caller retries. Asynchronous: the event goes on an internal queue, Lambda retries twice and then sends the event to a destination or dead-letter queue. Event source mapping: a poller reads batches from SQS, Kinesis, DynamoDB Streams or Amazon MSK, invokes the function synchronously and retries the batch.
The invocation model decides who retries: the caller for synchronous calls, Lambda for asynchronous events, and the event source mapping's poller for queues and streams.
Sort into groups

Which model does each source use?

Exam skills 1.1.2 · 1.2.4

Recognise the invocation model behind each event source, because it decides who retries a failure.

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

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.json

Asynchronous 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.

On-failure destination
TargetsSQS, SNS, Lambda, EventBridge (S3 for failures only)
Records successes tooYes (on-success destination)
ContentThe event plus the error and invocation details
Dead-letter queue
TargetsSQS, SNS
Records successes tooNo
ContentThe event only

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"}}'

The following diagram shows the retry sequence for an asynchronous event and the three possible outcomes when the last attempt fails.

Asynchronous retries. After a function error Lambda waits about one minute before the first retry and about two minutes before the second. If the third attempt fails, an on-failure destination receives the event with the error and attempt count, a dead-letter queue receives the original event only, and without either the event is discarded. Throttled events are retried until the maximum event age, six hours by default.
The waits between attempts are approximate. Throttled events are not counted as attempts; they are retried until the maximum event age.
Scenario questions

Follow a failed asynchronous event

Exam skills 1.2.3

Learn what Lambda does with an asynchronous event that keeps failing.

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

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.

SourceHow retries workSettings to know
SQSFailed messages become visible again after the visibility timeout; the queue's redrive policy moves them to a DLQVisibility timeout at least 6 × the function timeout; ReportBatchItemFailures
Kinesis, DynamoDB StreamsA failing batch blocks its shard until it succeeds or the records expireBisectBatchOnFunctionError, 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}

The following diagram contrasts how a failure is retried for a queue and for a stream.

Event source mapping retries. With SQS and ReportBatchItemFailures, the function reports only the failed message; Lambda deletes the others, the failed message becomes visible again after the visibility timeout and moves to a dead-letter queue after maxReceiveCount. In a Kinesis or DynamoDB stream, a bad record blocks its shard while later records wait; BisectBatchOnFunctionError isolates it, and an on-failure destination records the batch that is skipped when the retry or record-age limit is reached.
SQS retries individual messages once ReportBatchItemFailures is enabled, whereas a stream retries the batch in order, so one bad record holds back the rest of its shard.
Select all that apply

One failing message in an SQS batch

Exam skills 1.2.3 · 1.2.4

Learn what happens to a whole SQS batch when one message fails.

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

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.

Worked example

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 triggerInvocation modelWhat happens on failureWhere to look
get-order behind API GatewaySynchronousThe error returns to the client at once; nothing is retried by LambdaThe client's response and the function's logs
resize-image on S3 uploadsAsynchronousLambda retries twice, then sends the event to the on-failure destination if one is setThe SQS or SNS destination; otherwise the event is lost
process-payments on an SQS queueEvent source mapping (polling)The batch is retried until it succeeds or the message reaches the queue's maxReceiveCountThe 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.

Check yourself

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 ReportBatchItemFailures so 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.