S3 event notifications to SQS

How an S3 ObjectCreated event can put a message on SQS. Covers the queue access policy, decoding object keys, and writing processed files to a different bucket.

This post is about Amazon S3 event notifications to SQS. An event notification is a message S3 sends when something happens to an object, such as a new upload. SQS (Simple Queue Service) is a queue that stores those messages until a worker reads them.

Sunday Pantry is a small recipe website. Cover photos now go straight from the browser into S3 with a presigned URL. The API never saw the file, so it cannot call SendMessage the way the Fastify pipeline did.

S3 event notifications fill that gap. When an object is created, S3 publishes a message to a destination you choose: SQS, SNS, Lambda, or EventBridge. SNS (Simple Notification Service) fans one event out to many subscribers. Lambda is AWS’s run-your-function-for-you compute. EventBridge is a bus for routing events with rules. Sunday Pantry uses SQS so the same queue ideas from earlier posts still apply.

After this guide you will know s3:ObjectCreated:*, the queue policy that allows only your bucket to send, how to decode object keys, and why the processed file must land in a different bucket.

What S3 event notifications are

You attach a notification configuration to the bucket. That configuration says which events to watch and where to send them.

For uploads, the event type is object created. s3:ObjectCreated:* covers PUT, POST, and multipart complete. A presigned PUT fires that path. Multipart complete is the last step of a large upload that S3 splits into parts.

Delivery is at least once. S3 may send the same event more than one time. The docs say it is usually seconds and can take a minute or longer. Design the worker for duplicates, same as SQS.

FIFO SQS queues are not a valid S3 notification destination. FIFO means first-in, first-out, with stricter ordering. Use a standard queue, or EventBridge if you need FIFO downstream.

If the notification target writes a new object to the same bucket that you subscribed to, you can loop: create, notify, write, create. AWS warns about this. Processed covers go to a second bucket.

A small example

S3 is a service principal (s3.amazonaws.com). A service principal is an AWS identity for a service, not for a human user. The queue must grant sqs:SendMessage to that principal, limited to your originals bucket. Without this policy, notifications fail silently from the app’s point of view. The worker sits idle. You may think nothing was uploaded.

JSON code snippet
JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowPantryOriginalsToNotify",
      "Effect": "Allow",
      "Principal": {
        "Service": "s3.amazonaws.com"
      },
      "Action": "sqs:SendMessage",
      "Resource": "arn:aws:sqs:us-east-1:123456789012:pantry-cover-resize",
      "Condition": {
        "ArnEquals": {
          "aws:SourceArn": "arn:aws:s3:::pantry-covers-originals"
        },
        "StringEquals": {
          "aws:SourceAccount": "123456789012"
        }
      }
    }
  ]
}

This is a queue access policy, not a bucket policy. Principal.Service is S3. Action is sqs:SendMessage, which is “put a message on this queue.” Resource is the queue ARN (Amazon Resource Name). The first condition says the sender must be the originals bucket. The second condition says that bucket must belong to account 123456789012. Replace those account ids and names with yours.

Tighten Resource to your queue ARN. Tighten aws:SourceArn to the originals bucket. aws:SourceAccount binds the bucket owner. A policy that allows any bucket in the world to send is how you accept surprise messages.

The bucket notification then names the queue and the event:

JSON code snippet
JSON
{
  "QueueConfigurations": [
    {
      "QueueArn": "arn:aws:sqs:us-east-1:123456789012:pantry-cover-resize",
      "Events": ["s3:ObjectCreated:*"]
    }
  ]
}

This block lives on the bucket, not on the queue. QueueArn must match the queue you allowed in the policy. Events lists which S3 events to send. s3:ObjectCreated:* means any create, including a presigned PUT.

You can add a prefix filter (covers/ or a UUID prefix) so other keys in the same bucket do not enqueue. If the bucket only holds covers, ObjectCreated:* on the whole bucket is enough.

If the queue is encrypted with a customer-managed KMS key, that key policy must allow s3.amazonaws.com to kms:GenerateDataKey and kms:Decrypt. KMS (Key Management Service) encrypts data at rest. S3 needs those two KMS actions to write an encrypted SQS message.

How it works

When the API called SendMessage, the body was { coverId, bucket, key }. When S3 sends, the body is a JSON event document with a Records array. Each record has s3.bucket.name and s3.object.key. Your worker must parse this shape, not the old job JSON.

The key is URL-encoded. URL-encoding replaces some characters with % sequences so they are safe in a URL. Spaces can show up as +. Decode before GetObject or you will miss the object.

TypeScript code snippet
TypeScript
type S3EventRecord = {
  s3: {
    bucket: { name: string };
    object: { key: string };
  };
};

type S3EventDoc = {
  Records: S3EventRecord[];
};

const keysFromS3Notification = (body: string) => {
  const doc = JSON.parse(body) as S3EventDoc;

  return doc.Records.map((record) => {
    const bucket = record.s3.bucket.name;
    const key = decodeURIComponent(
      record.s3.object.key.replace(/\+/g, " "),
    );

    return { bucket, key };
  });
};

