Sub topic 14
Reacting to changes with event notifications
This chapter assumes you can create a bucket and upload objects, and that you can read basic IAM and JSON policies. Event notifications let S3 tell another service when something happens to an object. You can start work when a file arrives instead of polling the bucket for new keys.
How notifications work
You attach a notification configuration to a bucket. It lists the events you care about, an optional key filter, and a destination. When a matching event occurs, S3 sends a JSON message to the destination.
Common event types:
s3:ObjectCreated:*covers PUT, POST, copy and completed multipart uploads.s3:ObjectRemoved:*covers deletes and delete markers.s3:ObjectRestore:*ands3:LifecycleExpiration:*report restores and lifecycle actions.
S3 can deliver to four destinations: an AWS Lambda function, an Amazon SQS queue, an Amazon SNS topic, or Amazon EventBridge.
Configuring a queue destination
S3 must have permission to send to the destination. For SQS, you add a queue policy that allows the S3 service principal. Limit it to your bucket and account so no other bucket can use the queue.
{
"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-events",
"Condition": {
"ArnLike": { "aws:SourceArn": "arn:aws:s3:::my-example-bucket-123456789012" },
"StringEquals": { "aws:SourceAccount": "123456789012" }
}
}
]
}Next, the notification configuration. Save it as notification.json. It sends an event only for .csv objects created under reports/.
{
"QueueConfigurations": [
{
"Id": "new-reports",
"QueueArn": "arn:aws:sqs:eu-west-1:123456789012:report-events",
"Events": ["s3:ObjectCreated:*"],
"Filter": {
"Key": {
"FilterRules": [
{ "Name": "prefix", "Value": "reports/" },
{ "Name": "suffix", "Value": ".csv" }
]
}
}
}
]
}aws s3api put-bucket-notification-configuration \
--bucket my-example-bucket-123456789012 \
--notification-configuration file://notification.jsonS3 checks the destination permissions when you apply the configuration and returns an error if it cannot send to the queue.
Reading an event
The message body contains a Records list. The Lambda handler below prints the bucket and key of each record. Object keys arrive URL-encoded, with spaces as +, so you must decode them before you call S3.
import json
from urllib.parse import unquote_plus
def handler(event, context):
for record in event["Records"]:
bucket = record["s3"]["bucket"]["name"]
key = unquote_plus(record["s3"]["object"]["key"])
print(json.dumps({"bucket": bucket, "key": key, "event": record["eventName"]}))If the destination is SQS, the S3 record is inside the Body string of each queue message. Parse that string as JSON first.
Behavior to design for
- At-least-once delivery. An event can arrive twice. Make handlers idempotent, so processing the same key again causes no harm.
- No ordering guarantee. Two quick writes to one key can produce events in either order. On a versioned bucket, compare the
sequencerfield in each record to find the later one. - Recursive loops. If a function writes its output to a location that matches its own trigger, it fires itself forever. Write output to a different prefix or bucket.
- Replacement on update.
put-bucket-notification-configurationreplaces the whole configuration. Fetch the current one first if the bucket already has notifications.
Exercise
A function that resizes images under uploads/ writes each thumbnail back to the same bucket under uploads/thumbs/. Costs rise sharply after you deploy it. What is the cause, and how do you fix it?
Show answer
The thumbnail writes match the s3:ObjectCreated:* filter for uploads/, so each thumbnail triggers the function again, which creates a loop. Fix it by writing thumbnails to a prefix outside the filter, such as thumbs/, or to another bucket. You can also narrow the filter so it excludes the output location.