From ec37c3f27bcb8bcdf9564e6bd0267a6c2bdae140 Mon Sep 17 00:00:00 2001 From: Tomasz Czubocha Date: Wed, 25 Nov 2026 22:10:42 +0000 Subject: [PATCH 1/3] feat(aws-node-sqs-worker): bring the example to the standard with a live test --- README.md | 2 +- aws-node-sqs-worker/README.md | 198 ++++++++++--- aws-node-sqs-worker/example.json | 30 ++ aws-node-sqs-worker/handler.js | 20 -- aws-node-sqs-worker/handler.mjs | 38 +++ aws-node-sqs-worker/package-lock.json | 397 -------------------------- aws-node-sqs-worker/package.json | 10 - aws-node-sqs-worker/serverless.yml | 38 ++- aws-node-sqs-worker/test/smoke.mjs | 109 +++++++ examples.json | 5 +- 10 files changed, 370 insertions(+), 477 deletions(-) create mode 100644 aws-node-sqs-worker/example.json delete mode 100644 aws-node-sqs-worker/handler.js create mode 100644 aws-node-sqs-worker/handler.mjs delete mode 100644 aws-node-sqs-worker/package-lock.json delete mode 100644 aws-node-sqs-worker/package.json create mode 100644 aws-node-sqs-worker/test/smoke.mjs diff --git a/README.md b/README.md index da198b4ce..a1f868f2c 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ serverless deploy | [AWS Simple HTTP Endpoint example in NodeJS](https://github.com/serverless/examples/tree/v4/aws-node-simple-http-endpoint)
This example demonstrates how to setup a simple HTTP GET endpoint. Once you ping it, it will reply with the current time. | nodeJS | | [Simple AWS Transcribe example in NodeJS](https://github.com/serverless/examples/tree/v4/aws-node-simple-transcribe-s3)
This example demonstrates how to setup a lambda function to transcribe your audio file (.wav format) into a text transcription. The lambda will be triggered whenever a new audio file is uploaded to S3 and the transcription (JSON format) will be saved to a S3 bucket. | nodeJS | | [AWS Single Page Application example in NodeJS](https://github.com/serverless/examples/tree/v4/aws-node-single-page-app-via-cloudfront)
This example demonstrates how to setup a Single Page Application. | nodeJS | -| [Node SQS Producer Consumer on AWS](https://github.com/serverless/examples/tree/v4/aws-node-sqs-worker)
This template demonstrates how to develop and deploy a simple SQS-based producer-consumer service running on AWS Lambda using the traditional Serverless Framework. | nodeJS | +| [Node SQS Producer Consumer on AWS](https://github.com/serverless/examples/tree/v4/aws-node-sqs-worker)
This example shows how a Lambda function behind an HTTP API puts jobs on an Amazon SQS queue and a worker function processes them in batches, reporting failed messages so they retry and then move to a dead-letter queue. | nodeJS | | [AWS Stripe Integration example in NodeJS](https://github.com/serverless/examples/tree/v4/aws-node-stripe-integration)
This example for Stripe integration using AWS Lambda and API Gateway. | nodeJS | | [Simple Telegram bot](https://github.com/serverless/examples/tree/v4/aws-node-telegram-echo-bot)
This is a simple echo bot on Telegram. | nodeJS | | [AWS Data Processing example in NodeJS](https://github.com/serverless/examples/tree/v4/aws-node-text-analysis-via-sns-post-processing)
This example shows how a Lambda function behind an HTTP API publishes a note to an Amazon SNS topic and a second function subscribed to the topic analyzes it. | nodeJS | diff --git a/aws-node-sqs-worker/README.md b/aws-node-sqs-worker/README.md index 529baf0b3..fcca85852 100644 --- a/aws-node-sqs-worker/README.md +++ b/aws-node-sqs-worker/README.md @@ -1,6 +1,6 @@ -# Serverless Framework Node SQS Producer-Consumer on AWS +# Process a queue with Amazon SQS and Lambda -This template demonstrates how to build a producer-consumer service on AWS Lambda using the Serverless Framework. A `producer` function is exposed over HTTP API and accepts JSON payloads, which it forwards to an SQS queue for asynchronous processing. A `consumer` function is subscribed to that same queue and processes each message as it arrives. +[![Verified](https://raw.githubusercontent.com/serverless/examples/verified/badges/aws-node-sqs-worker.svg)](https://github.com/serverless/examples/blob/verified/results.json) -This template does not include any kind of persistence (database). For more advanced examples, check out the [serverless/examples repository](https://github.com/serverless/examples/) which includes Typescript, Mongo, DynamoDB and other examples. +An HTTP endpoint can accept work and leave it for later: it puts each job on an Amazon SQS queue and answers at once, and a worker function processes the queue in batches. The [`sqs` event](https://www.serverless.com/framework/docs/providers/aws/events/sqs) of the Serverless Framework connects the worker to the queue. With partial batch responses the worker reports only the messages it couldn't process, so the rest of the batch is done, and a dead-letter queue takes a message that keeps failing, so it doesn't come back forever. This example accepts jobs at `POST /jobs`, processes the ones that name a task, and moves the others to the dead-letter queue after three tries. -## Anatomy of the template +## What it deploys -This template defines two functions, `producer` and `consumer`, and one SQS queue, `JobsQueue`. +- An HTTP API with one route, `POST /jobs`, and a Lambda function, `producer`, that puts each job on the jobs queue. +- An SQS queue named `sqs-worker--jobs`, and a dead-letter queue named `sqs-worker--jobs-dlq` that keeps a failed job for 14 days. +- A Lambda function, `worker`, that Lambda invokes with batches of up to 10 messages from the jobs queue. +- An IAM role that lets the functions write their logs, lets `producer` send to the jobs queue only and lets `worker` read and delete its messages, and a CloudWatch Logs log group for each function. -- `producer` is triggered by an `httpApi` event on `POST /produce`. It accepts any request body and sends it as a message to `JobsQueue`, then responds immediately with a `202` status so the caller doesn't have to wait for the message to be processed. -- `consumer` is triggered by an `sqs` event sourced from `JobsQueue` with a batch size of 10. It logs each message it receives; this is where you would add your own background processing logic. +## Prerequisites -To learn more: +- The Serverless Framework CLI: `npm i -g serverless`, which needs [Node.js](https://nodejs.org/). See [Getting started](https://www.serverless.com/framework/docs/getting-started). +- An AWS account, with credentials configured on your machine. See [AWS credentials](https://www.serverless.com/framework/docs/providers/aws/guide/credentials). +- A Serverless account, or a license key in `SERVERLESS_LICENSE_KEY`. The CLI asks you to sign in the first time you run it. +- `curl`, to send jobs, and the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html), to read the dead-letter queue. The commands in Try it are written for Bash. -- about `httpApi` event configuration options, refer to the [HTTP API (API Gateway V2) event docs](https://www.serverless.com/framework/docs/providers/aws/events/http-api) -- about `sqs` event configuration options, refer to the [SQS event docs](https://www.serverless.com/framework/docs/providers/aws/events/sqs) -- about SQS processing with AWS Lambda, refer to the official [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html) +## Deploy -## Usage +Deploy from this directory: -### Deployment +```bash +serverless deploy +``` -Install dependencies with: +Without options, the deploy uses the stage `dev` and the Region `us-east-1`. To change them, pass `--stage` or `--region`, and pass the same options to every later command, including `serverless remove`. +You should see output like this: + +```text +Deploying "sqs-worker" to stage "dev" (us-east-1) +✔ Service deployed to stack sqs-worker-dev (119s) +endpoint: POST - https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/jobs + +functions: + producer: sqs-worker-dev-producer (8 kB) + worker: sqs-worker-dev-worker (8 kB) ``` -npm install -``` -Then deploy with: +## Try it + +Copy the endpoint from the deploy output into a shell variable: +```bash +URL=https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/jobs ``` -serverless deploy + +Send a job with a task, and a job without one: + +```bash +curl -X POST "$URL" -H 'content-type: application/json' --data '{"task": "resize photo-1.png"}' +curl -X POST "$URL" -H 'content-type: application/json' --data '{"name": "photo-2.png"}' ``` -After running deploy, you should see output similar to: +The API answers each with status 202 and the ID of the SQS message, before the job is processed: +```json +{"messageId":"ec7e4da2-61be-4b48-a044-75f90574a751"} +{"messageId":"7ab82ef6-12ea-4e01-9204-15c5b6ad7059"} ``` -Deploying "sqs-worker" to stage "dev" (us-east-1) -✔ Service deployed to stack sqs-worker-dev (78s) +Lambda polls the queue and invokes `worker` a moment later. Its log shows the first job processed. The second job fails, goes back to the queue, and is received again each time the queue's 36-second visibility timeout ends: -endpoint: POST - https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/produce -functions: - producer: sqs-worker-dev-producer (1.8 kB) - consumer: sqs-worker-dev-consumer (1.8 kB) +```bash +serverless logs --function worker ``` -_Note_: In current form, after deployment, your API is public and can be invoked by anyone. For production deployments, you might want to configure an authorizer. For details on how to do that, refer to the [HTTP API (API Gateway V2) event docs](https://www.serverless.com/framework/docs/providers/aws/events/http-api). +```text +INFO Processed job ec7e4da2-61be-4b48-a044-75f90574a751: resize photo-1.png +ERROR Job 7ab82ef6-12ea-4e01-9204-15c5b6ad7059 failed on receive 1: the job has no "task" string +ERROR Job 7ab82ef6-12ea-4e01-9204-15c5b6ad7059 failed on receive 2: the job has no "task" string +ERROR Job 7ab82ef6-12ea-4e01-9204-15c5b6ad7059 failed on receive 3: the job has no "task" string +``` -### Invocation +If the command prints `No existing streams for the function`, or a line isn't there yet, the worker hasn't run yet: wait a few seconds and run the command again. -After successful deployment, you can submit a job by sending a `POST` request to the `/produce` endpoint: +After the third failure, SQS moves the job to the dead-letter queue, about two minutes after it was sent. Show the stack outputs to find the dead-letter queue's URL: +```bash +serverless info --verbose ``` -curl -X POST https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/produce -d '{"job":"hello"}' + +```text +Stack Outputs: + DeadLetterQueueUrl: https://sqs.us-east-1.amazonaws.com/123456789012/sqs-worker-dev-jobs-dlq ``` -Which should result in a response similar to: +Read the job from the dead-letter queue with the AWS CLI: -```json -{ "status": "queued" } +```bash +aws sqs receive-message --region us-east-1 \ + --queue-url https://sqs.us-east-1.amazonaws.com/123456789012/sqs-worker-dev-jobs-dlq \ + --query 'Messages[].[MessageId,Body]' --output text +``` + +```text +7ab82ef6-12ea-4e01-9204-15c5b6ad7059 {"name":"photo-2.png"} ``` -with an HTTP status code of `202`. +A body that isn't a JSON object gets status 400 and `{"error":"Send a JSON object as the body."}`, and nothing is queued. -The message is placed on the `JobsQueue` SQS queue, and the `consumer` function picks it up and processes it. You can view its logs with: +## How it works +The `sqs` event in [`serverless.yml`](https://github.com/serverless/examples/blob/v4/aws-node-sqs-worker/serverless.yml) creates the event source mapping: Lambda polls the queue, invokes `worker` with up to 10 messages, and deletes the messages the worker processed. `functionResponseType: ReportBatchItemFailures` lets the worker name the messages it couldn't process, so only those return to the queue: + +```yaml +functions: + worker: + handler: handler.worker + events: + - sqs: + arn: !GetAtt JobsQueue.Arn + batchSize: 10 + functionResponseType: ReportBatchItemFailures ``` -serverless logs -f consumer + +The `sqs` event doesn't create queues, so both queues are declared under `resources`. The jobs queue's `RedrivePolicy` moves a message that was received three times without being deleted to the dead-letter queue. Its visibility timeout is at least the worker's timeout (6 seconds by default), as Lambda requires, and six times it, as AWS recommends: + +```yaml +resources: + Resources: + JobsQueue: + Type: AWS::SQS::Queue + Properties: + QueueName: ${self:service}-${sls:stage}-jobs + VisibilityTimeout: 36 + RedrivePolicy: + deadLetterTargetArn: !GetAtt DeadLetterQueue.Arn + maxReceiveCount: 3 + + DeadLetterQueue: + Type: AWS::SQS::Queue + Properties: + QueueName: ${self:service}-${sls:stage}-jobs-dlq + MessageRetentionPeriod: 1209600 ``` -Which should print output similar to: +Queue names are unique per account and Region, so the names include the stage: two stages get two pairs of queues. The `producer` function gets the jobs queue's URL in an environment variable, and its role may send to that queue only: + +```yaml +provider: + iam: + role: + statements: + - Effect: Allow + Action: + - sqs:SendMessage + Resource: !GetAtt JobsQueue.Arn +functions: + producer: + handler: handler.producer + environment: + QUEUE_URL: !Ref JobsQueue + events: + - httpApi: + path: /jobs + method: post ``` -processing job 9d1f2e3a-... {"job":"hello"} + +[`handler.mjs`](https://github.com/serverless/examples/blob/v4/aws-node-sqs-worker/handler.mjs) holds both functions. `producer` sends the job with the AWS SDK for JavaScript v3, which the Node.js runtime includes, and returns the message ID. `worker` processes each message of the batch on its own, and returns the IDs of the messages that failed in `batchItemFailures`: + +```javascript +export const worker = async (event) => { + const batchItemFailures = []; + for (const record of event.Records) { + try { + const job = JSON.parse(record.body); + if (typeof job.task !== 'string' || job.task.trim() === '') throw new Error('the job has no "task" string'); + console.log(`Processed job ${record.messageId}: ${job.task}`); + } catch (err) { + console.error(`Job ${record.messageId} failed on receive ${record.attributes.ApproximateReceiveCount}: ${err.message}`); + batchItemFailures.push({ itemIdentifier: record.messageId }); + } + } + return { batchItemFailures }; +}; ``` -### Removal +If the worker threw instead, Lambda would return every message of the batch to the queue, and the jobs that succeeded would run again. See [Handling errors for an SQS event source in Lambda](https://docs.aws.amazon.com/lambda/latest/dg/services-sqs-errorhandling.html). -When you are done, you can remove the service and all of its resources with: +## Cost and cleanup -``` +While the example is deployed, API Gateway bills each request to the HTTP API, Amazon SQS bills each request to the queues (sending, Lambda's polling, and receiving and deleting messages), Lambda bills each invocation and the functions' compute time, and CloudWatch Logs bills the functions' stored log data. See [API Gateway pricing](https://aws.amazon.com/api-gateway/pricing/), [Amazon SQS pricing](https://aws.amazon.com/sqs/pricing/), [Lambda pricing](https://aws.amazon.com/lambda/pricing/) and [CloudWatch pricing](https://aws.amazon.com/cloudwatch/pricing/). + +Remove the API, the queues and the messages in them, the functions and their log groups: + +```bash serverless remove ``` + +## Next steps + +- Read [SQS queue events](https://www.serverless.com/framework/docs/providers/aws/events/sqs) for batching windows, filter patterns that send the worker only some messages, maximum concurrency and FIFO queues. +- Move the jobs from the dead-letter queue back to the jobs queue once the worker can process them, with a [dead-letter queue redrive](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-configure-dead-letter-queue-redrive.html). +- Deliver each message to several subscribers instead of one worker, as the [SNS example](https://github.com/serverless/examples/tree/v4/aws-node-text-analysis-via-sns-post-processing) does. diff --git a/aws-node-sqs-worker/example.json b/aws-node-sqs-worker/example.json new file mode 100644 index 000000000..fac214799 --- /dev/null +++ b/aws-node-sqs-worker/example.json @@ -0,0 +1,30 @@ +{ + "title": "Node SQS Producer Consumer on AWS", + "description": "This example shows how a Lambda function behind an HTTP API puts jobs on an Amazon SQS queue and a worker function processes them in batches, reporting failed messages so they retry and then move to a dead-letter queue.", + "language": "node", + "platform": "AWS", + "framework": "v4", + "priority": 1, + "author": { + "name": "Serverless, Inc.", + "link": "https://github.com/serverless", + "avatar": "https://avatars1.githubusercontent.com/u/13742415?s=200&v=4" + }, + "services": [ + "lambda", + "apigateway", + "sqs", + "iam", + "logs" + ], + "test": { + "tier": "fast", + "checks": [ + { + "script": { + "path": "test/smoke.mjs" + } + } + ] + } +} diff --git a/aws-node-sqs-worker/handler.js b/aws-node-sqs-worker/handler.js deleted file mode 100644 index bc7280ea0..000000000 --- a/aws-node-sqs-worker/handler.js +++ /dev/null @@ -1,20 +0,0 @@ -import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs'; - -const sqs = new SQSClient({}); - -export const producer = async (event) => { - if (!event.body) { - return { statusCode: 400, body: JSON.stringify({ error: 'request body required' }) }; - } - await sqs.send(new SendMessageCommand({ - QueueUrl: process.env.QUEUE_URL, - MessageBody: event.body, - })); - return { statusCode: 202, body: JSON.stringify({ status: 'queued' }) }; -}; - -export const consumer = async (event) => { - for (const record of event.Records) { - console.log('processing job', record.messageId, record.body); - } -}; diff --git a/aws-node-sqs-worker/handler.mjs b/aws-node-sqs-worker/handler.mjs new file mode 100644 index 000000000..c646f5344 --- /dev/null +++ b/aws-node-sqs-worker/handler.mjs @@ -0,0 +1,38 @@ +import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs'; + +const sqs = new SQSClient(); + +// POST /jobs with a JSON object: puts it on the jobs queue and answers right +// away. The worker processes it later. +export const producer = async (event) => { + let job; + try { + const body = event.isBase64Encoded ? Buffer.from(event.body, 'base64').toString('utf8') : event.body; + job = JSON.parse(body ?? ''); + } catch { + // Not JSON: answered below. + } + if (job === null || typeof job !== 'object' || Array.isArray(job)) { + return { statusCode: 400, body: JSON.stringify({ error: 'Send a JSON object as the body.' }) }; + } + + const { MessageId } = await sqs.send(new SendMessageCommand({ QueueUrl: process.env.QUEUE_URL, MessageBody: JSON.stringify(job) })); + return { statusCode: 202, body: JSON.stringify({ messageId: MessageId }) }; +}; + +// Invoked by Lambda with a batch of up to 10 messages from the queue. Returns +// the IDs of the messages it couldn't process, so only those are retried. +export const worker = async (event) => { + const batchItemFailures = []; + for (const record of event.Records) { + try { + const job = JSON.parse(record.body); + if (typeof job.task !== 'string' || job.task.trim() === '') throw new Error('the job has no "task" string'); + console.log(`Processed job ${record.messageId}: ${job.task}`); + } catch (err) { + console.error(`Job ${record.messageId} failed on receive ${record.attributes.ApproximateReceiveCount}: ${err.message}`); + batchItemFailures.push({ itemIdentifier: record.messageId }); + } + } + return { batchItemFailures }; +}; diff --git a/aws-node-sqs-worker/package-lock.json b/aws-node-sqs-worker/package-lock.json deleted file mode 100644 index 6bf31defc..000000000 --- a/aws-node-sqs-worker/package-lock.json +++ /dev/null @@ -1,397 +0,0 @@ -{ - "name": "sqs-worker", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "sqs-worker", - "version": "1.0.0", - "license": "MIT", - "dependencies": { - "@aws-sdk/client-sqs": "^3.700.0" - } - }, - "node_modules/@aws-sdk/client-sqs": { - "version": "3.1085.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sqs/-/client-sqs-3.1085.0.tgz", - "integrity": "sha512-ND4HTISx/vwGhNmqgwaI/oQRVrTwqGerPJL0a6z0bRRme73fQ8RcciuVEDZT/klD5/J/uvw8g7cWlo+XjIMF/Q==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.975.1", - "@aws-sdk/credential-provider-node": "^3.972.66", - "@aws-sdk/middleware-sdk-sqs": "^3.972.35", - "@aws-sdk/types": "^3.974.0", - "@smithy/core": "^3.29.2", - "@smithy/fetch-http-handler": "^5.6.4", - "@smithy/node-http-handler": "^4.9.4", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/core": { - "version": "3.975.1", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.975.1.tgz", - "integrity": "sha512-8qh/6EYb7hl/ZwVfQufhbMEZs1gQIc7GbdrIf4eprQJ7cv042+74nE6l3YDfyWNzb9iPXb8fRyYSHkNIk5eE6Q==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "^3.974.0", - "@aws-sdk/xml-builder": "^3.972.34", - "@aws/lambda-invoke-store": "^0.3.0", - "@smithy/core": "^3.29.2", - "@smithy/signature-v4": "^5.6.3", - "@smithy/types": "^4.16.0", - "bowser": "^2.11.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-env": { - "version": "3.972.57", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.57.tgz", - "integrity": "sha512-1RfJaF7SW1TOnvNGU7kaYjwUf5H3sfm+synGH1bHhRlqcnxCt3szebH3dmKEyY4tuGcbQ6ffzUT89cRitBV8OQ==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.975.1", - "@aws-sdk/types": "^3.974.0", - "@smithy/core": "^3.29.2", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-http": { - "version": "3.972.59", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.59.tgz", - "integrity": "sha512-sRCkpTiFnCdQvuaRVjQ6SVoHu6i7RUpurVo1c4F81HWhPvUJ7Wdp5MNtSdX1O29CNXc8em3O5m52hCjVtAD9SA==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.975.1", - "@aws-sdk/types": "^3.974.0", - "@smithy/core": "^3.29.2", - "@smithy/fetch-http-handler": "^5.6.4", - "@smithy/node-http-handler": "^4.9.4", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.973.1", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.1.tgz", - "integrity": "sha512-6d8H6ZAh3ZPKZ6fe1nG2OWeZEZPtt9ravoD1dezPdPtsSkJRoxGAnFSHwKT3E/Te6fHE30zRzjV6TD12rvF6yQ==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.975.1", - "@aws-sdk/credential-provider-env": "^3.972.57", - "@aws-sdk/credential-provider-http": "^3.972.59", - "@aws-sdk/credential-provider-login": "^3.972.63", - "@aws-sdk/credential-provider-process": "^3.972.57", - "@aws-sdk/credential-provider-sso": "^3.973.1", - "@aws-sdk/credential-provider-web-identity": "^3.972.63", - "@aws-sdk/nested-clients": "^3.997.31", - "@aws-sdk/types": "^3.974.0", - "@smithy/core": "^3.29.2", - "@smithy/credential-provider-imds": "^4.4.7", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-login": { - "version": "3.972.63", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.63.tgz", - "integrity": "sha512-GREWRrMj0XnNKMaVa/Mauoaui26qBEHu71WWqXbwZOu/jFQOnPZjTf7u0KtGKC8VGa6VUs9kDWGgocrKNLS9vw==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.975.1", - "@aws-sdk/nested-clients": "^3.997.31", - "@aws-sdk/types": "^3.974.0", - "@smithy/core": "^3.29.2", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-node": { - "version": "3.972.66", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.66.tgz", - "integrity": "sha512-f+qjRXZpz7sgzbc4QB+6nLKfyKFgRRXzWdXbsKPv/VhVRyHsDyq4yBWC/B75BAJpFIcUeI2XR/3gdWJ677zB4A==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/credential-provider-env": "^3.972.57", - "@aws-sdk/credential-provider-http": "^3.972.59", - "@aws-sdk/credential-provider-ini": "^3.973.1", - "@aws-sdk/credential-provider-process": "^3.972.57", - "@aws-sdk/credential-provider-sso": "^3.973.1", - "@aws-sdk/credential-provider-web-identity": "^3.972.63", - "@aws-sdk/types": "^3.974.0", - "@smithy/core": "^3.29.2", - "@smithy/credential-provider-imds": "^4.4.7", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-process": { - "version": "3.972.57", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.57.tgz", - "integrity": "sha512-TiVQhuU0pbhIZAUZacbPHMyzrIdiH+lnx+PMY/Pu/b93dJrq3wdZwzUJ0TPpvNxaqbHsxJvQZW3/h/beLiKq7Q==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.975.1", - "@aws-sdk/types": "^3.974.0", - "@smithy/core": "^3.29.2", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.973.1", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.1.tgz", - "integrity": "sha512-3foTZUJ4821Ij60X7K3NJroygiZLnbBmarN+T//O2cjkISan90zElN3NBmgSlDrTQ7Gs6z/yO8V7h60QNcDZHQ==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.975.1", - "@aws-sdk/nested-clients": "^3.997.31", - "@aws-sdk/token-providers": "3.1083.0", - "@aws-sdk/types": "^3.974.0", - "@smithy/core": "^3.29.2", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-web-identity": { - "version": "3.972.63", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.63.tgz", - "integrity": "sha512-8qZLFhM69eKcS37m459ctPR05Qimycm/74OPVioe6wNZabMT54GYhwBju0+J656RkMasNSawWQu+c8CmBe3TUQ==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.975.1", - "@aws-sdk/nested-clients": "^3.997.31", - "@aws-sdk/types": "^3.974.0", - "@smithy/core": "^3.29.2", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/middleware-sdk-sqs": { - "version": "3.972.35", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-sqs/-/middleware-sdk-sqs-3.972.35.tgz", - "integrity": "sha512-J1u7OABwjjBB7sUJiET05dPVAfjFeR6vfM5//DInKuPzc7PhPVNEviC7RqbsIsBdZi8xICVnHemFrTuvGmhySA==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "^3.974.0", - "@smithy/core": "^3.29.2", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/nested-clients": { - "version": "3.997.31", - "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.31.tgz", - "integrity": "sha512-BDHTpwcsZHEBNEJzOg/B1BkFYJxAXY50dau/NyVWs3d51F0WgIUGSWZot/Os+N3KpDhXeaXnz37mWffAvduREw==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.975.1", - "@aws-sdk/signature-v4-multi-region": "^3.996.39", - "@aws-sdk/types": "^3.974.0", - "@smithy/core": "^3.29.2", - "@smithy/fetch-http-handler": "^5.6.4", - "@smithy/node-http-handler": "^4.9.4", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/signature-v4-multi-region": { - "version": "3.996.39", - "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.39.tgz", - "integrity": "sha512-8+srXqYIF8KYMLC4FxMLEM5Ek7kUNibJu1R4m8/fUhhNYIZZz26oGtKkCr8I/HiG2fFQxBvaGgQZT4/mqRCSnA==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "^3.974.0", - "@smithy/signature-v4": "^5.6.3", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/token-providers": { - "version": "3.1083.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1083.0.tgz", - "integrity": "sha512-s0woKnxuHrExLc5L2ArIH5BMkbonHPtt+5hSBM8oknp9M6QTuUmmAmJ2E0EdzCGONrO+8+ADPqvv6UX0nNcc7A==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.975.1", - "@aws-sdk/nested-clients": "^3.997.31", - "@aws-sdk/types": "^3.974.0", - "@smithy/core": "^3.29.2", - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/types": { - "version": "3.974.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.974.0.tgz", - "integrity": "sha512-QIBrw90CDm4O0UaIIzkU6DrFdeJzEb2Va5EPEVpyldj6sHJxB6cshhStJuhZxk3wR3PmjJlYsjPmY1kNb+KGBg==", - "license": "Apache-2.0", - "dependencies": { - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/xml-builder": { - "version": "3.972.34", - "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.34.tgz", - "integrity": "sha512-wHhWL1y7sN3enBA8POrPpQM5jCcmu2ozyhbRei4c8OjVcEaEs6yLucLa/pla457ggS/ysuy7bosagz3HaJkZXA==", - "license": "Apache-2.0", - "dependencies": { - "@smithy/types": "^4.16.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws/lambda-invoke-store": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz", - "integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/core": { - "version": "3.29.3", - "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.29.3.tgz", - "integrity": "sha512-L+Ys6ecjk5vwPMAKHBpPKlJ3DkqwNcnfEISXBZIsVvWG/XKXfsAP8mwIYlTeLcd2ElHdesPI8OuOmJSFAPhm6A==", - "license": "Apache-2.0", - "dependencies": { - "@smithy/types": "^4.16.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/credential-provider-imds": { - "version": "4.4.8", - "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.4.8.tgz", - "integrity": "sha512-q9J7JTiXrAhB8sDp4px97uEPT7CwKH61Co78grdNQvU8QZAdiuaSRhP0tUVf2ogy36RZTrlMU1rBmDEH+cnkiA==", - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.29.3", - "@smithy/types": "^4.16.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/fetch-http-handler": { - "version": "5.6.5", - "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.6.5.tgz", - "integrity": "sha512-SuqeisTyPoiIPtIYru/sGxGyXzmZ+8nnFOhC+qRPglt06Ebd1yH//CDltZB2J/3WBNVhwfUaZ0EtHB3cm2X32g==", - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.29.3", - "@smithy/types": "^4.16.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/node-http-handler": { - "version": "4.9.5", - "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.9.5.tgz", - "integrity": "sha512-bNqdxTQTxmLbomSmlkZFz8L6B/feQ2HHzw4L2zY7Ecp2XffYAZq2uzdWDdxJHJFbEvqd+SRuluJso0P8+xPdbw==", - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.29.3", - "@smithy/types": "^4.16.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/signature-v4": { - "version": "5.6.4", - "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.6.4.tgz", - "integrity": "sha512-B89bpf2t/y/wia6LZ+4JfHXYQT9PnVftsH05rgJKKIStS7r/4XSs9HOjtPoLtgcA6HCW9jVqX5DBbq7E0PAkiQ==", - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.29.3", - "@smithy/types": "^4.16.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/types": { - "version": "4.16.1", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.16.1.tgz", - "integrity": "sha512-0JFs3V2y2M9tKW5na/qxe69Zv+uxLMO7QBbhxF/FHu/Gp2NFZAAL9tWl9PU02xxo07pb3G9FTyjNc6D5uZrJIg==", - "license": "Apache-2.0", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/bowser": { - "version": "2.14.1", - "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz", - "integrity": "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==", - "license": "MIT" - }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "license": "0BSD" - } - } -} diff --git a/aws-node-sqs-worker/package.json b/aws-node-sqs-worker/package.json deleted file mode 100644 index 4831732d3..000000000 --- a/aws-node-sqs-worker/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "sqs-worker", - "version": "1.0.0", - "type": "module", - "description": "Serverless Framework Node SQS producer-consumer on AWS", - "license": "MIT", - "dependencies": { - "@aws-sdk/client-sqs": "^3.700.0" - } -} diff --git a/aws-node-sqs-worker/serverless.yml b/aws-node-sqs-worker/serverless.yml index 7a9d46f69..e5c2881d3 100644 --- a/aws-node-sqs-worker/serverless.yml +++ b/aws-node-sqs-worker/serverless.yml @@ -1,4 +1,5 @@ service: sqs-worker + frameworkVersion: '4' provider: @@ -8,8 +9,11 @@ provider: iam: role: statements: + # The producer may send messages to this service's jobs queue and nothing else. + # The sqs event adds the permissions the worker needs to read the queue. - Effect: Allow - Action: sqs:SendMessage + Action: + - sqs:SendMessage Resource: !GetAtt JobsQueue.Arn functions: @@ -19,18 +23,42 @@ functions: QUEUE_URL: !Ref JobsQueue events: - httpApi: - path: /produce + path: /jobs method: post - consumer: - handler: handler.consumer + + worker: + handler: handler.worker events: + # Creates the event source mapping: Lambda polls the queue and invokes + # the worker with up to 10 messages at a time. - sqs: arn: !GetAtt JobsQueue.Arn batchSize: 10 + # The worker returns the messages it couldn't process; only those go back to the queue. + functionResponseType: ReportBatchItemFailures +# The sqs event doesn't create queues, so they are declared here. resources: Resources: JobsQueue: Type: AWS::SQS::Queue Properties: - QueueName: ${self:service}-jobs-${sls:stage} + # The stage in the name lets two stages of this service share an account. + QueueName: ${self:service}-${sls:stage}-jobs + # At least the worker's timeout (6 seconds by default); AWS recommends six times it. + VisibilityTimeout: 36 + # A message received 3 times without success moves to the dead-letter queue. + RedrivePolicy: + deadLetterTargetArn: !GetAtt DeadLetterQueue.Arn + maxReceiveCount: 3 + + DeadLetterQueue: + Type: AWS::SQS::Queue + Properties: + QueueName: ${self:service}-${sls:stage}-jobs-dlq + # Keep failed jobs for 14 days, the longest SQS allows. + MessageRetentionPeriod: 1209600 + + Outputs: + DeadLetterQueueUrl: + Value: !Ref DeadLetterQueue diff --git a/aws-node-sqs-worker/test/smoke.mjs b/aws-node-sqs-worker/test/smoke.mjs new file mode 100644 index 000000000..de5e9e0be --- /dev/null +++ b/aws-node-sqs-worker/test/smoke.mjs @@ -0,0 +1,109 @@ +// Does what the README's Try it does: posts a valid job and a job without a +// task to the HTTP API, which puts both on the jobs queue. Then waits for the +// worker's log line for the valid job, and for the other job to arrive in the +// dead-letter queue after the worker reported it as failed three times. +// +// Run by the example test runner, with the stack outputs in EXAMPLE_OUTPUTS, +// EXAMPLE_REGION set and AWS credentials in the environment. It calls the aws +// CLI to read the worker's log group (logs filter-log-events) and the +// dead-letter queue (sqs receive-message). + +import { execFileSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; + +const DELAY_MS = 3_000; +const API_WAIT_MS = 90_000; +const LOG_WAIT_MS = 120_000; +// Three receives, 36 seconds of visibility timeout apart, then the move to the dead-letter queue. +const DLQ_WAIT_MS = 300_000; + +const outputs = JSON.parse(process.env.EXAMPLE_OUTPUTS ?? '{}'); +const apiUrl = outputs.HttpApiUrl; +const functionArn = outputs.WorkerLambdaFunctionQualifiedArn; +const dlqUrl = outputs.DeadLetterQueueUrl; +if (!apiUrl || !functionArn || !dlqUrl) { + fail(`stack outputs HttpApiUrl, WorkerLambdaFunctionQualifiedArn and DeadLetterQueueUrl needed; got ${Object.keys(outputs).join(', ')}`); +} +// arn:aws:lambda:::function:: +const logGroup = `/aws/lambda/${functionArn.split(':')[6]}`; +const region = ['--region', process.env.EXAMPLE_REGION ?? 'us-east-1']; + +const tag = randomBytes(4).toString('hex'); +const start = Date.now(); +const goodId = await postJob({ task: `resize photo-${tag}.png` }); +const badId = await postJob({ name: `photo-${tag}.png` }); + +// Lambda polls the queue, so the worker's line appears after a moment. +const wanted = `Processed job ${goodId}: resize photo-${tag}.png`; +let text = ''; +for (;;) { + try { + const out = aws(['logs', 'filter-log-events', ...region, '--log-group-name', logGroup, + '--filter-pattern', `"${goodId}"`, '--start-time', String(start - 60_000), '--output', 'json']); + if (JSON.parse(out).events.some((e) => e.message.includes(wanted))) break; + text = 'no matching line yet'; + } catch (err) { + // The log group exists only after the first invocation. + text = err.message; + } + if (Date.now() - start >= LOG_WAIT_MS) fail(`${logGroup}: no "${wanted}" line within ${LOG_WAIT_MS / 1000} s; last: ${text.slice(0, 300)}`); + await sleep(DELAY_MS); +} + +// The job without a task fails on every receive and then moves to the dead-letter queue. +let found; +const seen = new Set(); +for (;;) { + const out = aws(['sqs', 'receive-message', ...region, '--queue-url', dlqUrl, '--max-number-of-messages', '10', + '--wait-time-seconds', '10', '--visibility-timeout', '0', '--output', 'json']); + const messages = out.trim() ? (JSON.parse(out).Messages ?? []) : []; + for (const m of messages) seen.add(m.MessageId); + found = messages.find((m) => m.MessageId === badId); + if (found) break; + if (seen.has(goodId)) fail(`dead-letter queue: the processed job ${goodId} arrived there too`); + if (Date.now() - start >= DLQ_WAIT_MS) fail(`dead-letter queue: expected message ${badId} within ${DLQ_WAIT_MS / 1000} s; saw ${[...seen].join(', ') || 'none'}`); +} +if (!found.Body.includes(`photo-${tag}.png`)) fail(`dead-letter queue: expected the body of ${badId} to name photo-${tag}.png; got ${found.Body}`); + +console.log(`POST /jobs -> worker logged "${wanted}"; job ${badId} without a task -> dead-letter queue`); + +async function postJob(job) { + let res; + let body; + for (;;) { + // A new HTTP API can take a moment to answer, so the request retries. + try { + res = await fetch(`${apiUrl}/jobs`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(job), + }); + body = await res.text(); + if (res.status === 202) break; + } catch (err) { + body = `request error: ${err.message}`; + } + if (Date.now() - start >= API_WAIT_MS) fail(`POST /jobs: expected status 202; last: ${res?.status} ${body.slice(0, 300)}`); + await sleep(DELAY_MS); + } + const { messageId } = JSON.parse(body); + if (!messageId) fail(`POST /jobs: expected a messageId; got ${body.slice(0, 300)}`); + return messageId; +} + +function aws(args) { + try { + return execFileSync('aws', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); + } catch (err) { + throw new Error(`aws ${args.slice(0, 2).join(' ')}: exit ${err.status}, ${String(err.stderr ?? '').trim().slice(0, 300)}`); + } +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function fail(message) { + console.error(`smoke test failed: ${message}`); + process.exit(1); +} diff --git a/examples.json b/examples.json index 13f3f9f4f..5cf33df9b 100644 --- a/examples.json +++ b/examples.json @@ -762,14 +762,15 @@ { "title": "Node SQS Producer Consumer on AWS", "name": "aws-node-sqs-worker", - "description": "This template demonstrates how to develop and deploy a simple SQS-based producer-consumer service running on AWS Lambda using the traditional Serverless Framework.", + "description": "This example shows how a Lambda function behind an HTTP API puts jobs on an Amazon SQS queue and a worker function processes them in batches, reporting failed messages so they retry and then move to a dead-letter queue.", "githubUrl": "https://github.com/serverless/examples/tree/v4/aws-node-sqs-worker", "framework": "v4", "language": "node", "platform": "aws", "authorLink": "https://github.com/serverless", "authorName": "Serverless, Inc.", - "authorAvatar": "https://avatars1.githubusercontent.com/u/13742415?s=200&v=4" + "authorAvatar": "https://avatars1.githubusercontent.com/u/13742415?s=200&v=4", + "priority": 1 }, { "title": "AWS Stripe Integration example in NodeJS", From 5cba801fc825f3c9f6cee9ad69d9e8ce9cdee32d Mon Sep 17 00:00:00 2001 From: Tomasz Czubocha Date: Wed, 25 Nov 2026 22:25:52 +0000 Subject: [PATCH 2/3] fix(aws-node-sqs-worker): fail the smoke test when the processed job reaches the dead-letter queue --- aws-node-sqs-worker/test/smoke.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aws-node-sqs-worker/test/smoke.mjs b/aws-node-sqs-worker/test/smoke.mjs index de5e9e0be..04dd7e4f0 100644 --- a/aws-node-sqs-worker/test/smoke.mjs +++ b/aws-node-sqs-worker/test/smoke.mjs @@ -58,9 +58,9 @@ for (;;) { '--wait-time-seconds', '10', '--visibility-timeout', '0', '--output', 'json']); const messages = out.trim() ? (JSON.parse(out).Messages ?? []) : []; for (const m of messages) seen.add(m.MessageId); + if (seen.has(goodId)) fail(`dead-letter queue: the processed job ${goodId} arrived there too`); found = messages.find((m) => m.MessageId === badId); if (found) break; - if (seen.has(goodId)) fail(`dead-letter queue: the processed job ${goodId} arrived there too`); if (Date.now() - start >= DLQ_WAIT_MS) fail(`dead-letter queue: expected message ${badId} within ${DLQ_WAIT_MS / 1000} s; saw ${[...seen].join(', ') || 'none'}`); } if (!found.Body.includes(`photo-${tag}.png`)) fail(`dead-letter queue: expected the body of ${badId} to name photo-${tag}.png; got ${found.Body}`); From e77c93bba8b29b78362ec679cbc5ad4203b08257 Mon Sep 17 00:00:00 2001 From: Tomasz Czubocha Date: Wed, 25 Nov 2026 22:46:19 +0000 Subject: [PATCH 3/3] docs(aws-node-sqs-worker): say which log lines and stack outputs the trimmed blocks show --- aws-node-sqs-worker/README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/aws-node-sqs-worker/README.md b/aws-node-sqs-worker/README.md index fcca85852..b1602b92d 100644 --- a/aws-node-sqs-worker/README.md +++ b/aws-node-sqs-worker/README.md @@ -49,8 +49,8 @@ Deploying "sqs-worker" to stage "dev" (us-east-1) endpoint: POST - https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/jobs functions: - producer: sqs-worker-dev-producer (8 kB) - worker: sqs-worker-dev-worker (8 kB) + producer: sqs-worker-dev-producer (8.1 kB) + worker: sqs-worker-dev-worker (8.1 kB) ``` ## Try it @@ -81,6 +81,8 @@ Lambda polls the queue and invokes `worker` a moment later. Its log shows the fi serverless logs --function worker ``` +Among Lambda's own `START`, `END` and `REPORT` lines, the worker's lines are: + ```text INFO Processed job ec7e4da2-61be-4b48-a044-75f90574a751: resize photo-1.png ERROR Job 7ab82ef6-12ea-4e01-9204-15c5b6ad7059 failed on receive 1: the job has no "task" string @@ -88,7 +90,7 @@ ERROR Job 7ab82ef6-12ea-4e01-9204-15c5b6ad7059 failed on receive 2: the job has ERROR Job 7ab82ef6-12ea-4e01-9204-15c5b6ad7059 failed on receive 3: the job has no "task" string ``` -If the command prints `No existing streams for the function`, or a line isn't there yet, the worker hasn't run yet: wait a few seconds and run the command again. +If the command prints `No existing streams for the function` or only an `INIT_START` line, or a line isn't there yet, the worker hasn't run yet: wait a few seconds and run the command again. After the third failure, SQS moves the job to the dead-letter queue, about two minutes after it was sent. Show the stack outputs to find the dead-letter queue's URL: @@ -96,6 +98,8 @@ After the third failure, SQS moves the job to the dead-letter queue, about two m serverless info --verbose ``` +Among the other outputs, the list shows: + ```text Stack Outputs: DeadLetterQueueUrl: https://sqs.us-east-1.amazonaws.com/123456789012/sqs-worker-dev-jobs-dlq