# Add a Dead-Letter Queue to a Serverless SQS Worker

Yes. An agent adds an SQS dead-letter queue with a redrive policy, partial batch failures in the consumer, an alarm on the DLQ, tests, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-dlq/serverless/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the service as it is deployed before it adds a queue to it. In a service shaped like `aws-node-sqs-worker` in serverless/examples, `serverless.yml` names the service `sqs-worker` on `frameworkVersion: '4'`, runtime `nodejs24.x` on `arm64`, and gives the role one statement, `sqs:SendMessage` on `JobsQueue`. Two functions: `producer`, on `httpApi` `POST /produce` with `QUEUE_URL` set from `!Ref JobsQueue`, and `consumer`, on an `sqs` event from `!GetAtt JobsQueue.Arn` with `batchSize: 10`. The `resources` block defines one `AWS::SQS::Queue`, `JobsQueue`, with only a `QueueName` of `${self:service}-jobs-${sls:stage}`. `handler.js` is an ES module: `producer` rejects an empty body with 400 and otherwise sends `event.body` as the message and answers 202; `consumer` loops over `event.Records` and logs each `messageId` and body. `package.json` depends on `@aws-sdk/client-sqs` and has no `test` script.

Two things are missing and the code shows why they matter together. The queue has no `RedrivePolicy`, so a message the consumer cannot process is redelivered every visibility timeout until the queue's retention expires, four days by default, and then disappears without a trace. And `consumer` has no error handling and no `functionResponseType`, so the moment real work is added, one bad message makes Lambda report the whole batch of ten as failed and SQS redelivers all ten, good ones included. The sibling example `aws-python-sqs-worker` uses a Lift construct that creates its dead-letter queue for it; this one is plain CloudFormation and has to spell it out.

The agent adds `JobsDeadLetterQueue`, an `AWS::SQS::Queue` with `MessageRetentionPeriod: 1209600`, the fourteen-day maximum, so a failed message is kept long enough to be looked at, and gives `JobsQueue` a `RedrivePolicy` with `deadLetterTargetArn: !GetAtt JobsDeadLetterQueue.Arn` and `maxReceiveCount: 3`, plus a `VisibilityTimeout` at least six times the consumer's timeout, the ratio AWS documents for Lambda event source mappings. On the `sqs` event it sets `functionResponseType: ReportBatchItemFailures`, and rewrites `consumer` to process each record in a `try` and collect the `messageId` of any that throws into `batchItemFailures` as `itemIdentifier`, returning that object, so only the failing message is retried and, after its third receive, moved to the dead-letter queue. The processing itself becomes a `processJob` function that parses the body as JSON and throws on anything else, which is where a real service puts its work. A `AWS::CloudWatch::Alarm` on `ApproximateNumberOfMessagesVisible` for the dead-letter queue, in the `AWS/SQS` namespace with the queue's name as its dimension, fires at one or more messages, and the pull request says the alarm's action is left for the reader to point at their SNS topic.

Tests use the runtime's own runner, since Node 24 has `node:test` built in: a `test` script of `node --test`, and `handler.test.js` that calls `consumer` with an event of three records, one with a body that is not JSON, and asserts the returned `batchItemFailures` names exactly that record's `messageId`; a second case with three valid records asserts an empty list; a third calls `producer` with no body and expects 400. Then the agent runs `npm test`, `npx eslint .` with the repository's airbnb-base config, and `serverless package` to render the CloudFormation template under `.serverless/`, and reads the rendered `JobsQueue` to confirm the `RedrivePolicy`, the new queue, the event source mapping's `FunctionResponseTypes` and the alarm are in it. It updates the example's `README.md`, keeping the HTML comment frontmatter the repository's `validate.js` checks, and runs `node validate.js` from the root. A deploy needs AWS credentials the sandbox does not have, and the pull request says so.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add a dead-letter queue to the aws-node-sqs-worker service and open a pull request. Read its serverless.yml, handler.js, package.json and README.md, and the repository's package.json, .eslintrc.json and validate.js first. In serverless.yml add JobsDeadLetterQueue as an AWS::SQS::Queue with a fourteen-day MessageRetentionPeriod, give JobsQueue a RedrivePolicy with deadLetterTargetArn pointing at it and maxReceiveCount 3 and a VisibilityTimeout at least six times the consumer's timeout, set functionResponseType: ReportBatchItemFailures on the consumer's sqs event, and add a CloudWatch alarm on the dead-letter queue's ApproximateNumberOfMessagesVisible at one or more, with a comment on where to attach an action. In handler.js move the per-record work into a processJob function that parses the body as JSON and throws otherwise, wrap each record in try/catch, and return batchItemFailures with the itemIdentifier of every record that threw. Add a test script using node --test and handler.test.js covering one bad record out of three, three good records, and the producer's 400. Run npm test, npx eslint . with the repository config, and serverless package, then read the rendered CloudFormation template and confirm the redrive policy, the new queue, the response type and the alarm are present. Update the example README, keeping its frontmatter comment, and run node validate.js from the repository root. Paste every result in the pull request and say that no deploy was made.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `aws-node-sqs-worker/serverless.yml`, `handler.js`, `package.json` and `README.md` and adds `handler.test.js`. Nothing outside that directory changes. The description shows the queue and redrive settings as they appear in the rendered template, lists the three test cases, and says plainly that `serverless package` ran and `serverless deploy` did not.

