Service Bus MessageLockLost exception after manually completing message

Viewed 193

I have a Service Bus triggered method in an Azure WebJob that runs and awaits a very long running task. Because the triggered method may run for more than 5 minutes (maximum service bus lock time), I'm hoping to manually complete the message before starting the long running task. I'm able to do so, but am later seeing a MessageLockLost exception be logged to app insights. This happens both when running an app service or when testing locally.

I assume the message is being completed twice, because I see similar behavior if I attempt to manually complete the message twice. Why would this be happening though, since I specified AutoCompleteMessages = false in the ServiceBusTriggerAnnotation (see code snippet below)?

The code I'm running is something like:

public async Task StartLongRunningTask(
            [ServiceBusTrigger("topic-name", "subscription-name", AutoCompleteMessages = false)] ServiceBusReceivedMessage request,
            ServiceBusMessageActions messageActions,
            ILogger log)
{
  // ... Do some setup ...

  try
  {
    // Complete the message
    await messageActions.CompleteMessageAsync(request);
  }
  catch (ServiceBusException e)
  {
    log.LogWarning(e, "Failed to complete service bus message for request");
    return;
  }

  // ... Await a long running task...
}

This seems happy enough, and I'm never seeing a ServiceBusException be caught here. However, I'll later see an exception logged to app insights that reads something like:

Azure.Messaging.ServiceBus.ServiceBusException: 'The lock supplied is invalid. Either the lock expired, or the message has already been removed from the queue. For more information please see https://aka.ms/ServiceBusExceptions [...] (MessageLockLost)'

Thanks in advance!

0 Answers
Related