The types describe the fields you need. Real events have more fields. JSON.parse turns the SQS message string into an object. The function maps every record to a bucket name and a decoded key. replace(/\+/g, " ") turns plus signs into spaces first. decodeURIComponent then turns %2F into / and other % sequences into the real characters.

A worker that still expects { coverId } will throw on the first notification. That throw is a classic poison message unless you parse the S3 shape. A poison message is one the worker always fails, so it never leaves the queue until a dead-letter queue takes it.

You can derive coverId from the key if you create keys as ${coverId}/${filename} in the presign post.

A trimmed notification looks like this (fields omitted). Your worker should tolerate extra keys AWS adds over time.

JSON code snippet
JSON
{
  "Records": [
    {
      "eventName": "ObjectCreated:Put",
      "s3": {
        "bucket": { "name": "pantry-covers-originals" },
        "object": {
          "key": "9f3a%2Fsunday%20soup.jpg",
          "size": 2400112
        }
      }
    }
  ]
}

The %2F is a slash. The %20 is a space. After decodeURIComponent, the key is 9f3a/sunday soup.jpg. If you GetObject with the encoded string, S3 looks for a different object and you get NoSuchKey.

Test events in the Lambda console are easy to get wrong. An SQS-wrapped body is a string of this JSON, not the JSON as the top-level event. The next post shows that wrap.

EventBridge is an alternative destination if you want rules, archive, or a FIFO queue downstream. This series stays on SQS because the worker already knows queues.

Write processed files somewhere else. The Lambda or Node worker downloads from pantry-covers-originals and uploads WebP or JPEG to pantry-covers-web. Only the originals bucket has the notification. The web bucket can be public-read for the site, or private with CloudFront. CloudFront is AWS’s CDN (content delivery network). The web bucket does not enqueue new resize jobs.

TypeScript code snippet
TypeScript
const WEB_BUCKET = "pantry-covers-web";

const webKeyFromOriginal = (originalKey: string) => {
  return `web/${originalKey}.webp`;
};

This helper builds a stable output key from the original key. The same original always maps to the same web key. If S3 delivers a duplicate event, the worker overwrites the same object instead of creating a second file.

A prefix-only split on one bucket (incoming/ vs web/) can work if the notification is filtered to incoming/. Two buckets make the loop harder to create by accident.

End to end, the path is:

  1. The API creates a presigned PUT for pantry-covers-originals.
  2. The browser PUTs the file.
  3. S3 emits ObjectCreated. After the queue policy allows it, SQS stores the event JSON.
  4. A consumer (next post: Lambda) parses Records, decodes the key, resizes, writes pantry-covers-web.
  5. Duplicate notifications rerun the same key. Overwrite the same web key.

You no longer SendMessage from Node. You also no longer have a DynamoDB row unless you write one from the worker or from a separate “upload complete” callback. Many serverless pipelines skip the table and treat S3 as the source of truth plus an idempotent output key. Idempotent here means running the job twice produces the same result.

Common mistakes

Missing queue policy. S3 cannot SendMessage. Check the queue’s access policy before adding more debug logs to the worker. Silent failure is the usual symptom: the object is in S3, the queue stays empty.

Wrong Region or ARN. The queue and bucket Regions must match the ARNs you put in the policy and the notification. A queue in us-west-2 will not receive events from a bucket notification that names a us-east-1 ARN.

Worker still parsing the old job shape. Logs will show JSON parse success and then undefined bucket. Print Object.keys of the parsed body once. You should see Records, not coverId.

Forgetting to decode the key. GetObject fails with NoSuchKey for names that contain spaces or Unicode.

Writing processed files to the watched bucket. You will recurse until the DLQ fills or the bill grows. A DLQ (dead-letter queue) is where failed messages go after too many retries. The loop is worse than a DLQ: each processed write creates another job.

FIFO queue as destination. The configuration will not work as an S3 target. Use a standard queue.

Test PUT to a different bucket. Notifications are per bucket. A leftover pantry-covers from the first series will not fire this config.

When you do not need this

If the API still receives the file (first post), you already have coverId and can SendMessage with a small job. Notifications add operational pieces: policy, encoding, at-least-once events, loop risk.

SNS is useful when several subscribers should hear about the same object. SQS is useful when one worker should take a job. Sunday Pantry wants the second.

If the client uploads to S3, notifications (or EventBridge) are the usual way to start work without a second client round-trip. You do not need the client to call “resize now” after the PUT.

If you only need to run code and you do not need a queue, S3 can notify Lambda directly. This series uses SQS so retries, visibility timeout, and a DLQ stay in one place you already know.

Further reading

Related posts

  • Two AWS designs for an image pipeline

    A comparison of a Node.js worker you run yourself and a setup with presigned uploads plus Lambda. What each design includes, and how to choose.

  • Processing SQS messages with Lambda

    How Lambda receives messages from SQS, parses the nested S3 event, resizes the image, and writes to another bucket. Also batches, timeouts, and Sharp on Amazon Linux.

  • Presigned URLs for S3 uploads

    How to generate a short-lived S3 PUT URL in Node.js so the browser uploads the file directly. Also CORS, matching signed headers, and why the URL is a secret.

← Back to blog