Search code examples
c#.netazureservicebusazure-servicebus-queuesazure-servicebus-topics

I can't retry failed item in Azure Service Bus topic


I have a process that is consuming items from the Azure Service Bus topic. If everything goes well there is no problem but If the process gets an error I need to retry consuming the failed item.

Here is my message handler;

public async Task StartRecieverAsync()
    {
        var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
        {
            MaxConcurrentCalls = 1,
            AutoComplete = false,
            MaxAutoRenewDuration = TimeSpan.FromSeconds(30)
        };

        _creatorSubscription.RegisterMessageHandler(ProcessCreatorMessageAsync, messageHandlerOptions);

        Console.ReadLine();

        await _creatorSubscription.CloseAsync();
    }

    private async Task ProcessCreatorMessageAsync(Message message, CancellationToken token)
    {
        try
        {
            var jsonString = Encoding.UTF8.GetString(message.Body);
            PickingRequest req = JsonSerializer.Deserialize<PickingRequest>(jsonString);

            WorkOrderManager manager = new WorkOrderManager(_sqlManager, _cacheManager, _workOrderFunctions);
            manager.CreatePickingTask(req);

            SendNotification(req.UserRegistrationNumber, NotificationConstants.PickingRequestNotification);

            await _creatorSubscription.CompleteAsync(message.SystemProperties.LockToken);
        }
        catch
        {
            if (message.SystemProperties.DeliveryCount < 5)
            {
                await _creatorSubscription.AbandonAsync(message.SystemProperties.LockToken);
            }
            else
            {
                await _creatorSubscription.DeadLetterAsync(message.SystemProperties.LockToken);
            }
        }
    }

At first 5 times, I would like to try again but it results not change I want to send the item to the dead letter queue. But after the first time, the item goes to the dead letter queue.


Solution

  • How is the topic subscription configured on the service bus? If the max delivery count is 1 then after the first failure the service bus, will move the message to the Dead-letter queue. Service Bus Topic Subscription Properties:

    enter image description here

    • Also it's generally not necessary to manually dead letter a message with a calls DeadLetterAsync, the service bus will do this once the max delivery count is exceeded. i.e your the catch block can be simplified to just await _creatorSubscription.AbandonAsync(message.SystemProperties.LockToken);