awsdocs / aws-doc-sdk-examples

Welcome to the AWS Code Examples Repository. This repo contains code examples used in the AWS documentation, AWS SDK Developer Guides, and more. For more information, see the Readme.md file below.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Enhancement]: Java V2 SQS Manual retry example

getmane opened this issue · comments

Background story

Hey, I've recently stumbled into trying to find a way of retrying messages manually, without a built-in retry logic (redrive policy).
My challenge was implementing event source mapping for a Lambda function invoked by a dead-letter queue message.
Why did I need that? I didn't want to configure a new queue only to retry some operation that failed on the main queue but instead utilize the existing dead-letter one.

Here (in the dead-letter queue), unprocessed messages (because of Lambda function error) would be polled (and picked up) indefinitely until the configured retention passes as queues don't have redrive policies to delete the message.

Does the solution exist? Yes, we can utilize the Approximate Receive Count attribute (the same one that SQS uses for redrive policies) to determine if we should delete the message or keep retrying.

By providing an example of manual retry logic, it would be easier for users later on to have the same answer to the question "Is it even possible, and how would I do that?".

I would be glad to contribute such an example to your project.

What does this example accomplish?

The example will show a code snippet of a manual retry logic for an SQS message, allowing users with the same struggles as me to have concrete answers.

Which AWS service(s)?

SQS

Which AWS SDKs or tools?

  • All languages
  • .NET
  • C++
  • Go (v2)
  • Java
  • Java (v2)
  • JavaScript
  • JavaScript (v3)
  • Kotlin
  • PHP
  • Python
  • Ruby
  • Rust
  • Swift
  • Not applicable

Are there existing code examples to leverage?

There are examples of some message attributes, but not for Approximate Receive Count

Do you have any reference code?

// Lambda example (no-error run automatically deletes the message)
String receiveCount = message.getAttributes().get(MessageSystemAttributeName.APPROXIMATE_RECEIVE_COUNT.toString());

try{
// process message
} catch (Exception ex) {
    if (receiveCount > retries) {
        // consume error
    } else {
        throw new Exception();
    }
}