S3 Event Notifications and Lambda: How to Integrate Them

What S3 event notifications are and how to integrate them with Lambda: permissions, filters, at-least-once delivery, retries, encoded keys and loops.

Aug 6, 2025 - 14:03
Nov 12, 2026 - 18:08
 0  56
TOPICDevOps BasicsPractical guide
S3 Event Notifications and Lambda: How to Integrate Them

S3 event notifications are messages Amazon S3 sends when something happens to objects in a bucket, such as an upload or a delete. To integrate them with Lambda, you add a notification configuration on the bucket that names the event types, optional prefix and suffix filters, and the function ARN, and you grant S3 permission to invoke the function.

This guide focuses on getting that integration right in production: permissions, filters, delivery behaviour, retries and the mistakes that cause loops or missed events. If you are new to the pieces, read what Amazon S3 is and what AWS Lambda is first. For the architecture view of the same pattern, see building event-driven applications with Lambda and S3.

Key takeaways

  • S3 can send notifications to Amazon SNS topics, Amazon SQS queues, Lambda functions and Amazon EventBridge.
  • AWS states that S3 event notifications are designed to be delivered at least once, typically within seconds but sometimes a minute or longer. Your function must handle duplicates.
  • Notifications are not guaranteed to arrive in order. For PUT and DELETE events on the same key, the sequencer field tells you which happened later.
  • S3 invokes Lambda asynchronously. On function errors, Lambda retries twice by default, and you can capture failures with an on-failure destination or a dead-letter queue.
  • Object keys in the event are URL encoded, so red flower.jpg arrives as red+flower.jpg.
  • A function that writes back to the bucket that triggers it can invoke itself in a loop. Use a second bucket or a prefix filter.

What S3 can notify you about

The S3 user guide lists the event families it can publish: new objects created, objects removed, restore events, Reduced Redundancy Storage object loss, replication events, lifecycle expiration and transition, Intelligent-Tiering archival, object tagging, object ACL changes, object annotation events and object retention events. In a notification configuration you name specific types such as s3:ObjectCreated:Put, or a wildcard family such as s3:ObjectCreated:*, which also covers POST uploads, copies and completed multipart uploads.

Most Lambda integrations use object-created events. Typical jobs include generating thumbnails, validating and loading uploaded data files, scanning uploads, extracting metadata into a database, and kicking off downstream processing. Object-removed events are useful for keeping an index in sync with the bucket.

Choosing a destination

Sending events straight to Lambda is the simplest path, but it is not always the best one. The table summarises the options AWS documents.

DestinationWhen it fitsNotes
Lambda functionOne consumer, modest volume, simple processingS3 invokes asynchronously; configure retries and failure capture on the function
SQS queueYou want buffering, batching or control over consumer concurrencyStandard queues only; S3 does not support FIFO queues directly
SNS topicSeveral subscribers need the same eventFan out to queues, functions or other endpoints
EventBridgeContent-based routing, many targets, or FIFO queue targetsEnabled per bucket; AWS points to EventBridge for SQS FIFO delivery

A common production pattern puts an SQS queue between S3 and Lambda. The queue absorbs bursts, Lambda reads messages in batches, and failed messages move to a dead-letter queue after a set number of attempts. Our guide to integrating SQS with Lambda for task processing covers that side.

Setting up S3 to Lambda directly

Step 1: allow S3 to invoke the function

Lambda checks a resource-based policy on the function before accepting an invocation. When you add an S3 trigger in the Lambda console, the console updates this policy for you. When you configure the notification from the S3 side or through infrastructure code, you add the permission yourself. Restrict it to your bucket and account so another account's bucket with the same name pattern cannot invoke your function.

aws lambda add-permission \
  --function-name process-uploads \
  --statement-id s3-invoke-uploads \
  --action lambda:InvokeFunction \
  --principal s3.amazonaws.com \
  --source-arn arn:aws:s3:::example-uploads-bucket \
  --source-account 111122223333

