Currently, when messages are sent to Service Bus, they can only be removed by reading/completing them or waiting for them to age-out based on the retention policy. This can often become troublesome for applications that accumulate messages in their dead-letter queue when they do not wish to process them, or for applications with messages that are not actionable after a certain age.
Historically, developers have had to write code that loops to perform destructive reads for the messages that they want to remove. While this is relatively straightforward for purge scenarios, it can be tricky to do correctly when the desire is only to remove messages older than a given point in time.
To make this scenario easier for developers, Service Bus is adding a new operation capable of deleting batches of messages and limiting them to a specific time.
- Allow developers to purge all messages from a Service Bus entity.
- Allow developers to delete some number of messages from a Service Bus entity, optionally limited by age.
- Provide a discoverable client operation for delete rather than using destructive reads.
Developers have registered consistent feedback since the legacy client libraries were current asking for delete or purge functionality. This request has been around long enough that it is issue #1 in the Azure Service Bus repository, where the service team tracks feature requests.
var connectionString = "<< CONNECTION STRING FOR THE SERVICE BUS NAMESPACE >>";
var entityName = "<< NAME OF THE TARGET ENTITY >>";
await using var client = new ServiceBusClient(connectionString);
await using var receiver = client.CreateReceiver(entityName);
// Purge all messages.
await receiver.DeleteAllMessages();
var connectionString = "<< CONNECTION STRING FOR THE SERVICE BUS NAMESPACE >>";
var entityName = "<< NAME OF THE TARGET ENTITY >>";
await using var client = new ServiceBusClient(connectionString);
await using var receiver = client.CreateReceiver(entityName);
// Delete messages more than a year old.
await receiver.DeleteAllMessages(DateTimeOffset.UtcNow.AddYears(-1));
var connectionString = "<< CONNECTION STRING FOR THE SERVICE BUS NAMESPACE >>";
var entityName = "<< NAME OF THE TARGET ENTITY >>";
await using var client = new ServiceBusClient(connectionString);
await using var receiver = client.CreateReceiver(entityName);
// Delete the 50 oldest messages
await receiver.DeleteAllMessages(50);
var connectionString = "<< CONNECTION STRING FOR THE SERVICE BUS NAMESPACE >>";
var entityName = "<< NAME OF THE TARGET ENTITY >>";
await using var client = new ServiceBusClient(connectionString);
await using var receiver = client.CreateReceiver(entityName);
// Delete the 50 oldest messages that are more than a month old.
await receiver.DeleteAllMessages(50, DateTimeOffset.UtcNow.AddMonths(-1));
What does purge look like without the convenience method?