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.
This post is about processing Amazon SQS messages with AWS Lambda. SQS is a queue. It holds a job until something is ready to work on it. Lambda is a service that runs your function when that work arrives. You do not keep a Node.js process running all day to poll the queue.
Sunday Pantry is a small recipe website that stores cover photos. A cook uploads a photo to an originals bucket in Amazon S3. S3 puts a notification on the queue. This post is the function that reads that notification, resizes the photo, and writes an 800 px WebP file to a second bucket.
Earlier in the series, an app-owned worker was a while (true) loop that called ReceiveMessage. You ran that process yourself. If the machine stopped, the worker stopped until you started it again.
Lambda can be that consumer. You attach the function to the SQS queue. That attachment is called an event source mapping. Lambda polls, invokes your handler with a batch of messages, and deletes the batch if the invocation succeeds.
After this guide you will know the SQSEvent shape, why an S3 notification is nested in body, and how this replaces the long-poll loop. You will not need a full SAM or CDK tutorial to follow the code.
What Lambda does with SQS
An event source mapping is a poller AWS runs for you. It receives from SQS. The receive step uses the same long-poll idea as the Node.js worker. The mapping waits for messages instead of asking in a tight empty loop.
When the mapping has work, it calls your function synchronously. Synchronous here means Lambda waits for your handler to finish. Then it decides whether to delete the messages.
The default batch size is up to 10 messages. You can wait for a batch window so small queues do not invoke with one record every time.
If the handler returns without throwing, Lambda deletes those messages. You do not call DeleteMessage yourself on that path.
If the handler throws, the whole batch stays in the queue. The messages stay hidden until the visibility timeout. Visibility timeout is the period SQS keeps a message invisible after a receive, so two consumers do not grab it at once. When that period ends, the messages show up again and retry.
After enough receives, they go to the dead-letter queue (DLQ) you already know from earlier in the series.
The function and the queue must be in the same Region.
Delivery is still at least once. Duplicate invokes happen. The handler should be safe to run twice on the same cover key. Overwriting the same web file is a normal way to make a second run harmless.
This post stays at that mental model. Provisioned pollers, maximum concurrency, and exact scaling numbers live in the Lambda developer guide.
A small example
Lambda does not pass a parsed S3 event as the top-level object when SQS is the source. It passes SQS records. Each record has a body string. For S3 notifications, that string is the event document from the previous post.
import type { SQSEvent, SQSRecord } from "aws-lambda";
import {
GetObjectCommand,
PutObjectCommand,
S3Client,
} from "@aws-sdk/client-s3";
import sharp from "sharp";
const s3 = new S3Client({
region: process.env.AWS_REGION ?? "us-east-1",
});
const WEB_BUCKET = process.env.WEB_BUCKET ?? "pantry-covers-web";
export const handler = async (event: SQSEvent) => {
for (const record of event.Records) {
await processSqsRecord(record);
}
};
const processSqsRecord = async (record: SQSRecord) => {
const doc = JSON.parse(record.body) as {
Records: Array<{
s3: { bucket: { name: string }; object: { key: string } };
}>;
};
for (const s3Record of doc.Records) {
const bucket = s3Record.s3.bucket.name;
const key = decodeURIComponent(
s3Record.s3.object.key.replace(/\+/g, " "),
);
await writeWebCover(bucket, key);
}
};Here is what that code does, in order.
The imports pull in Lambda types, the S3 client, and Sharp. Sharp is the library that resizes the photo.
s3 is a client for the Region in AWS_REGION, or us-east-1 if that variable is missing.
WEB_BUCKET is the second bucket. Processed covers go there, not back into the originals bucket. Two buckets avoid a loop where a write causes another notification.
handler is the function Lambda calls. The event type is SQSEvent. That type has a Records array. Each item is one SQS message.
The outer for loop walks the SQS batch. For each message it calls processSqsRecord.
processSqsRecord parses record.body. That string is JSON. After JSON.parse, you get an object with its own Records array. Those inner records are S3 event records, not SQS records.
The inner loop reads the bucket name and the object key. The key is URL-encoded. Spaces can show up as +. decodeURIComponent after replacing + with a space gives you the real S3 key.
Then it calls writeWebCover.
Two loops: SQS batch, then S3 records inside each body. A test message you typed in the console will not have Records[0].s3. Guard or send it to the DLQ.
Resize and write to the other bucket:
const writeWebCover = async (bucket: string, key: string) => {
const object = await s3.send(
new GetObjectCommand({ Bucket: bucket, Key: key }),
);
if (!object.Body) {
throw new Error(`Empty object s3://${bucket}/${key}`);
}
const input = await object.Body.transformToByteArray();
const output = await sharp(input)
.resize({ width: 800, withoutEnlargement: true })
.webp({ quality: 80 })
.toBuffer();
await s3.send(
new PutObjectCommand({
Bucket: WEB_BUCKET,
Key: `web/${key}.webp`,
Body: output,
ContentType: "image/webp",
}),
);
};writeWebCover downloads the original with GetObjectCommand. If Body is missing, it throws. A throw fails the Lambda invocation, so the SQS batch is not deleted.
transformToByteArray turns the S3 body into bytes Sharp can read.
Sharp resizes to 800 px wide. withoutEnlargement: true means a smaller image is not stretched up. Then it encodes WebP at quality 80 and returns a buffer.
PutObjectCommand writes that buffer to the web bucket. The key is web/${key}.webp. The content type is image/webp.
Throw if GetObject fails. Lambda then retries the batch. After maxReceiveCount, the SQS DLQ holds the notification.
Sharp on Lambda needs a binary that matches Amazon Linux. Packaging that native module is the usual bump in real deploys. Locally you can point S3Client at an emulator with endpoint and forcePathStyle, same as earlier posts.
How it works
Each SQS record includes messageId, receiptHandle, body, and attributes.ApproximateReceiveCount. You rarely delete with the receipt handle yourself when the mapping is in charge. Lambda deletes on success.
A stripped-down picture:
{
"Records": [
{
"messageId": "059f36b4-87a3-44ab-83d2-661975830a7d",
"body": "{\"Records\":[{\"s3\":{\"bucket\":{\"name\":\"pantry-covers-originals\"},\"object\":{\"key\":\"9f3a/soup.jpg\"}}}]}",
"attributes": {
"ApproximateReceiveCount": "1"
},
"eventSource": "aws:sqs"
}
]
}The outer Records array is the SQS batch. This example has one message.
messageId identifies the SQS message.
body is a string. Inside that string is another JSON document. That inner document is the S3 event. It has its own Records array with s3.bucket.name and s3.object.key.
The inner body is a string, not a nested object, until you JSON.parse it. Until you parse it, you cannot read the bucket name or the object key.
ApproximateReceiveCount is how many times SQS has handed this message out. After enough receives, the DLQ takes it.
eventSource is aws:sqs. That confirms the mapping, not a direct S3-to-Lambda invoke.
By default, one throw fails the entire batch. Message A succeeds in your loop, message B throws, and A comes back too.
You can report item failures in the handler response so Lambda deletes the successes. That is worth adding once you process more than one cover per invoke. Until then, keep batches small or make every record idempotent so a replay of A is cheap (same web key overwrite).
Do not mix “delete in the function with DeleteMessage” and “let Lambda delete” without a clear rule. Pick one.
This table is the same job, two owners:
App-owned worker | Lambda + SQS mapping |
|---|---|
You run a Node process | AWS runs pollers and invokes |
You call | Mapping polls; success deletes the batch |
You size the box | You size memory, timeout, and concurrency |
Crash: process supervisor | Crash: retries + DLQ |
You still need IAM. IAM is the permission system on AWS. The function role must s3:GetObject on originals, s3:PutObject on the web bucket, and the mapping needs permission to receive from the queue.
Timeout must exceed Sharp plus both S3 calls. Visibility timeout on the queue should be longer than the function timeout so another invoke does not start while the first is still running.
Memory defaults (128 MB) are tight for Sharp. Start around 1024 MB and watch duration. More memory also means more CPU on Lambda, which shortens resize time. Set the timeout to a minute for 800 px covers unless you process huge TIFFs.
The execution role needs s3:GetObject on pantry-covers-originals/*, s3:PutObject on pantry-covers-web/*, and the mapping needs sqs:ReceiveMessage, sqs:DeleteMessage, and sqs:GetQueueAttributes on the processing queue. Missing one of those looks like a code bug.
Package Sharp for Amazon Linux 2023 (or the runtime you picked). A node_modules folder copied from macOS ARM will throw on import. Lambda layers and Docker image functions are the two usual fixes. Confirm with a one-line handler that only import sharp before you add S3.
The full path is: presigned PUT, then S3 originals, then a notification, then SQS, then Lambda, then the web bucket. The next post compares that shape with the Fastify plus worker plus DynamoDB pipeline so you can pick one on purpose.
Common mistakes
Writing the output to the originals bucket. You already know the loop. Lambda will scale the loop for you. That is worse. Write the WebP to a second bucket.
Parsing event.Records as S3 records. Those are SQS records. S3 lives in body. Parse record.body, then walk the inner Records.
Ignoring native Sharp on Lambda. The function fails every time, the DLQ fills, and the code looked fine on your Mac. Package a binary that matches Amazon Linux.
Function timeout shorter than visibility. Overlapping invokes, double Sharp, confused logs. Set the queue visibility timeout longer than the Lambda timeout.
Assuming one invoke, one image. Batches exist. Write the outer loop first.
No DLQ on the queue. A bad notification retries until retention expires.
When you do not need this
If you already run workers, need a debugger attached, or depend on a GPU or a binary Lambda will not package, keep the Node loop. Lambda shines when you do not want that process: traffic is spiky, idle time should cost zero, and the work fits the timeout.
Further reading
- Using Lambda with Amazon SQS – polling, batches, example events, at-least-once warning
- Previous: S3 event notifications to SQS
- Next: Two AWS designs for an image pipeline
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.
- 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.
- 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.