The run's record keeps `npm test` with each case named, the ESLint run, the `serverless package` output and the lines of the rendered template the agent read back, and the `validate.js` run from the repository root. The repository has no workflow that runs on pull requests, so that record is the check a reviewer reads.

Before merging, a reviewer sets `maxReceiveCount` and the visibility timeout to match how long their real `processJob` takes, decides whether the alarm should fire at one message or a higher threshold, and points its action at their SNS topic. After deploying, they can send a body that is not JSON to `POST /produce` and watch it land in the dead-letter queue after three receives.

## Run it on every queue consumer without a redrive policy

A team with several Serverless services starts one run per service from the terminal: `POST /o/{org}/sessions` with this prompt, the service directory named in `input`, and the repository in `resources`. Each run reads that service's own `serverless.yml` and handler, so a service with two consumers gets a dead-letter queue per source queue, and each run opens its own pull request.

Give the key a `webhook_url` and `run.completed` arrives with `data.session_url` for each, so the pull request links collect in one place. Send a `request_id` with each request so a retried call returns the run it already started.

## Why run it on Rush?

A dead-letter queue is cheap to add and easy to get wrong in ways that only show up under failure: a `maxReceiveCount` of one that dead-letters a message on a single transient error, a visibility timeout shorter than the function's, or a consumer that still fails whole batches so the redrive counts are wrong. In a Rush sandbox the agent writes the consumer with partial batch responses, runs the tests that pin that behaviour, renders the CloudFormation template and reads the redrive policy back from it, and keeps every command and its output in the run's record beside the pull request.

The result is a pull request with the rendered template as evidence rather than a YAML change nobody has packaged. The sandbox needs no AWS credentials for any of it, and the same request works on every queue consumer the team runs.

## Frequently asked questions

### Why ReportBatchItemFailures as well as the dead-letter queue?

Without it, one bad record makes Lambda fail the whole batch of ten and SQS redelivers all ten, so good messages are reprocessed and the receive count of every message climbs together. With partial batch responses only the record that threw is retried, so the redrive policy counts the right thing.

### Will messages already in the queue be affected?

The redrive policy applies to receives after the update, and a message's receive count carries over, so a message that has already failed twice moves to the dead-letter queue on its next failure. The pull request notes this for a stage with a backlog.

### Does the agent deploy to AWS?

No. The sandbox has no AWS credentials, so the proof is `serverless package` and the rendered template, plus the tests. The pull request says exactly that, and the reviewer deploys after merging.

### What about the alarm's action?

The alarm is defined with its metric, dimension and threshold but no `AlarmActions`, because the topic is the reader's. The pull request shows where to add the ARN. An alarm with no action still shows the state in CloudWatch.

## More Serverless Framework jobs

- [Turn On DynamoDB Point-in-Time Recovery in a Serverless Framework Service](https://getrush.ai/run/add-dynamodb-point-in-time-recovery/serverless/)
- [Add a DynamoDB TTL to a Serverless Framework Service](https://getrush.ai/run/add-dynamodb-ttl/serverless/)
- [Add GitHub Actions CI and Deploy for a Serverless Framework Service](https://getrush.ai/run/add-github-actions-ci/serverless/)

## The same job on other stacks

- [Add a Dead Letter Queue to a Lambda in AWS CDK from a Linear Issue](https://getrush.ai/run/add-dlq/aws-cdk/)

## More jobs like this: Hand off a long task

- [Add a Docker Bake File to Build Every Image in a Repository](https://getrush.ai/run/add-docker-bake/docker/)
- [Add a GitHub Actions Workflow That Builds a Docker Image and Pushes It to GHCR](https://getrush.ai/run/add-docker-publish-workflow/docker/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
