Search code examples
azure-functionsazureservicebusazure-servicebus-queues

Could I send a message from Dead Letter Queue back to Dead Letter Queue?


I currently have an azure function that processes message from a DLQ of a service bus. What I want to implement is to try to process this manually, but if it doesn't succeed to forward the message back to the DLQ and based on a custom logic to do that for let's say 3 times. I am receiving the ServiceBusReceivedMessage object but when I try to send it back to DLQ either by creating a new ServiceBusClient and receiver either by using the ServiceBusMessageActions I either get a The lock supplied is invalid. Either the lock expired, or the message has already been removed from the queue, or was received by a different receiver instance. (MessageLockLost). or an InvalidException.

Is what I want to do achievable or I should create a new ServiceBusMessage and resubmit the message to the original queue instead of doing it directly to the DLQ?

This is the code that resubmits everything:

try
            {
                var serviceBusClient = new ServiceBusClient(Environment.GetEnvironmentVariable("ConnectionString"), new ServiceBusClientOptions()
                {
                    
                });
                var receiver = serviceBusClient.CreateReceiver(Environment.GetEnvironmentVariable("QueueName"), new ServiceBusReceiverOptions()
                {
                    SubQueue = SubQueue.DeadLetter,
                });
                await receiver.DeadLetterMessageAsync(dlqItem, deadLetterReason: Constants.DLQReason);
                //Above method not working. Bellow neither
                //await messageActions.DeadLetterMessageAsync(dlqItem, deadLetterReason: Constants.DLQReason);

            } catch (Exception ex)
            {
                log.LogError($"MessageId: {dlqItem.MessageId}. There was an error sending the message to DLQ: {ex.Message}");
                throw;
            }

Thanks!


Solution

  • When receiving a message from a dead-letter queue, it's already dead-lettered and doesn't need to be dead-lettered again. As long as you receive the dead-lettered message in a peek-lock mode, the message will remain in the DLQ. If you receive a message in a receive-and-delete mode, it will be gone from the broker and cannot be DLQ-ed.

    You need to be careful not to DDOS yourself here. If a function is configured to receive from a DLQ and cannot handle a message, it will continue receiving that message unless it's completed.