Sub topic 6
Synchronous, asynchronous and poll-based invocation
This chapter assumes you can write a handler, set memory and timeout, and attach an execution role. It covers the three ways Lambda runs a function, because the way a function is invoked decides who sees errors, how retries work, and where to put your handling logic.
Why the invocation type matters
Every Lambda run starts with an invocation. Lambda has three invocation models:
- Synchronous: the caller waits for the function to finish and receives its result or error.
- Asynchronous: the caller hands over an event and gets an acknowledgment. Lambda runs the function later.
- Poll-based: Lambda itself reads from a queue or stream and invokes your function with batches of records.
The same handler code behaves differently under each model. A raised exception means "return a 502 to the client" in one model, "retry twice and then drop the event" in another, and "retry the whole batch" in the third.
Synchronous invocation
In a synchronous invocation the client opens a connection, sends the event, and blocks until the function returns. The response body is the function's return value. If the function fails, the error comes back to the caller.
Services that invoke synchronously include API Gateway, Application Load Balancer, Lambda function URLs and CloudFront (Lambda@Edge). You can also do it yourself with the SDK. The InvocationType of RequestResponse is the default.
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"]))Note the two layers of failure here:
- If Lambda cannot run the function at all (throttling, permissions, a payload that is too large), the API call itself fails with an error such as
TooManyRequestsException. - If the function runs and raises an exception, the API call succeeds with HTTP status 200. The response includes a
FunctionErrorfield, and the payload holds the error details. Code that only checks the status code will miss the failure.
Lambda does not retry synchronous invocations. The caller owns retry logic. The AWS SDKs retry throttling and service errors automatically, but they do not retry an exception thrown by your handler. The request payload limit is 6 MB, and the response limit is also 6 MB. Make sure your function timeout is shorter than the timeout of whatever sits in front of it. For example, API Gateway has its own integration timeout, and a Lambda that keeps running after the client has given up still costs money.
Asynchronous invocation
With asynchronous invocation, Lambda places the event on an internal queue and returns HTTP 202 right away. The caller never sees the function's result. S3, SNS, EventBridge and CloudWatch Logs subscriptions invoke this way. With the SDK, set InvocationType="Event".
import json
import boto3
client = boto3.client("lambda")
response = client.invoke(
FunctionName="orders-function",
InvocationType="Event",
Payload=json.dumps({"item": "book"}).encode(),
)
print(response["StatusCode"]) # 202: accepted, not processedThe 202 only means Lambda accepted the event. It says nothing about whether the function succeeded. The payload limit for asynchronous events is 1 MB (older documentation says 256 KB, so check the current quota for your Region).
Retry behavior
If the function returns an error or is throttled, Lambda retries on its own:
- By default it retries twice, so a failing event runs up to three times in total. You can set
MaximumRetryAttemptsfrom 0 to 2. - Lambda waits about a minute before the first retry and about two minutes before the second.
- Events can stay in the internal queue for up to six hours (
MaximumEventAgeInSeconds, configurable from 60 seconds to 6 hours). If throttling or a lack of concurrency delays the event past that age, Lambda discards it. - Lambda may deliver an event more than once even when the function succeeds. Handlers must be idempotent, meaning a repeated event produces the same end state.
Where failed events go
Once retries are exhausted or the event ages out, Lambda drops the event unless you configure a destination:
- A dead-letter queue (an SQS queue or SNS topic) receives the failed event payload.
- An on-failure destination receives the event plus metadata about the failure. It can be SQS, SNS, EventBridge or another Lambda function.
- An on-success destination receives the result of successful runs, which is useful for chaining.
Destinations carry more context than a DLQ and are the recommended choice for new work. The next chapter covers them in detail. You configure them like this:
aws lambda put-function-event-invoke-config \
--function-name orders-function \
--maximum-retry-attempts 1 \
--maximum-event-age-in-seconds 3600 \
--destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:us-east-1:123456789012:orders-failures"}}'The execution role needs permission to send to the destination (for example sqs:SendMessage), or the failed events are lost.
Poll-based invocation
Some sources cannot push events to Lambda. SQS queues, Kinesis and DynamoDB streams, Kafka topics and Amazon MQ brokers hold records until a consumer reads them. For these, Lambda runs an event source mapping, a resource that polls the source and invokes your function with a batch.
The invocation of your function from the mapping is synchronous. The mapping waits for your function and uses the result to decide what to do next. This is the key point: the retry rules come from the source type, not from the asynchronous rules above.
| Aspect | Synchronous | Asynchronous | Poll-based |
|---|---|---|---|
| Who calls the function | The client | The client, via Lambda's internal queue | Lambda's event source mapping |
| Caller sees the result | Yes | No, only a 202 | No, the mapping consumes it |
| Automatic retries | None from Lambda | Up to 2, configurable | Depends on source |
| Failure handling | Caller decides | DLQ or destination | Source redelivery, DLQ on the queue, on-failure destination for streams |
| Typical sources | API Gateway, function URL | S3, SNS, EventBridge | SQS, Kinesis, DynamoDB Streams, Kafka |
| Input | One event | One event | A batch of records |
SQS
For SQS, Lambda polls the queue and passes up to BatchSize messages (up to 10 for standard queues by default, up to 10,000 when you set a MaximumBatchingWindowInSeconds). If the function succeeds, Lambda deletes the whole batch. If the function raises an exception, none of the messages are deleted. They become visible again after the queue's visibility timeout and are retried until the queue's maxReceiveCount sends them to its dead-letter queue.
Because one bad message fails the whole batch, the good ones get reprocessed too. Enable ReportBatchItemFailures on the mapping and return only the failed IDs:
import json
def process(message):
if "order_id" not in message:
raise ValueError("missing order_id")
def handler(event, context):
failures = []
for record in event["Records"]:
try:
process(json.loads(record["body"]))
except Exception:
failures.append({"itemIdentifier": record["messageId"]})
return {"batchItemFailures": failures}Lambda deletes the successful messages and leaves the listed ones in the queue. An empty list means the entire batch succeeded. If you return the wrong key or forget to enable the setting, Lambda treats the invocation as a full success or full failure, so check both sides.
Set the queue's visibility timeout to at least six times your function timeout. This gives a throttled or retried batch room before messages reappear.
Kinesis and DynamoDB Streams
Streams are ordered per shard. If a batch fails, Lambda retries the same batch until it succeeds or the records expire, and it does not move on to later records in that shard. One poison record can block a shard. This is why stream mappings offer extra controls:
MaximumRetryAttemptsandMaximumRecordAgeInSecondslimit how long Lambda keeps trying.BisectBatchOnFunctionErrorsplits a failing batch in half to isolate the bad record.- An on-failure destination receives metadata about the skipped records (not the records themselves) so you can fetch them from the stream.
ParallelizationFactorruns up to 10 concurrent batches per shard while keeping order per partition key.
Choosing a model
You usually do not choose freely, because the trigger fixes the model. When you do have a choice, such as one function calling another, apply these rules:
- Use synchronous invocation when the caller needs the answer to continue, and keep the chain short. Each synchronous hop adds latency, and the caller pays for time spent waiting.
- Use asynchronous invocation for fire-and-forget work where retries and a failure destination are enough.
- Put an SQS queue in front of the function when you need to control throughput, absorb bursts, or keep failed messages for inspection.
Do not chain synchronous Lambda calls to wait for another Lambda. You pay for both functions while one idles. Prefer a queue, Step Functions, or a single function.
Common errors
- Treating a 202 as success. An async
invokecall tells you nothing about the outcome. Watch the destination or DLQ and theAsyncEventsDroppedmetric. - Ignoring
FunctionError. Synchronous SDK calls return 200 even when the handler raised. - Non-idempotent handlers. Retries and at-least-once delivery cause duplicates. Store an idempotency key, or use conditional writes.
- Visibility timeout shorter than function timeout. SQS makes a message visible again while the first function is still working on it, creating duplicates.
- A poison message with no limit. Without
maxReceiveCounton the queue or retry limits on a stream mapping, one bad record can loop or block forever. - Missing permissions. The mapping needs
sqs:ReceiveMessage,sqs:DeleteMessageandsqs:GetQueueAttributeson the queue. TheAWSLambdaSQSQueueExecutionRolemanaged policy covers these.
Exercise
A function is triggered by an SQS queue with a batch size of 10. One message in a batch of 10 is malformed and makes the handler raise an exception. ReportBatchItemFailures is not enabled. What happens to the other nine messages, and what change fixes it?
Show answer
The invocation fails, so Lambda deletes none of the ten messages. All ten become visible again after the visibility timeout and are processed again, which re-runs the nine good ones. Enable ReportBatchItemFailures on the event source mapping and have the handler catch the error per record and return {"batchItemFailures": [{"itemIdentifier": messageId}]} for the bad message only. Also set maxReceiveCount and a dead-letter queue on the source queue so the bad message eventually stops retrying.
Exercise
You call a function with InvocationType "Event" and receive StatusCode 202. The handler then raises an exception on every attempt. How many times does Lambda run it by default, and where can you find the failed event afterward?
Show answer
Lambda runs it three times in total: the first attempt plus two retries, with waits of roughly one and two minutes. After that the event is discarded unless you configured a dead-letter queue or an on-failure destination, which is where you find the failed event. The 202 only confirmed that Lambda accepted the event.