What you'll learn
bucket.addEventNotificationsubscribes a function to events such asOBJECT_CREATED. CDK wires the invoke permission for you.- If a function writes into the same bucket it listens to, filter by prefix and suffix so its own output can't trigger it.
- Behind the scenes CDK uses a custom resource to set the bucket's notification configuration.
Section 01
Subscribe a function
An event notification has an event type, a destination and optional filters. The destination classes live in aws-s3-notifications: LambdaDestination, SqsDestination and SnsDestination.
import * as s3n from "aws-cdk-lib/aws-s3-notifications";
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
new s3n.LambdaDestination(processorFn),
{ prefix: "sprites/originals/", suffix: ".png" },
);Section 02
The infinite loop
The processor reads sprites/originals/0252-treecko.png and writes sprites/thumbs/0252-treecko.png into the same bucket. If the notification has no filter, that new object is also an OBJECT_CREATED event, which invokes the function, which writes another object. Each invocation triggers the next, one after another, and Lambda's recursive-loop detection may eventually cut it off, but you have already paid for every invocation and every object written.
Two defences, both cheap: use filters so the function only sees inputs, or write outputs to a different bucket. The starter in the exercise has the loop; the checker tests which keys your filter would match, the way S3 would.
Practice
Your turn
ProcessorFn makes a thumbnail for every new sprite and writes it back to sprites/thumbs/ in the same bucket. As written, each thumbnail triggers the function again. Trigger it only for PNG files under sprites/originals/.
OBJECT_CREATED notification with prefix: "sprites/originals/" and suffix: ".png".The simulator runs the constructs this course teaches, plus simple loops and helper methods. Other CDK code may not be recognised.
Check
Check your understanding
Quick Quiz · one question, as many tries as you need.
sprites/thumbs/ in the same bucket that triggers it. Which setup avoids a loop and still processes new PNGs?Choose one answer.