'What is the best way to handle @SqsListener processing failure in Spring Boot?

We have implemented sqslistner as the documentation suggests, the best way to receive AWS SQS message Cloud Spring Doc.

There are two ways for receiving SQS messages, either use the receive methods of the QueueMessagingTemplate or with annotation-driven listener endpoints. The latter is by far the more convenient way to receive messages.

Everything is working as expected. If business process failed, we throw a runtime exception. The particular message is sent back to the SQS queue for retry. When visibility timeout passed the message reappears to the worker for processing.

Sample Code is here:

    @SqsListener(value="sample-standard-queue",deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS)
public void receiveMessage(String message) {
    log.info("Message Received **************************** "+message );
    log.info("After Conversion"+new JSONObject(message).getString("payload"));
    throw new RuntimeException("An exception was thrown during the execution of the SQS listener method and Message will be still available in Queue");
}

But there are some examples where "Acknowledgment" is used instead of throwing run time exception. Documentation doesn't suggest that.

Which one is the best way to deal with a business logic failure scenario?Is Acknowledgment necessary?

Thanks in advance.



Solution 1:[1]

One way is to keep a track of messages being processed in some RDS table. If any message gets retried then increase the retry count in the table for that particular message.

There should be some configured numbers of retries that you want to retry one particular message and then you may want to move that to a dead-letter-queue or you may log it and just simply discard it.

There can be multiple ways of handling it: One way can be:

@SqsListener(value="sample-standard-queue",deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS)
public void receiveMessage(String message) {
    try{
       log.info("Message Received **************************** "+message );
       log.info("After Conversion"+new JSONObject(message).getString("payload"));
    }catch(Exception e){
       // check if its retry count has exhausted or not
       // if exhausted - then acknowledge it (push it into dead-letter-queue) and dont throw the exception
       // If not exhausted - increase the retry count in the table before throwing exception
       throw new RuntimeException("An exception was thrown during the execution of the SQS listener method and Message will be still available in Queue");
    }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vaibhav Sharma