Sub topic 14
Reacting to changes with event notifications
S3 can tell other services when something happens to a bucket. A new object arrives, an object is deleted, or a lifecycle rule expires one, and S3 sends a message. You can use this to start a thumbnail job on each upload, queue files for processing, or alert a team when a file disappears.
This chapter assumes you know how buckets, keys and prefixes work, how bucket policies are written, and that you have used the AWS CLI or boto3. You should also have met versioning and multipart upload, because both change which events fire.
How notifications work
An event notification is a rule stored in the bucket's notification configuration. The rule says: when an event of this type happens to a key matching this filter, send a message to this destination. S3 does the sending. You do not poll the bucket.
There are two mechanisms, and you can use both on one bucket:
- Direct notifications go from S3 to one of three destinations: an SQS standard queue, an SNS standard topic, or a Lambda function.
- Amazon EventBridge receives every event from the bucket. EventBridge rules then filter and route them to many more targets.
Event types
You choose events by name. A trailing * selects a group.
| Event name | When it fires |
|---|---|
| `s3:ObjectCreated:*` | Any create: `Put`, `Post`, `Copy`, `CompleteMultipartUpload` |
| `s3:ObjectRemoved:Delete` | A permanent delete of an object or version |
| `s3:ObjectRemoved:DeleteMarkerCreated` | A delete in a versioned bucket that adds a delete marker |
| `s3:ObjectRestore:Completed` | A Glacier restore finished |
| `s3:LifecycleExpiration:*` | A lifecycle rule expired an object |
| `s3:LifecycleTransition` | A lifecycle rule moved an object to another storage class |
| `s3:Replication:*` | A replication operation failed, missed its threshold, or completed |
A multipart upload produces one ObjectCreated:CompleteMultipartUpload event when the upload is completed. The individual parts do not produce events. This is usually what you want, because the object does not exist until the upload completes.
In a versioned bucket, a plain DELETE request creates a delete marker, so you get DeleteMarkerCreated and not Delete. A consumer that listens only for ObjectRemoved:Delete will miss ordinary deletes in versioned buckets. Subscribing to ObjectRemoved:* covers both.
Configuring a direct notification
Suppose a pipeline should process every .csv file under reports/. Send those events to an SQS queue so a worker can process them at its own pace.
First, the queue must allow S3 to send to it. S3 does not use your credentials for this. The queue's access policy has to grant sqs:SendMessage to the S3 service. Scope it to your bucket and account so that no other bucket can write to your queue (the confused deputy problem):
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowS3ToSend",
"Effect": "Allow",
"Principal": { "Service": "s3.amazonaws.com" },
"Action": "sqs:SendMessage",
"Resource": "arn:aws:sqs:eu-west-1:123456789012:report-uploads",
"Condition": {
"ArnLike": { "aws:SourceArn": "arn:aws:s3:::my-example-bucket-123456789012" },
"StringEquals": { "aws:SourceAccount": "123456789012" }
}
}
]
}Then save the notification configuration as notification.json:
{
"QueueConfigurations": [
{
"Id": "new-csv-reports",
"QueueArn": "arn:aws:sqs:eu-west-1:123456789012:report-uploads",
"Events": ["s3:ObjectCreated:*"],
"Filter": {
"Key": {
"FilterRules": [
{ "Name": "prefix", "Value": "reports/" },
{ "Name": "suffix", "Value": ".csv" }
]
}
}
}
]
}Apply it:
aws s3api put-bucket-notification-configuration \
--bucket my-example-bucket-123456789012 \
--notification-configuration file://notification.jsonWhen you apply the configuration, S3 sends a test message (s3:TestEvent) to the destination. If the destination policy is wrong, the call fails with an error such as "Unable to validate the following destination configurations". Fix the policy and try again.
SNS topics need the same kind of resource policy, with sns:Publish as the action. Lambda needs a resource-based permission added with aws lambda add-permission, using principal s3.amazonaws.com and the same source ARN and account.
Handling an event in Lambda
Each notification carries a Records list. Here is a handler that reads it:
import urllib.parse
def handler(event, context):
for record in event["Records"]:
bucket = record["s3"]["bucket"]["name"]
key = urllib.parse.unquote_plus(record["s3"]["object"]["key"])
size = record["s3"]["object"].get("size")
print(f"{record['eventName']}: s3://{bucket}/{key} ({size} bytes)")Two details matter here:
- Keys are URL-encoded in the event. A key such as
reports/Q1 summary.csvarrives asreports/Q1+summary.csv. If you pass the raw value toget_object, the call fails withNoSuchKey. Always decode withunquote_plus. - Not every field is present on every event. Delete events have no
size, which is why the code uses.get.
If you send events to SQS through SNS, or to SQS with other wrapping, the S3 JSON sits inside a message body and must be parsed out of it first.
Delivery guarantees
Notifications are designed to be delivered at least once. They usually arrive within seconds, though occasionally they take a minute or longer. Design consumers around these properties:
- Duplicates happen. Make processing idempotent. For example, record the bucket, key and version ID (or ETag) of work already done, and skip repeats.
- Order is not guaranteed. Two quick writes to the same key can produce events in the wrong order. Each record has a
sequencervalue, a hexadecimal string. For the same key, compare sequencers after padding them with zeros to equal length. The larger one is the later event. Sequencers cannot be compared across different keys. - Missing events are possible, though rare. If a missed object would be costly, add a periodic reconciliation, such as a scheduled job that lists the prefix and compares it against your records.
- FIFO destinations are not supported. SQS and SNS FIFO queues and topics cannot be direct destinations. If you need strict ordering, use EventBridge and your own sequencing logic.
For Lambda, S3 invokes the function asynchronously. Lambda retries failures twice by default. Configure an on-failure destination or dead-letter queue so that events that keep failing are kept for inspection. With SQS, set a redrive policy to a dead-letter queue and a visibility timeout longer than your worker's processing time.
Using EventBridge instead
To send all events to EventBridge, turn it on for the bucket:
aws s3api put-bucket-notification-configuration \
--bucket my-example-bucket-123456789012 \
--notification-configuration '{"EventBridgeConfiguration": {}}'Events arrive on the default event bus with source set to aws.s3 and a detail-type such as Object Created or Object Deleted. Rules can match on fields in detail, including key prefix, suffix and wildcards, object size, and source IP. A single rule can fan out to up to five targets, and rules can target many services, including Step Functions, Kinesis and another account's bus. You can also archive and replay events.
The cost of this flexibility is a small charge per event published, and slightly higher latency than a direct path in typical cases. Direct notifications are free apart from the cost of the destination service.
| Question | Direct notifications | EventBridge |
|---|---|---|
| Destinations | SQS, SNS, Lambda | Many AWS services and other buses |
| Filtering | Key prefix and suffix | Key, size, event fields, and more |
| Overlapping rules | Not allowed for the same event type and prefix or suffix | Any number of rules |
| Archive and replay | No | Yes |
| Extra cost | None | Per event |
Common errors
- Replacing the whole configuration.
put-bucket-notification-configurationoverwrites everything. If you send only a new queue rule, you delete existing Lambda and SNS rules. Read the current configuration withget-bucket-notification-configuration, add your entry, and send the merged result. - Overlapping filters. Two rules for the same event type whose prefix and suffix filters can match the same key are rejected. Make filters distinct, or use one SNS topic and fan out.
- Infinite loops. A function triggered by uploads to
incoming/that writes its result back to the same prefix triggers itself again, and costs grow quickly. Write output to a different bucket or a prefix excluded by your filter. - Forgetting URL decoding. See above.
- Wrong Region. A direct destination must be in the same Region as the bucket. EventBridge can forward to other Regions afterward.
Exercise
A versioned bucket sends s3:ObjectRemoved:Delete events to a Lambda function that removes the matching row from a search index. Users report that deleted files still appear in search. What is the likely cause, and how do you fix it?
Show answer
In a versioned bucket, a normal delete only adds a delete marker, which produces s3:ObjectRemoved:DeleteMarkerCreated. The Delete event fires only on permanent deletes of a specific version. Change the rule to subscribe to s3:ObjectRemoved:* (or add DeleteMarkerCreated), and make the function idempotent so that duplicate deliveries do not cause errors.
Exercise
You send a new LambdaFunctionConfigurations entry with put-bucket-notification-configuration, and your existing SQS notification stops working. Why, and what should you have done?
Show answer
The command replaces the bucket's entire notification configuration. The SQS entry was missing from the new document, so it was removed. First run get-bucket-notification-configuration, add the Lambda entry to that output, and submit the combined document.