Azure Service Bus Function fails with "The lock supplied is invalid. Either the lock expired, or the message has already been removed from the queue."

Pavel Kusonski 0 Reputation points
2025-03-07T22:41:11.5966667+00:00

Hi.

Azure Service Bus Function (CompleteMessageAsync) Exception: "The lock supplied is invalid. Either the lock expired, or the message has already been removed from the queue."

Microsoft.Azure.Functions.Worker.Extensions.ServiceBus 5.22.0

Attr: [ServiceBusTrigger("%QueueName%", Connection = "ConnectionString", AutoCompleteMessages = false)]

Host.json:
"extensions": {
"serviceBus": {
"autoCompleteMessages": false,
"maxConcurrentCalls": 500
}}

Message lock duration: 5 minutes
Execution time of the failed function: 15 sec

The exception appears after handling 3-6 K messages (1K/6 min).
(sending ~ 1K or more to bus using a batched approach)

Also ... I found that performance fully degradaiting after an hour (some task execution > 5 min)

Could you help me, please?

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,524 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Shireesha Eeraboina 1,980 Reputation points Microsoft External Staff
    2025-03-10T06:28:29.3566667+00:00

    Hi @Pavel Kusonski ,

    The error happens because message locks expire before processing is finished, even with a 15-second runtime, due to high concurrency or prefetching.

    • Increase maxAutoRenewDuration: Change this setting in host.json to extend the lock renewal time (up to 5 minutes):
    "extensions": {
      "serviceBus": {
        "maxAutoRenewDuration": "00:05:00",
        "maxConcurrentCalls": 100  // Lower this if necessary
      }
    }
    
    
    • Set prefetchCount to 0 in host.json to prevent cached messages from losing their locks.
    • Use RenewMessageLockAsync for messages that take a long time to process and add retry logic.

    For more details, please refer to these documents:

    Azure Service Bus message lock troubleshooting and Troubleshoot Azure Service Bus.

    If you find the answer helpful, kindly click "Accept Answer" and upvote it. If you have any further questions or concerns, please feel free to reach out to us. We are happy to assist you.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.