Separately, if the function reads or writes S3 objects through the SDK, its execution role needs the matching S3 permissions. These are two different policies: one lets S3 call the function, the other lets the function call S3.

Step 2: add the notification configuration

The S3 API call PutBucketNotificationConfiguration sets the configuration. The AWS CLI reference is clear that it replaces the bucket's existing configuration with the one in the request. If the bucket already sends events to an SNS topic or another function, fetch the current configuration first and include those entries, or you will remove them.

{
  "LambdaFunctionConfigurations": [
    {
      "Id": "incoming-csv",
      "LambdaFunctionArn": "arn:aws:lambda:ap-south-1:111122223333:function:process-uploads",
      "Events": ["s3:ObjectCreated:*"],
      "Filter": {
        "Key": {
          "FilterRules": [
            { "Name": "prefix", "Value": "incoming/" },
            { "Name": "suffix", "Value": ".csv" }
          ]
        }
      }
    }
  ]
}
aws s3api get-bucket-notification-configuration --bucket example-uploads-bucket
aws s3api put-bucket-notification-configuration \
  --bucket example-uploads-bucket \
  --notification-configuration file://notification.json

When the request includes a Lambda destination, S3 checks that the function's policy grants it permission to invoke. If Step 1 is missing, the configuration call fails, which is a useful early warning.

Step 3: write a handler that expects real-world events

The event contains a Records array. Each record holds the bucket name, the object key, size, ETag, a version ID when versioning is on, and a sequencer. Two details from the S3 event structure documentation trip up most first versions. The key is URL encoded, so decode it before using it. And after you configure notifications, S3 sends a test message (s3:TestEvent) in a different format without the Records array, so guard against it.

import urllib.parse
import boto3

s3 = boto3.client("s3")

def handler(event, context):
    records = event.get("Records", [])
    if not records:
        # s3:TestEvent and other non-record messages
        return {"skipped": True}

    for record in records:
        bucket = record["s3"]["bucket"]["name"]
        key = urllib.parse.unquote_plus(record["s3"]["object"]["key"])
        etag = record["s3"]["object"].get("eTag")
        # Make processing idempotent: skip if this bucket/key/etag was already handled
        obj = s3.get_object(Bucket=bucket, Key=key)
        process(obj["Body"].read(), key)
    return {"processed": len(records)}

Filters and their rules

Prefix and suffix filters keep the function from running on objects it should ignore. The S3 filtering documentation sets out the rules:

  • Wildcards are not allowed in filter values.
  • Spaces in a prefix or suffix must be written as +, and other special characters must be URL encoded.
  • For the same event type, configurations cannot have overlapping prefixes, overlapping suffixes, or overlapping prefix and suffix combinations. A configuration with no filter overlaps with everything.
  • Overlapping prefixes are allowed if their suffixes do not overlap, for example images/ with .jpg to one function and images/ with .png to another.
  • Overlapping filters are allowed across different event types, such as one prefix for created events and the same prefix for removed events.

Note how suffix overlap is defined: two suffixes overlap if a string can end with both. jpg and pg overlap; .jpg and .png do not.

Delivery behaviour you must design for

At-least-once delivery

AWS says notifications are designed to be delivered at least once. Separately, the Lambda documentation on asynchronous invocation warns that a function can receive the same event more than once even without errors, because the internal queue is eventually consistent. Both point to the same requirement: processing must be idempotent. Record which bucket/key/eTag (or version ID) combinations you have processed, or design the output so repeating the work gives the same result.

Ordering

Events are not guaranteed to arrive in the order they happened. If you maintain an index or database of objects, store the sequencer value with each key. For two events on the same key, the larger sequencer is the later event. AWS notes that sequencer strings can differ in length, so left-pad the shorter one with zeros before comparing, and that sequencers cannot order events across different keys.

Retries and failures

S3 invokes Lambda asynchronously, so S3 hands the event to Lambda's internal queue and moves on. If the function returns an error, Lambda by default retries twice more, waiting one minute before the first retry and two minutes before the second. For throttling and system errors, Lambda keeps the event and retries for up to six hours by default, with increasing intervals. Events that exhaust their retries or expire are discarded unless you capture them. Configure an on-failure destination or a dead-letter queue, and reduce the retry count or maximum event age if stale events are useless to you.

