+1 (726) 207-9872

SQS and Lambda Failure Handling: Partial Batch Responses, DLQs, and Redrive with Serverless Framework V4

One poisoned message can make a healthy SQS-backed Lambda look broken. By default, if your handler throws on one record in a batch of ten, the whole batch returns to the queue, the nine good messages are processed again, and the bad one keeps coming back until it hits the redrive limit. This tutorial covers the failure-handling setup we use on SQS-triggered functions with Serverless Framework V4: partial batch responses, a dead-letter queue with sensible retry settings, controlled concurrency, and a redrive workflow. It complements our post on EventBridge, SQS, and idempotency; here the focus is what happens when messages fail.

The failure model in one paragraph

Lambda polls SQS through an event source mapping and hands your function a batch. If the invocation succeeds, Lambda deletes the whole batch. If it throws, none of the batch is deleted. Each message becomes visible again after the queue's visibility timeout, and its receive count goes up. Once the receive count passes maxReceiveCount, SQS moves the message to the dead-letter queue (DLQ). Three settings must agree with each other: the function timeout, the queue visibility timeout, and maxReceiveCount.

Step 1: Queues and the DLQ

service: order-processor
frameworkVersion: '4'

provider:
  name: aws
  runtime: nodejs22.x
  architecture: arm64
  environment:
    QUEUE_URL: !Ref OrdersQueue

functions:
  processOrders:
    handler: src/processOrders.handler
    timeout: 30
    events:
      - sqs:
          arn: !GetAtt OrdersQueue.Arn
          batchSize: 10
          maximumBatchingWindow: 5
          maximumConcurrency: 10
          functionResponseType: ReportBatchItemFailures

resources:
  Resources:
    OrdersQueue:
      Type: AWS::SQS::Queue
      Properties:
        VisibilityTimeout: 180
        RedrivePolicy:
          deadLetterTargetArn: !GetAtt OrdersDLQ.Arn
          maxReceiveCount: 5
    OrdersDLQ:
      Type: AWS::SQS::Queue
      Properties:
        MessageRetentionPeriod: 1209600

Notes on these values:

  • VisibilityTimeout: 180 is six times the 30-second function timeout. AWS recommends at least six times, which leaves room for retries and batching-window delay. A visibility timeout shorter than the function timeout causes duplicate processing.
  • MessageRetentionPeriod on the DLQ is 14 days. Messages moved to a DLQ keep their original enqueue timestamp, so a short retention can expire them almost immediately. Always give the DLQ the maximum.
  • maxReceiveCount: 5 gives transient errors a few chances without letting a bad message loop for hours.
  • maximumConcurrency: 10 caps how many concurrent invocations this queue can drive. This protects downstream databases and stops one noisy queue from consuming the account's concurrency. The minimum allowed value is 2.

Step 2: Return partial batch failures

ReportBatchItemFailures lets the handler tell Lambda which messages failed. Only those return to the queue.

import type { SQSEvent, SQSBatchResponse } from 'aws-lambda';

export const handler = async (event: SQSEvent): Promise<SQSBatchResponse> => {
  const batchItemFailures: { itemIdentifier: string }[] = [];

  for (const record of event.Records) {
    try {
      const order = JSON.parse(record.body);
      await processOrder(order);
    } catch (err) {
      console.error(JSON.stringify({
        msg: 'record failed',
        messageId: record.messageId,
        error: (err as Error).message,
      }));
      batchItemFailures.push({ itemIdentifier: record.messageId });
    }
  }

  return { batchItemFailures };
};

Two pitfalls:

  1. Do not throw out of the handler once you are using partial responses. A thrown error fails the whole batch. Catch per record.
  2. Never return a malformed response. An unrecognised or null itemIdentifier is treated as a failure of the entire batch. Return { batchItemFailures: [] } on full success.

For FIFO queues, stop at the first failure and report that message plus every message after it in the batch, so ordering within a message group is preserved.

Because failed messages are retried, and in rare cases successful ones are delivered twice, the processing step must be idempotent. See our idempotency post for the pattern.

Step 3: Separate poison messages from transient failures

Not all errors deserve five retries. A message with invalid JSON will fail identically every time. Consider classifying errors:

  • Permanent (validation errors, unknown schema version): log with the message ID and send directly to the DLQ using SendMessage, then treat the record as handled. This avoids burning five invocations.
  • Transient (timeouts, throttling, a downstream 503): add to batchItemFailures and let the queue retry.

Direct-to-DLQ sends need sqs:SendMessage on the DLQ, so grant that explicitly:

provider:
  iam:
    role:
      statements:
        - Effect: Allow
          Action: sqs:SendMessage
          Resource: !GetAtt OrdersDLQ.Arn

Step 4: Alarm on the DLQ

A DLQ nobody watches is just a slower way to lose data. Alarm on any visible message:

resources:
  Resources:
    DLQAlarm:
      Type: AWS::CloudWatch::Alarm
      Properties:
        AlarmName: ${self:service}-${sls:stage}-dlq-not-empty
        Namespace: AWS/SQS
        MetricName: ApproximateNumberOfMessagesVisible
        Dimensions:
          - Name: QueueName
            Value: !GetAtt OrdersDLQ.QueueName
        Statistic: Maximum
        Period: 60
        EvaluationPeriods: 1
        Threshold: 0
        ComparisonOperator: GreaterThanThreshold
        TreatMissingData: notBreaching
        AlarmActions:
          - !Ref AlertsTopic
    AlertsTopic:
      Type: AWS::SNS::Topic

Subscribe your on-call channel to the topic. Also consider alarming on ApproximateAgeOfOldestMessage on the main queue, which catches a stuck consumer even when nothing reaches the DLQ.

Step 5: Fix the bug, then redrive

Once the root cause is deployed, move messages back to the source queue. The SQS console has a "Start DMS (dead-letter queue redrive)" action, and the CLI equivalent is:

aws sqs start-message-move-task \
  --source-arn arn:aws:sqs:us-east-1:123456789012:order-processor-dev-OrdersDLQ \
  --max-number-of-messages-per-second 20

Set a rate limit so a large backlog does not flood the consumer. Check progress with aws sqs list-message-move-tasks --source-arn <dlq-arn>. Before redriving, inspect a few messages to confirm they will now succeed. Otherwise they will cycle back to the DLQ.

Step 6: Test the failure path

Add a unit test that feeds a mixed batch to the handler and asserts the exact response:

it('reports only the bad record', async () => {
  const event = { Records: [
    { messageId: 'a', body: '{"id":1}' },
    { messageId: 'b', body: 'not json' },
    { messageId: 'c', body: '{"id":3}' },
  ] } as any;
  const res = await handler(event);
  expect(res.batchItemFailures).toEqual([{ itemIdentifier: 'b' }]);
});

In an ephemeral stage, send one bad message and confirm that it reaches the DLQ after five receives and that the alarm fires.

Checklist

  • functionResponseType: ReportBatchItemFailures set and the handler never throws.
  • Visibility timeout is at least 6x the function timeout.
  • DLQ retention is 14 days and the DLQ is alarmed.
  • maximumConcurrency is set to protect downstream systems.
  • Permanent errors are separated from transient ones.
  • A redrive runbook exists and has been rehearsed.

If your queues are already in production and you want a review of retry, concurrency, and DLQ settings, our team does this as part of serverless architecture and performance engagements. Get in touch via the contact page.