Sub topic 6
Synchronous, asynchronous and poll-based invocation
This chapter assumes you can write a handler, set a timeout, and attach an execution role. It covers the three ways Lambda is invoked and how each one retries. Which model a trigger uses decides who sees an error and who retries.
The three invocation models
| Model | Who calls Lambda | Caller waits for result | Retry owner |
|---|---|---|---|
| Synchronous | The client or service, such as API Gateway | Yes | The caller |
| Asynchronous | The client or service, such as S3 or SNS | No, it gets an acknowledgment | Lambda |
| Poll-based | A Lambda event source mapping | No | The event source mapping |
Synchronous invocation
The caller sends the event and waits. Lambda runs the handler and returns the result or the error in the same response. Lambda does not retry. If the function fails, the caller gets the error and decides what to do.
API Gateway, Application Load Balancer, and the RequestResponse invocation type all work this way. The following code calls a function synchronously and reads its result.
import json
import boto3
client = boto3.client("lambda")
response = client.invoke(
FunctionName="orders-function",
InvocationType="RequestResponse",
Payload=json.dumps({"body": json.dumps({"item": "book"})}).encode(),
)
print(json.load(response["Payload"]))If the handler raises an exception, the response still has HTTP status 200. The FunctionError field in the response is set. Check that field, not only the status code.
Asynchronous invocation
With InvocationType="Event", Lambda places the event in an internal queue and returns status 202 right away. The caller never sees the function's output or its errors. S3, SNS, and EventBridge invoke functions this way.
Lambda retries failed asynchronous invocations. The defaults are:
- Up to 2 retries, for 3 attempts in total. You can set this from 0 to 2.
- A maximum event age of 6 hours. You can lower it to as little as 60 seconds.
- Delays between attempts that grow, starting at about one minute.
Events that fail all attempts, or expire, are dropped unless you configure a dead-letter queue or an on-failure destination. The next chapter covers those.
Because of retries, a function can receive the same event more than once. Write handlers that are idempotent, meaning that running them twice has the same effect as running them once.
Poll-based invocation
For SQS, Kinesis, DynamoDB Streams, and similar sources, the source does not call Lambda. An event source mapping is a Lambda-managed resource that polls the source and invokes your function with a batch of records. It invokes the function synchronously, but the caller is Lambda itself.
Retry behavior depends on the source:
- SQS: If the function fails, the whole batch becomes visible in the queue again after the visibility timeout. The message is retried until it succeeds or reaches the queue's
maxReceiveCount. After that it moves to the queue's dead-letter queue, if one exists. - Kinesis and DynamoDB Streams: The shard is blocked. Lambda retries the same batch until it succeeds or the records expire, so one bad record can stall the shard. You can limit retries and bisect the batch to isolate the bad record.
Choosing a model
Choose the model based on what the caller needs:
- If the caller needs the answer now, use synchronous invocation.
- If the work can happen later and the caller only needs to hand it off, use asynchronous invocation.
- If you need buffering, ordering, or batching, put a queue or stream in front and use an event source mapping.
Exercise
A function is invoked by S3 and throws an exception on every attempt. No dead-letter queue or destination is configured. How many times does Lambda run the function, and what happens to the event?
Show answer
S3 invokes asynchronously, so Lambda runs the function once and retries twice with the default settings, which is 3 attempts in total. After the last failure the event is discarded, because nothing is configured to catch it.
Exercise
A synchronous invoke call returns HTTP status 200, but the function raised an exception. How does your code detect this?
Show answer
Check the FunctionError field in the response. Lambda returns 200 for the invoke request itself, and sets FunctionError when the handler failed. The response payload then holds the error details.