Skip to content
Quest 11Advanced14 min

React to Uploads

Every new sprite needs a thumbnail for the Pokédex grid. Instead of polling the bucket, let S3 tell you: event notifications invoke a Lambda function (or send a message) the moment an object is created.

What you'll learn

  • S3 can notify Lambda, SQS (standard queues), SNS or EventBridge about object created, deleted, restored and other events.
  • Filter by key prefix and suffix — and make sure the function's own output can't trigger it again.
  • Delivery is at least once and not strictly ordered: make handlers idempotent.

Section 01

Destinations

DestinationChoose it when
LambdaOne function should react directly
SQSYou want buffering, batching and retries under your control
SNSSeveral subscribers need the same event
EventBridgeYou want rich filtering (key patterns, object size), many targets, archive and replay. Turn it on once per bucket; it receives all events

Section 02

The recursion trap

The thumbnail function writes sprites/thumbs/0252-treecko.png. If the notification fires on every ObjectCreated event in the bucket, that thumbnail triggers the function again, which writes another thumbnail… and your bill climbs.

Fix it by design: filter on a prefix and suffix that only originals match (sprites/originals/ + .png), or write outputs to a different bucket. Filters on the same event type can't overlap within one bucket.

Section 03

Reading the event

  • Events usually arrive within seconds, but occasionally more than once or out of order. Use the sequencer field to order events for the same key.
  • Writing the thumbnail to a deterministic key makes a duplicate event harmless: the second run just overwrites the same file.
Lambda handlerJavaScript
export const handler = async (event) => {
  for (const record of event.Records) {
    const bucket = record.s3.bucket.name;
    // Keys arrive URL-encoded, with spaces as "+".
    const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, " "));
    await makeThumbnail(bucket, key); // must be safe to run twice
  }
};

Practice

Your turn

A Lambda function makes a thumbnail for every new sprite and writes it to sprites/thumbs/. The notification below fires for every new object — including the thumbnails the function writes. Filter it so only original PNGs trigger the function.

Add a Filter with a prefix of sprites/originals/ and a suffix of .png.
Tab inserts two spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the code.
Simulated — no AWS calls

Check

Check your understanding

Quick Quiz · one question, as many tries as you need.

Your handler occasionally processes the same upload twice. What is the right fix?

Choose one answer.