Sub topic 7
Triggering functions from API Gateway, SQS and S3
This chapter covers how a Lambda function gets connected to the services that start it. It assumes you know the three invocation types (synchronous, asynchronous and poll-based), the role of an execution role, and basic SAM syntax. Each trigger below follows a different invocation path. That path decides who calls the function, who holds the permission, how failures are retried, and what the event looks like.
Event sources and who does the calling
An event source is any service or resource configured to start your function. There are two mechanisms behind them:
- Push. The source service calls the Lambda Invoke API. API Gateway does this synchronously. S3 does it asynchronously. The function needs a resource-based policy that allows the source to call it.
- Poll. Lambda itself reads from the source through an event source mapping, a Lambda-managed poller. SQS works this way. The function's execution role needs permission to read from the source, because Lambda reads on the function's behalf.
| Trigger | Invocation type | Who calls | Permission that matters | Retry behavior |
|---|---|---|---|---|
| API Gateway | Synchronous | API Gateway | Resource-based policy on the function | None from Lambda. The client sees the error and decides. |
| S3 | Asynchronous | S3 | Resource-based policy on the function | Lambda retries twice by default, then drops the event or sends it to a destination or DLQ. |
| SQS | Poll-based | Lambda poller | Execution role (SQS read actions) | The message returns to the queue after the visibility timeout. |
API Gateway
API Gateway puts an HTTP endpoint in front of a function. Two flavors matter here:
- HTTP API is cheaper and simpler. It sends the function a version 2.0 payload.
- REST API has more features, such as API keys, request validation and usage plans. With Lambda proxy integration it sends a version 1.0 payload.
With a proxy integration, API Gateway passes the whole request to the function as the event. This includes the method, path, headers, query string parameters and body. The function must return a response object with statusCode, headers and body. The body must be a string, so serialize JSON yourself. The handler from earlier in this tutorial does this:
import json
import os
import uuid
import boto3
table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])
def handler(event, context):
body = json.loads(event.get("body") or "{}")
item = {"id": str(uuid.uuid4()), "item": body.get("item", "unknown")}
table.put_item(Item=item)
return {
"statusCode": 201,
"headers": {"Content-Type": "application/json"},
"body": json.dumps(item),
}Common errors with this trigger:
- 502 Bad Gateway. The function returned something API Gateway cannot parse, such as a missing
statusCodeor abodythat is a dict instead of a string. An unhandled exception also produces a 5xx. - Base64 bodies. Binary request bodies arrive with
isBase64Encodedset totrue. Decode them before parsing. - Timeouts. API Gateway waits about 30 seconds by default. A function with a longer timeout still runs, but the client has already received a 504. For slow work, accept the request, put a message on a queue, and return 202.
- Errors you must map yourself. Lambda does not retry a synchronous call. If you want a 400 for bad input, catch the exception and return it explicitly.
The API Gateway permission to invoke the function is a resource-based policy statement. SAM creates it for you when you declare an HttpApi event.
SQS
SQS is a poll-based source. You create an event source mapping between a queue and a function, and Lambda runs pollers that read messages in batches. Your function never calls ReceiveMessage. Instead, the event contains a Records list, each with a messageId, body and attributes.
The execution role needs sqs:ReceiveMessage, sqs:DeleteMessage and sqs:GetQueueAttributes on the queue. The managed policy AWSLambdaSQSQueueExecutionRole grants these. SAM adds an equivalent for an SQS event.
Lambda deletes messages from the queue only when the invocation succeeds. If the function raises an error, the whole batch becomes visible again after the visibility timeout and is retried. This causes three common problems:
- Poison messages. One bad message makes every batch containing it fail. The good messages in the batch are reprocessed too. Report partial batch failures so only the bad messages return.
- Visibility timeout too short. If it is shorter than the function timeout, a message can reappear while the first invocation is still working on it. AWS recommends at least six times the function timeout.
- Duplicates. Standard queues deliver at least once. Make the processing idempotent, for example by using the message ID or a business key as a conditional write key.
The partial batch handler reports 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}This only works if the event source mapping has ReportBatchItemFailures in its FunctionResponseTypes. Without that setting, Lambda ignores the returned list and treats a normal return as full success. That deletes the failed messages too.
Where a message goes after repeated failure is decided on the queue. Set a redrive policy with a dead-letter queue and a maxReceiveCount. A DLQ configured on the function does not apply to SQS polling, because that setting belongs to asynchronous invocation.
S3
S3 event notifications call your function asynchronously when an object is created, deleted or restored. You choose the event types, such as s3:ObjectCreated:*, and can filter by key prefix and suffix. Lambda queues the event internally and returns a quick acknowledgment to S3. If the function fails, Lambda retries it twice by default, with a delay between attempts. Configure destinations or a DLQ to keep events that still fail.
The event describes the object but does not contain it. Read the bucket name and key from the record, then call get_object yourself. That requires s3:GetObject in the execution role. The key in the event is URL-encoded, so a space arrives as +. Decode it before use:
import urllib.parse
import boto3
s3 = boto3.client("s3")
def handler(event, context):
for record in event["Records"]:
bucket = record["s3"]["bucket"]["name"]
key = urllib.parse.unquote_plus(record["s3"]["object"]["key"])
head = s3.head_object(Bucket=bucket, Key=key)
print(f"{bucket}/{key} is {head['ContentLength']} bytes")Delivery is at least once, and ordering is not guaranteed. Two uploads of the same key in quick succession can arrive out of order or twice. Keep the handler idempotent.
For S3, the permission is a resource-based policy. It allows s3.amazonaws.com to invoke the function, and it should be restricted with SourceArn (the bucket) and SourceAccount. Without the account condition, another account that reuses your bucket name after deletion could invoke your function.
Declaring all three in SAM
SAM turns each Events entry into the right wiring: the API route, the event source mapping, the S3 notification, and the invoke permissions.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
UploadBucketName:
Type: String
Resources:
OrderWorker:
Type: AWS::Serverless::Function
Properties:
Handler: worker.handler
Runtime: python3.12
CodeUri: src/
Timeout: 10
Events:
FromQueue:
Type: SQS
Properties:
Queue: !GetAtt OrdersQueue.Arn
BatchSize: 10
FunctionResponseTypes:
- ReportBatchItemFailures
UploadHandler:
Type: AWS::Serverless::Function
Properties:
Handler: uploads.handler
Runtime: python3.12
CodeUri: src/
Policies:
- Statement:
- Effect: Allow
Action: s3:GetObject
Resource: !Sub arn:aws:s3:::${UploadBucketName}/*
Events:
NewUpload:
Type: S3
Properties:
Bucket: !Ref UploadBucket
Events: s3:ObjectCreated:*
Filter:
S3Key:
Rules:
- Name: prefix
Value: uploads/
UploadBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Ref UploadBucketName
OrdersQueue:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeout: 60
RedrivePolicy:
deadLetterTargetArn: !GetAtt OrdersDLQ.Arn
maxReceiveCount: 3
OrdersDLQ:
Type: AWS::SQS::QueueThe queue's VisibilityTimeout of 60 seconds is six times the function's 10-second timeout. After three failed receives, a message moves to OrdersDLQ.
Choosing a trigger
- Use API Gateway when a caller waits for the answer and the work fits within the gateway timeout.
- Use SQS when you want buffering, controlled retry, and protection for downstream systems. The queue absorbs bursts that would otherwise reach your database at full speed.
- Use S3 when the trigger is the arrival of data and no caller is waiting. Pair it with SQS if you need buffering. Route S3 notifications to a queue, then process from the queue.
Exercise
A function reads from an SQS queue with a batch size of 10. One message in a batch fails and the handler raises an exception. The function code is correct, but the same 9 good messages keep being processed again, and the bad message eventually vanishes with no trace. Name two changes that fix both problems.
Show answer
First, return {"batchItemFailures": [...]} containing only the failed message IDs, and enable ReportBatchItemFailures on the event source mapping, so the nine good messages are deleted and only the bad one returns to the queue. Second, add a redrive policy to the queue with a dead-letter queue and a maxReceiveCount, so the bad message is moved to the DLQ after repeated failures instead of being lost.
Exercise
A function triggered by s3:ObjectCreated:* on a bucket generates thumbnails and saves them to the same bucket. Costs climb rapidly. What is the cause, and what are two ways to fix it?
Show answer
Each thumbnail is a new object, so it triggers the function again, which creates a loop. Fix it by writing thumbnails to a different bucket, or by filtering the trigger to a prefix such as uploads/ and writing thumbnails to a different prefix such as thumbs/.