AWS Builder Center
One bad SQS message should not replay the whole Lambda batch

One bad SQS message should not replay the whole Lambda batch

Wire SQS to Lambda in CDK with a dead-letter queue, a safe visibility timeout and partial batch responses, so one bad message doesn't replay the whole batch.

Estudiante de ingeniería de software | DevOps
A Lambda function that reads from SQS receives messages in batches. If the function throws, the whole batch goes back to the queue, including the messages that were processed without trouble. The Lambda documentation states this directly: by default, all messages in a failed batch become visible again.
With a batch size of 10 and one malformed message, nine good messages get processed again on every retry. If those messages have side effects, that is how duplicate emails and double writes happen.
Three settings keep this under control: partial batch responses, a visibility timeout sized against the function timeout, and a dead-letter queue on the source queue. In CDK they are a few lines each, and each has a detail that is easy to miss.

The stack

This is a plain JavaScript CDK app with one queue, one dead-letter queue and one function. The comments point at the parts that matter.
const { App, Stack, Duration } = require('aws-cdk-lib');
const sqs = require('aws-cdk-lib/aws-sqs');
const lambda = require('aws-cdk-lib/aws-lambda');
const { SqsEventSource } = require('aws-cdk-lib/aws-lambda-event-sources');

class OrdersStack extends Stack {
constructor(scope, id) {
super(scope, id);

const fnTimeout = Duration.seconds(30);
const batchWindow = Duration.seconds(5);

const dlq = new sqs.Queue(this, 'OrdersDlq', {
retentionPeriod: Duration.days(14),
});

const queue = new sqs.Queue(this, 'OrdersQueue', {
// six times the function timeout, plus the batching window
visibilityTimeout: Duration.seconds(
fnTimeout.toSeconds() * 6 + batchWindow.toSeconds()
),
deadLetterQueue: { queue: dlq, maxReceiveCount: 5 },
});

const fn = new lambda.Function(this, 'OrdersWorker', {
runtime: lambda.Runtime.NODEJS_20_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('handler'),
timeout: fnTimeout,
});

fn.addEventSource(new SqsEventSource(queue, {
batchSize: 10,
maxBatchingWindow: batchWindow,
reportBatchItemFailures: true,
}));
}
}

const app = new App();
new OrdersStack(app, 'OrdersStack');

Size the visibility timeout from the function timeout

The docs recommend a source queue visibility timeout of at least six times the function timeout. The extra room lets Lambda retry if the function is throttled while it is still working through a previous batch. When a batching window is set, the recommendation adds MaximumBatchingWindowInSeconds on top. In the stack above that is 30 x 6 + 5 = 185 seconds.
There is also a hard rule. The function timeout must be less than or equal to the queue's visibility timeout, and Lambda checks this when the event source mapping is created or updated. If the function timeout is larger, the mapping call returns an error.
Deriving one number from the other in code, as the stack does, means a later change to the function timeout moves the queue setting with it.

The dead-letter queue belongs to the source queue

For an SQS event source, the dead-letter queue is configured through the source queue's redrive policy. In CDK that means the deadLetterQueue property on the source queue, not anything on the function.
The docs recommend a maxReceiveCount of at least 5. A value of 1 sends a message to the dead-letter queue after a single failed receive, which leaves Lambda no room to retry, for example after a throttled invocation. Five gives a few attempts before a message is parked.

Report only the messages that failed

Setting reportBatchItemFailures to true adds ReportBatchItemFailures to the mapping's FunctionResponseTypes. After that, the function can return the IDs of the messages that failed, and only those go back to the queue.
exports.handler = async (event) => {
const batchItemFailures = [];

for (const record of event.Records) {
try {
JSON.parse(record.body); // stand-in for real work
} catch (err) {
batchItemFailures.push({ itemIdentifier: record.messageId });
}
}

return { batchItemFailures };
};
The response format is a batchItemFailures list of objects with an itemIdentifier, which is the message ID. An empty list tells Lambda the whole batch succeeded.
A few cases count as a complete batch failure instead: the function throws an exception, the response is not valid JSON, an itemIdentifier is empty or null, the key name is wrong, or the identifier does not match a message in the batch. A typo in a key name is enough to make the feature silently do nothing useful, because every message returns to the queue again. The docs suggest watching the NumberOfMessagesDeleted metric for this; if it drops to zero, the responses are probably malformed.
FIFO queues need extra care. The function should stop at the first failure and return that message plus every message it did not get to, so ordering is preserved.

What was checked

Running cdk synth on the stack above produces a queue with VisibilityTimeout 185, a RedrivePolicy with maxReceiveCount 5, a 14-day retention period on the dead-letter queue, and an event source mapping with BatchSize 10, MaximumBatchingWindowInSeconds 5 and FunctionResponseTypes set to ReportBatchItemFailures. The stack was not deployed, so the handler behavior described here comes from the AWS documentation and not from a live test.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article