Search code examples
c#.netamazon-sqs

Singleton AmazonSQSClient to receive messages concurrenlty and ReceiptHandle issue


AmazonSQSClient is advertised as thread-safe, but if I am going to use it to received messages concurrently, then how do I delete a message after it is successfully processed?

I understand from docs that ReceiptHandle used to delete messages will change after each request, and that I will have to use the last ReceiptHandle to delete a message.

I conclude from that that AmazonSQSClient shouldn't be used as singleton, and an instance should only handle messages squentially: receive, process, delete.

Am I missing something?


Solution

  • Okay, the idea is that receipt handle is actually associated with message, so you can always retrieve multiple messages before deleting the one you want.

    However, if you receive the same message again, receipt handle will be different, and you should use the last one you got for the same message.

    The idea here is that you shouldn't really persist ReceiptHandle or treat it as absolute id to point to message (say in DB), because:

    1. You might fail processing the message, and thus it becomes visible to other consumers (or your instance) after visibility timeout reached.

    2. Only the consumer who is currently processing the message can delete it.

    The ReceiptHandle is associated with a specific instance of receiving a message. If you receive a message more than once, the ReceiptHandle is different each time you receive a message. When you use the DeleteMessage action, you must provide the most recently received ReceiptHandle for the message (otherwise, the request succeeds, but the message will not be deleted).

    https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_DeleteMessage.html