This page refers to an unreleased utility that has yet to be published on the npm registry. Any version of the package built from source, as well as all future versions tagged with the -alpha suffix should be treated as experimental. Follow the Beta release milestone for updates on the progress of this utility.
The batch processing utility handles partial failures when processing batches from Amazon SQS, Amazon Kinesis Data Streams, and Amazon DynamoDB Streams.
When using SQS, Kinesis Data Streams, or DynamoDB Streams as a Lambda event source, your Lambda functions are triggered with a batch of messages.
If your function fails to process any message from the batch, the entire batch returns to your queue or stream. This same batch is then retried until either condition happens first: a) your Lambda function returns a successful response, b) record reaches maximum retry attempts, or c) when records expire.
With this utility, batch records are processed individually – only messages that failed to be processed return to the queue or stream for a further retry. This works when two mechanisms are in place:
ReportBatchItemFailures is set in your SQS, Kinesis, or DynamoDB event source properties
A specific response is returned so Lambda knows which records should not be deleted during partial responses
Warning: This utility lowers the chance of processing records more than once; it does not guarantee it
We recommend implementing processing logic in an idempotent manner wherever possible.
You can find more details on how Lambda works with either SQS, Kinesis, or DynamoDB in the AWS Documentation.
Regardless whether you're using SQS, Kinesis Data Streams or DynamoDB Streams, you must configure your Lambda function event source to use ReportBatchItemFailures.
You do not need any additional IAM permissions to use this utility, except for what each event source requires.
The remaining sections of the documentation will rely on these samples. For completeness, this demonstrates IAM permissions and Dead Letter Queue where batch records will be sent after 2 retries were attempted.
AWSTemplateFormatVersion:'2010-09-09'Transform:AWS::Serverless-2016-10-31Description:partial batch response sampleGlobals:Function:Timeout:5MemorySize:256Runtime:nodejs18.xTracing:ActiveEnvironment:Variables:LOG_LEVEL:INFOPOWERTOOLS_SERVICE_NAME:helloResources:HelloWorldFunction:Type:AWS::Serverless::FunctionProperties:Handler:index.handlerCodeUri:hello_worldPolicies:# Lambda Destinations require additional permissions# to send failure records to DLQ from Kinesis/DynamoDB-Version:'2012-10-17'Statement:Effect:'Allow'Action:-sqs:GetQueueAttributes-sqs:GetQueueUrl-sqs:SendMessageResource:!GetAttSampleDLQ.ArnEvents:KinesisStream:Type:KinesisProperties:Stream:!GetAttSampleStream.ArnBatchSize:100StartingPosition:LATESTMaximumRetryAttempts:2DestinationConfig:OnFailure:Destination:!GetAttSampleDLQ.ArnFunctionResponseTypes:-ReportBatchItemFailuresSampleDLQ:Type:AWS::SQS::QueueSampleStream:Type:AWS::Kinesis::StreamProperties:ShardCount:1StreamEncryption:EncryptionType:KMSKeyId:alias/aws/kinesis
AWSTemplateFormatVersion:'2010-09-09'Transform:AWS::Serverless-2016-10-31Description:partial batch response sampleGlobals:Function:Timeout:5MemorySize:256Runtime:nodejs18.xTracing:ActiveEnvironment:Variables:LOG_LEVEL:INFOPOWERTOOLS_SERVICE_NAME:helloResources:HelloWorldFunction:Type:AWS::Serverless::FunctionProperties:Handler:index.handlerCodeUri:hello_worldPolicies:# Lambda Destinations require additional permissions# to send failure records from Kinesis/DynamoDB-Version:'2012-10-17'Statement:Effect:'Allow'Action:-sqs:GetQueueAttributes-sqs:GetQueueUrl-sqs:SendMessageResource:!GetAttSampleDLQ.ArnEvents:DynamoDBStream:Type:DynamoDBProperties:Stream:!GetAttSampleTable.StreamArnStartingPosition:LATESTMaximumRetryAttempts:2DestinationConfig:OnFailure:Destination:!GetAttSampleDLQ.ArnFunctionResponseTypes:-ReportBatchItemFailuresSampleDLQ:Type:AWS::SQS::QueueSampleTable:Type:AWS::DynamoDB::TableProperties:BillingMode:PAY_PER_REQUESTAttributeDefinitions:-AttributeName:pkAttributeType:S-AttributeName:skAttributeType:SKeySchema:-AttributeName:pkKeyType:HASH-AttributeName:skKeyType:RANGESSESpecification:SSEEnabled:trueStreamSpecification:StreamViewType:NEW_AND_OLD_IMAGES
When using SQS FIFO queues, we will stop processing messages after the first failure, and return all failed and unprocessed messages in batchItemFailures.
This helps preserve the ordering of messages in your queue.
All records in the batch will be passed to this handler for processing, even if exceptions are thrown - Here's the behaviour after completing the batch:
All records successfully processed. We will return an empty list of item failures {'batchItemFailures': []}
Partial success with some exceptions. We will return a list of all item IDs/sequence numbers that failed processing
All records failed to be processed. We will raise BatchProcessingError exception with a list of all exceptions raised when processing
You can use AsyncBatchProcessor class and asyncProcessPartialResponse function to process messages concurrently.
When is this useful?
Your use case might be able to process multiple records at the same time without conflicting with one another.
For example, imagine you need to process multiple loyalty points and incrementally save in a database. While you await the database to confirm your records are saved, you could start processing another request concurrently.
The reason this is not the default behaviour is that not all use cases can handle concurrency safely (e.g., loyalty points must be updated in order).
import{AsyncBatchProcessor,EventType,asyncProcessPartialResponse,}from'@aws-lambda-powertools/batch';importaxiosfrom'axios';// axios is an external dependencyimporttype{SQSEvent,SQSRecord,Context,SQSBatchResponse,}from'aws-lambda';constprocessor=newAsyncBatchProcessor(EventType.SQS);constrecordHandler=async(record:SQSRecord):Promise<number>=>{constres=awaitaxios.post('https://httpbin.org/anything',{message:record.body,});returnres.status;};exportconsthandler=async(event:SQSEvent,context:Context):Promise<SQSBatchResponse>=>{returnawaitasyncProcessPartialResponse(event,recordHandler,processor,{context,});};
Within your recordHandler function, you might need access to the Lambda context to determine how much time you have left before your function times out.
We can automatically inject the Lambda context into your recordHandler as optional second argument if you register it when using BatchProcessor or the processPartialResponse function.
You can create your own partial batch processor from scratch by inheriting the BasePartialProcessor class, and implementing the prepare(), clean(), processRecord() and asyncProcessRecord() abstract methods.
processRecord() – handles all processing logic for each individual message of a batch, including calling the recordHandler (this.handler)
prepare() – called once as part of the processor initialization
clean() – teardown logic called once after processRecord completes
asyncProcessRecord() – If you need to implement asynchronous logic, use this method, otherwise define it in your class with empty logic
You can then use this class as a context manager, or pass it to processPartialResponse to process the records in your Lambda handler function.
import{randomInt}from'node:crypto';import{DynamoDBClient,BatchWriteItemCommand,}from'@aws-sdk/client-dynamodb';import{marshall}from'@aws-sdk/util-dynamodb';import{BasePartialProcessor,processPartialResponse,}from'@aws-lambda-powertools/batch';importtype{SuccessResponse,FailureResponse,EventSourceType,}from'@aws-lambda-powertools/batch';importtype{SQSEvent,Context,SQSBatchResponse}from'aws-lambda';consttableName=process.env.TABLE_NAME||'table-not-found';classMyPartialProcessorextendsBasePartialProcessor{#tableName:string;#client?:DynamoDBClient;publicconstructor(tableName:string){super();this.#tableName=tableName;}publicasyncasyncProcessRecord(_record:EventSourceType):Promise<SuccessResponse|FailureResponse>{thrownewError('Not implemented');}/** * It's called once, **after** processing the batch. * * Here we are writing all the processed messages to DynamoDB. */publicclean():void{// We know that the client is defined because clean() is called after prepare()// eslint-disable-next-line @typescript-eslint/no-non-null-assertionthis.#client!.send(newBatchWriteItemCommand({RequestItems:{[this.#tableName]:this.successMessages.map((message)=>({PutRequest:{Item:marshall(message),},})),},}));}/** * It's called once, **before** processing the batch. * * It initializes a new client and cleans up any existing data. */publicprepare():void{this.#client=newDynamoDBClient({});this.successMessages=[];}/** * It handles how your record is processed. * * Here we are keeping the status of each run, `this.handler` is * the function that is passed when calling `processor.register()`. */publicprocessRecord(record:EventSourceType):SuccessResponse|FailureResponse{try{constresult=this.handler(record);returnthis.successHandler(record,result);}catch(error){returnthis.failureHandler(record,errorasError);}}}constprocessor=newMyPartialProcessor(tableName);constrecordHandler=():number=>{returnMath.floor(randomInt(1,10));};exportconsthandler=async(event:SQSEvent,context:Context):Promise<SQSBatchResponse>=>{returnprocessPartialResponse(event,recordHandler,processor,{context,});};
As there is no external calls, you can unit test your code with BatchProcessor quite easily.
Example:
Given a SQS batch where the first batch record succeeds and the second fails processing, we should have a single item reported in the function response.