Message size

The maximum size of an S3 event notification message is 64 KB. If you route through SQS, AWS recommends setting the queue's MaximumMessageSize to at least 64 KB, because SQS rejects larger notifications.

Avoiding recursive loops

Both the S3 and Lambda documentation warn about the same trap. If a function triggered by uploads to a bucket writes its output to that same bucket, the write triggers the function again. AWS recommends two fixes: write output to a different bucket, or limit the trigger to a prefix used only for incoming objects (for example, trigger on incoming/ and write to processed/). Prefer the two-bucket design where you can, since a later change to the filter can quietly reintroduce the loop.

Monitoring the integration

Watch the function's Errors, Throttles and duration metrics, and alarm on failures reaching your dead-letter queue or failure destination. Log the bucket, decoded key and sequencer for every record so you can trace a specific object. For log analysis techniques, see monitoring and debugging Lambda with CloudWatch Logs. If uploads arrive in bursts, check that the function's concurrency is enough; throttled invocations are retried but add delay.

Troubleshooting checklist

  • Configuration call fails. The function policy does not allow S3 to invoke it, or filters overlap with an existing rule for the same event type.
  • Function never runs. Check the prefix and suffix against the actual key, including case and the URL encoding of special characters. Confirm the event type matches how objects are uploaded (multipart uploads raise CompleteMultipartUpload, which ObjectCreated:* covers but ObjectCreated:Put does not).
  • An existing notification stopped working. Someone ran put-bucket-notification-configuration without including the existing entries, which replaced them.
  • NoSuchKey errors in the function. The key was used without URL decoding.
  • Duplicate output records. Processing is not idempotent.
  • Invocation counts climbing without new uploads. A recursive loop. Disable the trigger, then separate input and output locations.

Infrastructure as code tip

Because the notification configuration is a single document per bucket, manage it in one place. If two Terraform modules or two CloudFormation stacks each try to own notifications on the same bucket, they will overwrite each other. Keep one resource responsible for the bucket's full notification configuration, and make the Lambda permission a dependency of it so the permission exists before S3 validates the destination.

Where to go next

For other ways to trigger functions, see Lambda triggers and AWS service integrations. Hands-on serverless and S3 work is part of the AWS Solutions Architect Associate training and the AWS DevOps Engineer Professional training, available in our Kharadi, Pune classroom and live online across India.

Frequently asked questions

What are S3 event notifications?

They are messages Amazon S3 publishes when specified events happen in a bucket, such as object creation, deletion, restore or replication. You choose the event types and a destination: Lambda, SQS, SNS or EventBridge.

How does S3 get permission to invoke a Lambda function?

Through the function's resource-based policy. Grant lambda:InvokeFunction to the s3.amazonaws.com principal, restricted to your bucket ARN and account. The Lambda console does this automatically when you add an S3 trigger there.

Can S3 event notifications be delivered twice?

Yes. AWS designs them for at-least-once delivery, and Lambda can also deliver an asynchronous event more than once. Make your function idempotent, for example by tracking processed bucket, key and ETag combinations.

Why does my Lambda function get NoSuchKey for uploaded files?

The object key in the event is URL encoded. Decode it, for example with urllib.parse.unquote_plus in Python, before calling GetObject.

How do I stop a Lambda function from triggering itself?

Write output to a different bucket, or restrict the trigger to an input prefix and write output under a different prefix. AWS recommends one of these to avoid recursive invocation.

Should I send S3 events to Lambda or to SQS?

Direct to Lambda is simplest for modest volumes. Put SQS in between when you need buffering for bursts, batch processing, or more control over retries and concurrency.

Why did my existing S3 notifications disappear?

PutBucketNotificationConfiguration replaces the whole configuration. Read the current configuration first and include every existing entry when you add a new one.

References

Interested in learning more?Get a callback from our training advisors.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.