Home > Mobile >  Configuring Lambda to retrieve all the messages in DLQ
Configuring Lambda to retrieve all the messages in DLQ

Time:09-11

I have a lambda configured to a DLQ that may have a few messages in a day. I'm using java for lambda function. My Handler class and method looks something like this:

public class LambdaMethodHandler implements RequestHandler<SQSEvent, String> {

    @Override
    public String handleRequest(SQSEvent event, Context context){

        context.getLogger().log("Started processing messages in DLQ");
        List<String> failedMessages = new ArrayList<>();

        event.getRecords().stream().forEach(message -> {
            context.getLogger().log("Message body: " message.getBody() ", Message sent on: " message.getMessageAttributes().get("timestamp") ", Message ID: " message.getMessageId());
            failedMessages.add(message.getBody());
        });

The idea was to trigger this lambda once a day using EventBridge and if there are multiple messages in the DLQ, it should iterate through them and save it in a file. So I assumed that in SQSEvent the records field is a List so ideally if there are multiple messages in the DLQ then these messages will be passed as List<SQSMessage> records in the SQSEvent. But as I was testing(for now by manually adding messages to the DLQ before configuring the lambda), if there were multiple messages, it would just trigger the lambda multiple time.

Not sure if I've understood the concept incorrectly or is there something wrong with my implementation.

CodePudding user response:

Your lambda is written as though it is subscribed to your SQS queue, which you don't want, since EventBridge will be triggering your lambda directly. You would only use SQSEvent in your handler if the lambda were being triggered by an SQS subscription rather than an EventBridge rule.

To make it run on a schedule:

  1. Unsubscribe your lambda from the SQS queue.

  2. Make your lambda the target of your EventBridge rule.

  3. Update the handler to receive a generic request from EventBridge, i.e.:

    public class LambdaMethodHandler implements RequestHandler<Map<String, Object>, String> {
    
        @Override
        public String handleRequest(Map<String, Object> event, Context context) {
    

    This is required because there's currently no EventBridgeEvent until events v4.

  4. Receive/delete your messages manually. Lambdas that receive SQS messages on a schedule have to manually read messages from the SQS queue and delete them when they're done. In java you would use a ReceiveMessageRequest and then delete it afterward with a DeleteMessageRequest.

  • Related