[{"data":1,"prerenderedAt":58},["ShallowReactive",2],{"snippet-integration-sqs-to-lambda-with-batch-item-handling":3},{"id":4,"title":5,"contributors":6,"description":8,"extension":9,"gitHub":10,"introBox":13,"languages":17,"meta":21,"resources":22,"services":26,"snippets":29,"stem":54,"tags":55,"type":56,"__hash__":57},"snippets\u002Fsnippets\u002Fintegration-sqs-to-lambda-with-batch-item-handling.json","Amazon SQS trigger to invoke a Lambda function",[7],"content\u002Fcontributors\u002Fmohammed-tomeh.json","Using an Amazon SQS trigger to invoke a Lambda function","json",{"template":11},{"repoURL":12},"https:\u002F\u002Fgithub.com\u002Faws-samples\u002Fserverless-snippets\u002Ftree\u002Fmain\u002Fintegration-sqs-to-lambda-with-batch-item-handling",{"headline":14,"text":15},"How it works",[16],"The Lambda function retrieves a batch of SQS messages from the event parameter that it receives. The function logs the content of each message. When an exception occurs for one or more of the received messages, the handler returns SQSBatchResponse that contains batchItemFailure for failed messages that can be used for message reprocessing or move failed messages to DLQ",[18,19,20],"Node.js","TypeScript",".NET",{},{"bullets":23},[24],{"text":8,"link":25},"https:\u002F\u002Fdocs.aws.amazon.com\u002Flambda\u002Flatest\u002Fdg\u002Fwith-sqs.html",[27,28],"lambda-event-functions","sqs",[30],{"title":31,"codeTabs":32},"Runtimes",[33,40,47],{"id":18,"title":34,"description":35,"snippets":36},"Usage Example with Node:","Consuming an SQS event with Lambda using JavaScript with batch item handling.",[37],{"language":38,"code":39},"js","exports.handler = async (event, context) =&#62; {\n    const batchItemFailures = [];\n    if (event.Records.length == 0){\n        console.log('Empty SQS Event received');\n        return { batchItemFailures };\n    }\n    for(const message of event.Records){\n        const result = await processMessageAsync(message);\n        if(result !== null){\n            batchItemFailures.push(result);\n        }\n    }\n    return { batchItemFailures };\n};\n\nasync function processMessageAsync(message) {\n    try {\n            console.log(`Processed message ${message.body}`);\n            \u002F\u002F TODO: Do interesting work based on the new message\n            await Promise.resolve(1); \u002F\u002FPlaceholder for actual async work\n            return null;\n        } catch (err) {\n            console.error(`An error occurred while processing ${message} - Error: ${err.message}`);\n            return { itemIdentifier: message.messageId };\n        }\n    }",{"id":19,"title":41,"description":42,"snippets":43},"Usage Example with TypeScript:","Consuming an SQS event with Lambda using TypeScript with batch item handling.",[44],{"language":45,"code":46},"ts","import { SQSEvent, Context, SQSHandler, SQSBatchResponse, SQSBatchItemFailure, SQSRecord } from 'aws-lambda';\n\nexport const functionHandler : SQSHandler = async (event: SQSEvent, context: Context) : Promise&#60;SQSBatchResponse&#62; =&#62; {\n    const batchItemFailures : SQSBatchItemFailure[] = [];\n    if (event.Records.length == 0){\n        console.log('Empty SQS Event received');\n        return { batchItemFailures };\n    }\n\n    for(const message of event.Records){\n        const result = await processMessageAsync(message);\n        if(result !== null){\n            batchItemFailures.push(result);\n        }\n    }\n    return { batchItemFailures };\n};\n\nasync function processMessageAsync(message: SQSRecord) : Promise&#60;SQSBatchItemFailure | null&#62; {\n    try {\n            console.log(`Processed message ${message.body}`);\n            \u002F\u002F TODO: Do interesting work based on the new message\n            await Promise.resolve(1); \u002F\u002FPlaceholder for actual async work\n            return null;\n        } catch (err) {\n            console.error(`An error occurred while processing ${message} - Error: ${err.message}`);\n            return { itemIdentifier: message.messageId };\n        }\n    }",{"id":20,"title":48,"description":49,"snippets":50},"Usage Example with .NET:","Consuming an SQS event with Lambda using .NET with batch item handling.",[51],{"language":52,"code":53},"dotnet","using Amazon.Lambda.Core;\nusing Amazon.Lambda.SQSEvents;\nusing static Amazon.Lambda.SQSEvents.SQSBatchResponse;\n\n\n\u002F\u002F Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.\n[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]\n\nnamespace SqsIntegration;\n\npublic class Function\n{\n    public async Task&#60;SQSBatchResponse&#62; FunctionHandler(SQSEvent evnt, ILambdaContext context)\n    {\n\n        List&#60;BatchItemFailure&#62; _batchItemFailures = new();\n\n        if (evnt.Records.Count == 0)\n        {\n            context.Logger.LogLine(\"Empty SQS Event received\");\n            return new SQSBatchResponse();\n        }\n\n        foreach (var message in evnt.Records)\n        {\n            BatchItemFailure? result = await ProcessMessageAsync(message, context);\n            if (result != null)\n            {\n                _batchItemFailures.Add(result);\n            }\n        }\n\n        return new SQSBatchResponse(_batchItemFailures);\n    }\n\n    private async Task&#60;BatchItemFailure?&#62; ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context)\n    {\n        try\n        {\n            context.Logger.LogInformation($\"Processed message {message.Body}\");\n            \u002F\u002F TODO: Do interesting work based on the new message\n            await Task.CompletedTask; \u002F\u002F Placeholder for actual async work\n            return null;\n\n        }\n        catch (Exception e)\n        {\n            context.Logger.LogError($\"An error occurred - {e.Message}\");\n            return new BatchItemFailure { ItemIdentifier = message.MessageId };\n        }\n    }\n}","snippets\u002Fintegration-sqs-to-lambda-with-batch-item-handling",[],"Integration","BmfRIapv-_c4W6LTiWod75wRW03GbWo8WkVNXBONXI8",1792578864340]