Amazon SQS partial batch response Lambda function

This snippet demonstrates how to handle an SQS event and implement a partial batch response in a lambda function.

The Lambda function retrieves a source SQS event which may contain messages that cannot be processed. As exceptions are caught processing messages, a list of itemIdentifiers is collected. The collection is returned as batchItemFailures, a JSON serialized list of itemIdentifiers. This sample assumes ReportBatchItemFailures is activated on your lambda function.

Select language:

Usage Example with Java:

Implementing partial SQS batch responses using Java.

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.SQSEvent;
import com.amazonaws.services.lambda.runtime.events.SQSBatchResponse;
 
import java.util.ArrayList;
import java.util.List;
 
public class ProcessSQSMessageBatch implements RequestHandler<SQSEvent, SQSBatchResponse> {
    @Override
    public SQSBatchResponse handleRequest(SQSEvent sqsEvent, Context context) {
 
         List<SQSBatchResponse.BatchItemFailure> batchItemFailures = new ArrayList<SQSBatchResponse.BatchItemFailure>();
         String messageId = "";
         for (SQSEvent.SQSMessage message : sqsEvent.getRecords()) {
             try {
                 //process your message
                 messageId = message.getMessageId();
             } catch (Exception e) {
                 //Add failed message identifier to the batchItemFailures list
                 batchItemFailures.add(new SQSBatchResponse.BatchItemFailure(messageId));
             }
         }
         return new SQSBatchResponse(batchItemFailures);
     }
}
                                                      



Created by:

Victor Feinman

Victor Feinman

Sr. Solutions Architect at AWS

Follow on LinkedIn

Charles Ede

Charles Ede

Sr. Engineer at LEGO

Sangeetha Kamatkar

Sangeetha Kamatkar

Solutions Architect at AWS

Follow on LinkedIn