Exponential Backoff Retries in Azure Service Bus
When a handler calls AbandonMessageAsync, the message is available again right away. For failures that need time to clear, such as a downstream service that is briefly unavailable, you usually want to wait between attempts instead. This guide shows a simple way to do that with scheduled messages.
The approach
Service Bus has no option to abandon a message with a delay. Abandon releases the lock and increases DeliveryCount, and after MaxDeliveryCount attempts (10 by default) the message is dead-lettered. Deferring a message sets it aside but never redelivers it, and the lock duration is a single fixed delay of at most five minutes.
What Service Bus does have is scheduled messages: a message sent with ScheduledEnqueueTime is not delivered until that time. So on failure you can complete the original message and send a copy scheduled for later. The copy is a new message with a delivery count of one, so you track the attempt number yourself in an application property.
The code
These extensions use C# 14 extension members. The delay grows by a factor of four per attempt, from one second up to about an hour, and after seven retries the message goes to the dead-letter queue with the exception type as the reason.
public static class ServiceBusRetryExtensions
{
private const string RetryCountProperty = "RetryCount";
private const int MaxRetryCount = 7;
extension(ServiceBusReceivedMessage message)
{
public int RetryCount =>
message.ApplicationProperties.TryGetValue(RetryCountProperty, out var value) && value is int count
? count
: 0;
}
extension(ServiceBusReceiver receiver)
{
public async Task RetryLaterOrDeadLetterAsync(
ServiceBusSender sender,
ServiceBusReceivedMessage message,
Exception exception,
ILogger logger,
CancellationToken cancellationToken)
{
var retryCount = message.RetryCount;
if (retryCount >= MaxRetryCount)
{
logger.LogError(exception, "Message {MessageId} failed {RetryCount} times, dead-lettering",
message.MessageId, retryCount);
await receiver.DeadLetterMessageAsync(
message,
$"ProcessingFailed:{exception.GetType().Name}",
$"Message failed {retryCount} times. Error: {exception.Message}",
cancellationToken);
return;
}
// 1s, 4s, 16s, 64s, ~4m, ~17m, ~68m
var delay = TimeSpan.FromSeconds(Math.Pow(4, retryCount));
logger.LogWarning(exception, "Message {MessageId} failed, retry {Attempt} in {Delay}",
message.MessageId, retryCount + 1, delay);
var retryMessage = new ServiceBusMessage(message)
{
// The copy would otherwise keep the original MessageId.
MessageId = $"{message.MessageId}:retry-{retryCount + 1}",
ScheduledEnqueueTime = DateTimeOffset.UtcNow + delay,
};
retryMessage.ApplicationProperties[RetryCountProperty] = retryCount + 1;
// Complete the original and send the copy as one unit.
using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
await receiver.CompleteMessageAsync(message, cancellationToken);
await sender.SendMessageAsync(retryMessage, cancellationToken);
scope.Complete();
}
}
}
When many messages fail at once, their retries become available at roughly the same time, but your receiver still works through them at its normal concurrency. If you run with very high concurrency against a fragile dependency, adding a small random amount to each delay spreads them out further.
Things to know
Give each retry its own MessageId
The ServiceBusMessage(ServiceBusReceivedMessage) constructor copies the original MessageId. If duplicate detection is enabled on the entity, the broker accepts the copy without an error and then discards it as a duplicate. Deriving a new ID from the original, as above, avoids this and keeps retries easy to trace.
Complete and send in one transaction
Without a transaction, a failure between the two calls leaves you with either two copies or none. For example, if the lock expired during processing, the send succeeds but the complete fails, and the original is delivered again. Service Bus supports transactions covering sends and settlements, so the two calls either both happen or neither does.
The scope is not passed to the sender or receiver. TransactionScope sets an ambient transaction, and the Service Bus client checks for it on each operation and enlists automatically, the same way SqlConnection does. TransactionScopeAsyncFlowOption.Enabled is required for the transaction to flow across await; without it the calls silently run outside the transaction.
This only works because the receiver and the sender come from the same ServiceBusClient. A transaction lives on a single AMQP connection, and each client owns one connection that all of its senders and receivers share. With two separate clients the operations travel over different connections, and one transaction cannot cover both. A single ServiceBusClient registered as a singleton, with senders and receivers created from it, is the usual setup and gives you this for free.
Other limits: transactions need the Standard or Premium tier, they time out two minutes after the first operation, and they only cover Service Bus operations, not your database. Scheduled sends work inside a transaction, although Microsoft's documentation does not mention it.
Topics send the retry to every subscription
You cannot send to a subscription, only to its topic, so a retry from one subscription is delivered to every subscription whose filter matches.
The simplest fix is to not consume from the subscription at all. Auto-forward it into a queue and point your consumer at that queue. The retry is then sent back to the queue it came from, so no other subscriber sees it, and because the send and the complete happen on the same entity, no cross-entity transaction is needed.
If you do consume from the subscription directly, you can mark the copy with a property such as RetryFor = "billing" and give each subscription a filter like RetryFor IS NULL OR RetryFor = 'billing'. Sending to the topic while completing on the subscription is a cross-entity transaction, so the client also needs EnableCrossEntityTransactions.
The consumer needs permission to send
Because the retry is a new message sent to the entity the consumer reads from, the consumer needs both send and receive rights on it: the Azure Service Bus Data Sender and Data Receiver roles (or Data Owner), or a shared access policy with both Send and Listen. Consumers set up with least privilege often only have receive rights, and the first retry then fails with an authorization error.
Sessions lose ordering
The copy keeps its SessionId, but the rest of the session continues while the copy waits, so later messages can be processed before the retry. If ordering matters, the receiver has to hold back the session until the retry completes; this post on session hold-backs covers how.
Not every exception should be retried
A validation error will fail the same way on every attempt. Send those straight to the dead-letter queue. Keep MaxDeliveryCount on the entity as well, since it still catches messages that crash the process before your handler runs.
Inspecting retries
Scheduled messages are not delivered to receivers until their time, but a peek shows them. In Bussin they appear alongside active messages with their scheduled time and RetryCount, and you can cancel them. Messages that run out of retries show up in the dead-letter queue with the reason set above; the dead-letter guide covers working through those.
Frequently Asked Questions
Can I abandon a Service Bus message with a delay?
No. Abandon makes the message available again immediately and increases its delivery count. To wait before retrying, complete the original and send a scheduled copy, preferably in one transaction.
Why does my retried message never arrive?
A copy made from the received message keeps the original MessageId. If duplicate detection is enabled on the entity, the broker drops the copy as a duplicate. Give each retry its own MessageId.