Build Event-Driven Apps with AWS Lambda and S3
Build event-driven apps with AWS Lambda and S3: notification setup, Python handler, permissions, loop prevention, at-least-once delivery, limits.
You build an event-driven application with AWS Lambda and Amazon S3 by configuring an S3 bucket to publish events, such as object created or object removed, to a Lambda function. S3 invokes the function asynchronously with a JSON record that names the bucket and object key, and your code processes that object and writes the result somewhere else. This guide walks through the design, a working example, and the failure cases you must plan for.
Limits, runtimes and behaviour below were checked against the Amazon S3 and AWS Lambda documentation in November 2026.
Key takeaways
- S3 event notifications can go to Lambda, SNS, SQS (standard queues only) or Amazon EventBridge.
- S3 invokes Lambda asynchronously, and AWS designs event notifications for at-least-once delivery, so your function must be idempotent.
- Writing output back to the bucket that triggered the function can create a loop. Use a second bucket or a prefix filter.
- Lambda's recursive loop detection covers S3 and stops a chain after roughly 16 invocations, but you should not rely on it as your design.
- A single invocation can run for up to 900 seconds (15 minutes) with 128 MB to 10,240 MB of memory and up to 10,240 MB of
/tmpstorage. - For new Python functions, use a current runtime such as
python3.13orpython3.14, both on Amazon Linux 2023.
What "event-driven" means here
In an event-driven application, components react to things that happen instead of polling for changes or running on a fixed schedule. With S3 and Lambda, the event is a change in a bucket: someone uploads an invoice, a camera drops an image, or a partner delivers a CSV file. S3 publishes a notification, Lambda runs your code, and the code does one job such as resizing an image, validating a file or loading rows into a database.
The appeal is that you pay for and run compute only when work arrives, and that each step is small enough to test and deploy on its own. If you are new to the compute side, our explainer on what AWS Lambda is and how serverless architecture works covers execution environments, cold starts and pricing basics.
How S3 delivers events
You enable notifications by adding a notification configuration to a bucket. The configuration lists which event types to publish and which destinations receive them. According to the S3 user guide, S3 can publish events for new objects, object removal, restores, replication, lifecycle expiration and transition, Intelligent-Tiering archival, object tagging, ACL changes and more.
The four destination types are:
| Destination | When to choose it |
|---|---|
| Lambda function | One function processes each event directly. Simplest path. |
| SQS standard queue | You want buffering, batch processing or controlled concurrency. FIFO queues are not supported as a direct destination. |
| SNS topic | Several subscribers need the same event (fan-out). |
| Amazon EventBridge | You want content-based rules, many targets, archive and replay, or routing to an SQS FIFO queue. |
Two delivery details shape the whole design. First, AWS states that event notifications are designed to be delivered at least once. You can receive the same event twice. Second, notifications typically arrive within seconds but can sometimes take a minute or longer. Do not build anything that assumes instant or exactly-once delivery.
For a narrower walkthrough of the notification configuration itself, see our post on S3 event notifications and Lambda integration. This guide focuses on the application around it.
Typical use cases
The S3 and Lambda pairing suits work that starts when a file arrives and finishes in seconds or minutes. Image and video teams use it to create thumbnails or extract metadata as soon as media lands. Data teams use it to validate partner CSV or JSON drops, reject malformed files early, and convert accepted files into a columnar format for analytics. Security teams use it to scan uploads, check file types and quarantine anything suspicious before another system reads it. Operations teams use it to process log exports, for example parsing load balancer logs and loading summaries into a database.
All of these share three properties. The work for one object is independent of the work for other objects, so it parallelises well. The input is small enough to process within the Lambda limits. And a short delay between upload and result is acceptable. If your job needs strict ordering across many files, very large objects, or a result within milliseconds of the upload, test carefully or pick a different design, such as a streaming service or a long-running container.
It also helps to think about what does not belong in the function. Keep business rules in the function, but keep heavy orchestration, such as multi-step approval or human review, in Step Functions, where each step has its own retries and state.
A reference architecture
A common and safe layout for a file-processing pipeline uses two buckets:
- An input bucket receives uploads under an
incoming/prefix. - An S3 event notification for
s3:ObjectCreated:*, filtered on theincoming/prefix and a suffix such as.csv, invokes a Lambda function. - The function reads the object, validates and transforms it, and writes the result to a separate output bucket.
- Failed events go to an on-failure destination (an SQS queue or SNS topic) so that nothing disappears silently.
- CloudWatch metrics and logs track invocations, errors, duration and throttles.
Separate buckets remove the loop risk entirely. They also let you apply different lifecycle rules and permissions: the input bucket can expire raw files after a few days, while the output bucket keeps processed data longer.
Step-by-step build
1. Create the execution role
The function needs an execution role that allows it to write logs, read from the input bucket and write to the output bucket. Keep the permissions to those two buckets and the specific prefixes you use.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": "arn:aws:s3:::example-input-bucket/incoming/*"
},
{
"Effect": "Allow",
"Action": ["s3:PutObject"],
"Resource": "arn:aws:s3:::example-output-bucket/processed/*"
},
{
"Effect": "Allow",
"Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
"Resource": "*"
}
]
}
The AWS managed policy AWSLambdaBasicExecutionRole covers the logging statement if you prefer to attach it instead.
2. Write the function
The handler below processes every record in the event, decodes the object key, and writes a processed copy to the output bucket. S3 URL-encodes object keys in the event, so names with spaces or special characters must be decoded before you call GetObject.
import json
import os
import urllib.parse
import boto3
s3 = boto3.client("s3")
OUTPUT_BUCKET = os.environ["OUTPUT_BUCKET"]
def handler(event, context):
for record in event["Records"]:
bucket = record["s3"]["bucket"]["name"]
key = urllib.parse.unquote_plus(record["s3"]["object"]["key"])
obj = s3.get_object(Bucket=bucket, Key=key)
body = obj["Body"].read().decode("utf-8")
rows = [line for line in body.splitlines() if line.strip()]
result = {"source": key, "row_count": len(rows)}
out_key = "processed/" + key.split("/")[-1] + ".json"
s3.put_object(
Bucket=OUTPUT_BUCKET,
Key=out_key,
Body=json.dumps(result).encode("utf-8"),
ContentType="application/json",
)
return {"status": "ok"}
Notice that the output key is derived from the input key. If the same event arrives twice, the function overwrites the same output object with the same content. That is the simplest form of idempotency, and it covers the at-least-once delivery rule.
3. Create the function
zip function.zip app.py
aws lambda create-function \
--function-name csv-processor \
--runtime python3.13 \
--handler app.handler \
--role arn:aws:iam::123456789012:role/csv-processor-role \
--zip-file fileb://function.zip \
--timeout 60 \
--memory-size 512 \
--environment "Variables={OUTPUT_BUCKET=example-output-bucket}"
4. Allow S3 to invoke the function
S3 needs permission in the function's resource-based policy. Restrict it to your bucket and your account so that no other bucket can trigger the function.
aws lambda add-permission \
--function-name csv-processor \
--statement-id s3-invoke-input-bucket \
--action lambda:InvokeFunction \
--principal s3.amazonaws.com \
--source-arn arn:aws:s3:::example-input-bucket \
--source-account 123456789012
5. Add the bucket notification
aws s3api put-bucket-notification-configuration \
--bucket example-input-bucket \
--notification-configuration '{
"LambdaFunctionConfigurations": [
{
"LambdaFunctionArn": "arn:aws:lambda:ap-south-1:123456789012:function:csv-processor",
"Events": ["s3:ObjectCreated:*"],
"Filter": {
"Key": {
"FilterRules": [
{"Name": "prefix", "Value": "incoming/"},
{"Name": "suffix", "Value": ".csv"}
]
}
}
}
]
}'
Upload a test file to incoming/ and check the output bucket and the function's CloudWatch log group. If nothing happens, the usual causes are a missing add-permission statement, a filter that does not match the key, or the function failing on the first line because of a missing environment variable.
Designing for failure
Loops
Both the S3 and Lambda documentation warn about this. If a function triggered by uploads to a bucket writes back to that same bucket, it triggers itself. The fix is a second bucket or a prefix filter that excludes the output location. Lambda's recursive loop detection does cover S3: if a function is invoked about 16 times in the same chain of requests, Lambda stops the next invocation, sends the event to a dead-letter queue or on-failure destination if you configured one, and notifies you. That protection only works with supported AWS SDK versions and is a safety net, so design the loop out in the first place.
Duplicate and late events
Because delivery is at least once, every side effect must be safe to repeat. Writing to a deterministic output key, using conditional database writes, or recording processed object versions in a DynamoDB table are common approaches. If ordering matters, do not assume events arrive in upload order. Each record carries an object sequencer value, and the S3 documentation on event message structure explains how to use it when comparing events for the same key.
Errors and retries
S3 invokes Lambda asynchronously. Lambda queues the event and retries if your function returns an error. Configure the retry attempts and maximum event age to match your use case, and always add an on-failure destination so that events that exhaust their retries are captured. A small SQS queue that collects failures, with an alarm on its depth, is enough for most teams.
Limits
Check your work against the Lambda quotas before you choose this pattern for large files. The function timeout maximum is 900 seconds. Memory runs from 128 MB to 10,240 MB, and CPU scales with memory; at 1,769 MB a function has the equivalent of one vCPU. The /tmp directory can be set between 512 MB and 10,240 MB. The default concurrency quota is 1,000 per Region, shared by all functions in the account. If a bulk upload of thousands of files arrives at once, those invocations compete with everything else in the account.
| Limit | Value (Lambda quotas page) |
|---|---|
| Maximum timeout | 900 seconds |
| Memory | 128 MB to 10,240 MB |
/tmp storage | 512 MB to 10,240 MB |
| Asynchronous payload | 1 MB |
| Default concurrent executions | 1,000 per Region |
| Deployment package (.zip, direct upload) | 50 MB zipped, 250 MB unzipped |
For long-running or very large jobs, have the function start an AWS Step Functions workflow, an AWS Batch job or an ECS task instead of doing the work itself. Our post on Lambda timeout and payload limits covers these workarounds.
When to put a queue or EventBridge in the middle
Sending S3 events directly to Lambda is the simplest option, but it gives you limited control over the rate of processing. Placing an SQS queue between S3 and Lambda adds buffering, lets Lambda read messages in batches, and lets you cap concurrency on the event source mapping so that a downstream database is not overwhelmed. Our guide to integrating SQS with Lambda shows that pattern.
EventBridge is the better choice when several teams want to react to the same bucket in different ways, or when you need rules that match on object metadata. Fan-out to many consumers is also simpler through EventBridge or an SNS topic than through a long list of bucket notification entries.
Monitoring and testing
Watch four Lambda metrics in CloudWatch: Invocations, Errors, Duration and Throttles. Add RecursiveInvocationsDropped if you want to know when loop detection steps in. Log the bucket, key and request ID for every record so that you can trace a single file through the pipeline. Our post on monitoring and debugging Lambda with CloudWatch Logs covers log queries and alarms.
For testing, keep the processing logic in a plain function that takes bytes and returns bytes, and test it without AWS at all. Then add one integration test that uploads a small file to a test bucket and checks the output. Save a sample S3 event as a JSON file and invoke the handler with it locally to check parsing, including keys with spaces and Unicode characters.
Deploying with infrastructure as code
Clicking through the console is fine for learning, but production pipelines should be defined in code. AWS SAM, CloudFormation, the AWS CDK and Terraform can all declare the buckets, the function, the permission and the notification together. Declaring them together avoids a common ordering problem: the notification configuration fails if S3 cannot confirm that it is allowed to invoke the function, so the permission must exist first.
Keep the runtime version in code as well. AWS publishes deprecation dates on the Lambda runtimes page; for example, python3.13 and python3.14 show a projected deprecation date of 30 June 2029. Review that page when you plan upgrades.
Security checklist
- Block public access on both buckets unless a public bucket is a deliberate requirement.
- Restrict the function's execution role to specific buckets and prefixes.
- Restrict the resource-based permission with
--source-arnand--source-account. - Validate file size and type inside the function before you parse anything, because anyone who can write to the input bucket controls the input.
- Encrypt both buckets and keep secrets in AWS Secrets Manager or Parameter Store, never in environment variables in plain text.
Learning the AWS developer stack
S3, Lambda, IAM, SQS and CloudWatch appear together in most AWS developer and DevOps roles. Our AWS DevOps Engineer Professional training covers these services and the automation around them, with a classroom in Kharadi, Pune, and live online batches for other cities.
Frequently asked questions
Does S3 invoke Lambda synchronously or asynchronously?
Asynchronously. Lambda queues the S3 event and runs your function, retrying on errors according to the function's asynchronous invocation settings. Configure an on-failure destination to capture events that still fail.
Can the same S3 event trigger my function twice?
Yes. AWS states that S3 event notifications are designed to be delivered at least once. Make your function idempotent, for example by writing to a deterministic output key.
How do I stop a Lambda function from triggering itself through S3?
Write output to a different bucket, or filter the trigger on an input prefix that the function never writes to. Lambda's recursive loop detection stops loops after about 16 invocations, but it is a safety net.
Can S3 send events to an SQS FIFO queue?
Not directly. FIFO queues are not supported as an S3 event notification destination. Enable Amazon EventBridge on the bucket and route events to the FIFO queue from there.
What is the maximum time a Lambda function can run on an S3 event?
The maximum function timeout is 900 seconds, or 15 minutes. For longer jobs, have the function start Step Functions, AWS Batch or an ECS task.
Why does my function fail on file names with spaces?
Object keys in S3 event records are URL-encoded. Decode them, for example with urllib.parse.unquote_plus in Python, before calling GetObject.
Which Python runtime should I use for a new function?
Use a supported Amazon Linux 2023 runtime such as python3.13 or python3.14. Check the Lambda runtimes page for current deprecation dates before you choose.
References
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0