Sub topic 7
Triggering functions from API Gateway, SQS and S3
This chapter assumes you can write a handler, know the three invocation types (synchronous, asynchronous, poll-based), and understand execution roles. Here you connect a function to three common triggers and see how each one shapes the event your code receives.
How a trigger reaches your function
An event source is the AWS service that causes a function to run. The service decides the invocation type, the event format, and who retries on failure.
| Trigger | Invocation type | Who calls the function | Event contents |
|---|---|---|---|
| API Gateway | Synchronous | API Gateway | One HTTP request |
| S3 | Asynchronous | S3 | One or more object notifications |
| SQS | Poll-based | Lambda's event source mapping | A batch of messages |
API Gateway
API Gateway receives an HTTP request and invokes your function, then waits for the result. Your return value becomes the HTTP response. With the proxy integration used by HTTP APIs, the event contains the headers, path, query string, and body. The body is always a string, so parse it yourself, as the handler from the earlier chapter does with json.loads.
Return an object with statusCode, headers, and a string body. If the function raises an error or returns a malformed response, the client gets a 5xx error. API Gateway does not retry, so the client decides whether to try again.
SQS
SQS is different because your function is not called by the queue. An event source mapping is a Lambda-managed resource that polls the queue, collects messages into a batch, and invokes your function with event["Records"]. Each record has a messageId and a string body.
If the function returns without error, Lambda deletes the whole batch. If it raises an error, every message in the batch becomes visible again after the visibility timeout and is retried. Two settings matter here:
- Set the queue's visibility timeout to at least six times the function timeout. If it is shorter, a message can become visible again while the function is still processing it, and it gets processed twice.
- Enable
ReportBatchItemFailuresand returnbatchItemFailures, as in the handler from the spine. Then only the failed messages are retried and the rest are deleted.
SQS delivers at least once, so make your processing idempotent.
S3
S3 sends an event asynchronously when something happens to an object, such as s3:ObjectCreated:*. Lambda queues the event and retries on error, which the error-handling chapter covers. Each record holds s3.bucket.name and s3.object.key. The key is URL-encoded, so a space arrives as +. Decode it with urllib.parse.unquote_plus before calling get_object.
Never write a function that is triggered by uploads to a bucket and writes back to the same bucket without a prefix or suffix filter. It will trigger itself in a loop.
Wiring all three in SAM
This template attaches an SQS trigger and an S3 trigger to one function. SAM generates the event source mapping and the permission that lets S3 invoke the function.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
UploadsBucket:
Type: AWS::S3::Bucket
JobsQueue:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeout: 60
WorkerFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
CodeUri: src/
Timeout: 10
Events:
Jobs:
Type: SQS
Properties:
Queue: !GetAtt JobsQueue.Arn
BatchSize: 10
FunctionResponseTypes:
- ReportBatchItemFailures
Upload:
Type: S3
Properties:
Bucket: !Ref UploadsBucket
Events: s3:ObjectCreated:*
Filter:
S3Key:
Rules:
- Name: prefix
Value: incoming/The timeout is 10 seconds, so a visibility timeout of 60 meets the six-times rule.
Common mistakes
- Treating an API Gateway
bodyas a parsed object instead of a string. - Letting one bad SQS message fail the entire batch because partial batch responses are not enabled.
- Forgetting to URL-decode S3 object keys.
- Assuming the execution role lets the function read the S3 object. The trigger permission lets S3 call the function, but reading the object needs
s3:GetObjectin the role.
Exercise
A function reads from an SQS queue with a 30-second visibility timeout and a 20-second function timeout. Some messages are processed twice even though nothing fails. What is the likely cause, and what is the fix?
Show answer
The visibility timeout is shorter than six times the function timeout. A message can become visible again while the first invocation is still running or being retried, so another poller picks it up. Raise the queue's visibility timeout to at least 120 seconds (six times 20), and make the processing idempotent because SQS delivers at least once.