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:python3.10Tracing:ActiveEnvironment:Variables:LOG_LEVEL:INFOPOWERTOOLS_SERVICE_NAME:helloResources:HelloWorldFunction:Type:AWS::Serverless::FunctionProperties:Handler:app.lambda_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:python3.10Tracing:ActiveEnvironment:Variables:LOG_LEVEL:INFOPOWERTOOLS_SERVICE_NAME:helloResources:HelloWorldFunction:Type:AWS::Serverless::FunctionProperties:Handler:app.lambda_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 async_process_partial_response 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).
importhttpx# external dependencyfromaws_lambda_powertools.utilities.batchimport(AsyncBatchProcessor,EventType,async_process_partial_response,)fromaws_lambda_powertools.utilities.data_classes.sqs_eventimportSQSRecordfromaws_lambda_powertools.utilities.typingimportLambdaContextprocessor=AsyncBatchProcessor(event_type=EventType.SQS)asyncdefasync_record_handler(record:SQSRecord):# Yield control back to the event loop to schedule other tasks# while you await from a response from httpbin.orgasyncwithhttpx.AsyncClient()asclient:ret=awaitclient.get("https://httpbin.org/get")returnret.status_codedeflambda_handler(event,context:LambdaContext):returnasync_process_partial_response(event=event,record_handler=async_record_handler,processor=processor,context=context)
Using tracer?
AsyncBatchProcessor uses asyncio.gather which can cause side effects and reach trace limits at high concurrency.
You can bring your own Pydantic models via model parameter when inheriting from SqsRecordModel, KinesisDataStreamRecord, or DynamoDBStreamRecordModel
Inheritance is importance because we need to access message IDs and sequence numbers from these records in the event of failure. Mypy is fully integrated with this utility, so it should identify whether you're passing the incorrect Model.
fromaws_lambda_powertoolsimportLogger,Tracerfromaws_lambda_powertools.utilities.batchimport(BatchProcessor,EventType,process_partial_response,)fromaws_lambda_powertools.utilities.parserimportBaseModelfromaws_lambda_powertools.utilities.parser.modelsimportSqsRecordModelfromaws_lambda_powertools.utilities.parser.typesimportJsonfromaws_lambda_powertools.utilities.typingimportLambdaContextclassOrder(BaseModel):item:dictclassOrderSqsRecord(SqsRecordModel):body:Json[Order]# deserialize order data from JSON stringprocessor=BatchProcessor(event_type=EventType.SQS,model=OrderSqsRecord)tracer=Tracer()logger=Logger()@tracer.capture_methoddefrecord_handler(record:OrderSqsRecord):logger.info(record.body.item)returnrecord.body.item@logger.inject_lambda_context@tracer.capture_lambda_handlerdeflambda_handler(event,context:LambdaContext):returnprocess_partial_response(event=event,record_handler=record_handler,processor=processor,context=context)
importjsonfromtypingimportDict,Optionalfromtyping_extensionsimportLiteralfromaws_lambda_powertoolsimportLogger,Tracerfromaws_lambda_powertools.utilities.batchimport(BatchProcessor,EventType,process_partial_response,)fromaws_lambda_powertools.utilities.parserimportBaseModel,validatorfromaws_lambda_powertools.utilities.parser.modelsimport(DynamoDBStreamChangedRecordModel,DynamoDBStreamRecordModel,)fromaws_lambda_powertools.utilities.typingimportLambdaContextclassOrder(BaseModel):item:dictclassOrderDynamoDB(BaseModel):Message:Order# auto transform json string# so Pydantic can auto-initialize nested Order model@validator("Message",pre=True)deftransform_message_to_dict(cls,value:Dict[Literal["S"],str]):returnjson.loads(value["S"])classOrderDynamoDBChangeRecord(DynamoDBStreamChangedRecordModel):NewImage:Optional[OrderDynamoDB]OldImage:Optional[OrderDynamoDB]classOrderDynamoDBRecord(DynamoDBStreamRecordModel):dynamodb:OrderDynamoDBChangeRecordprocessor=BatchProcessor(event_type=EventType.DynamoDBStreams,model=OrderDynamoDBRecord)tracer=Tracer()logger=Logger()@tracer.capture_methoddefrecord_handler(record:OrderDynamoDBRecord):ifrecord.dynamodb.NewImageandrecord.dynamodb.NewImage.Message:logger.info(record.dynamodb.NewImage.Message.item)returnrecord.dynamodb.NewImage.Message.item@logger.inject_lambda_context@tracer.capture_lambda_handlerdeflambda_handler(event,context:LambdaContext):returnprocess_partial_response(event=event,record_handler=record_handler,processor=processor,context=context)
Within your record_handler 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 record_handler if your function signature has a parameter named lambda_context. When using a context manager, you also need to pass the Lambda context object like in the example below.
You can create your own partial batch processor from scratch by inheriting the BasePartialProcessor class, and implementing _prepare(), _clean(), _process_record() and _async_process_record().
_process_record() – handles all processing logic for each individual message of a batch, including calling the record_handler (self.handler)
_prepare() – called once as part of the processor initialization
_clean() – teardown logic called once after _process_record completes
_async_process_record() – 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 batch_processor to use as a decorator on your Lambda handler function.
importosimportsysfromrandomimportrandintfromtypingimportAnyimportboto3fromaws_lambda_powertoolsimportLoggerfromaws_lambda_powertools.utilities.batchimport(BasePartialBatchProcessor,EventType,process_partial_response,)table_name=os.getenv("TABLE_NAME","table_not_found")logger=Logger()classMyPartialProcessor(BasePartialBatchProcessor):""" Process a record and stores successful results at a Amazon DynamoDB Table Parameters ---------- table_name: str DynamoDB table name to write results to """def__init__(self,table_name:str):self.table_name=table_namesuper().__init__(event_type=EventType.SQS)def_prepare(self):# It's called once, *before* processing# Creates table resource and clean previous resultsself.ddb_table=boto3.resource("dynamodb").Table(self.table_name)self.success_messages.clear()def_clean(self):# It's called once, *after* closing processing all records (closing the context manager)# Here we're sending, at once, all successful messages to a ddb tablewithself.ddb_table.batch_writer()asbatch:forresultinself.success_messages:batch.put_item(Item=result)def_process_record(self,record):# It handles how your record is processed# Here we're keeping the status of each run# where self.handler is the record_handler function passed as an argumenttry:result=self.handler(record)# record_handler passed to decorator/context managerreturnself.success_handler(record,result)exceptExceptionasexc:logger.error(exc)returnself.failure_handler(record,sys.exc_info())defsuccess_handler(self,record,result:Any):entry=("success",result,record)self.success_messages.append(record)returnentryasyncdef_async_process_record(self,record:dict):raiseNotImplementedError()processor=MyPartialProcessor(table_name)defrecord_handler(record):returnrandint(0,100)deflambda_handler(event,context):returnprocess_partial_response(event=event,record_handler=record_handler,processor=processor,context=context)
Tracer response auto-capture for large batch sizes¶
When using Tracer to capture responses for each batch record processing, you might exceed 64K of tracing data depending on what you return from your record_handler function, or how big is your batch size.
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.
Use context manager when you want access to the processed messages or handle BatchProcessingError exception when all records within the batch fail to be processed.
What's the difference between the decorator and process_partial_response functions?¶
batch_processor and async_batch_processor decorators are now considered legacy. Historically, they were kept due to backwards compatibility and to minimize code changes between V1 and V2.
As 2.12.0, process_partial_response and async_process_partial_response are the recommended instead. It reduces boilerplate, smaller memory/CPU cycles, and it makes it less error prone - e.g., decorators required an additional return.
fromsentry_sdkimportcapture_exceptionfromaws_lambda_powertools.utilities.batchimportBatchProcessor,FailureResponseclassMyProcessor(BatchProcessor):deffailure_handler(self,record,exception)->FailureResponse:capture_exception()# send exception to Sentryreturnsuper().failure_handler(record,exception)