In the previous article, Azure Service Bus Messages – Structure, Properties and Types, we explored the fundamentals of Azure Service Bus messages, including message structure, message body, system properties, application properties, message types, and payload size considerations.
Understanding the structure of a message is the first step in working with Azure Service Bus. However, in real-world applications, it is equally important to understand how messages are received, filtered, processed, and managed throughout their lifecycle.
In this article, we will focus on how applications interact with Azure Service Bus messages. We will explore message receive modes such as PeekLock and ReceiveAndDelete, subscription filters for controlling message delivery, and various message operations such as sending, receiving, completing, abandoning, deferring, scheduling, and dead-lettering messages.
By the end of this article, you will have a better understanding of how Azure Service Bus manages message delivery and how to implement reliable message-processing workflows in .NET applications.
Understanding Message Receive Modes in Azure Service Bus
Azure Service Bus provides two message receive modes that define what happens to a message when a consumer receives it from a queue or topic subscription.
These modes control when a message is removed from the queue or subscription and whether it can be delivered again if message processing fails.
Azure Service Bus supports the following receive modes:
- PeekLock
- ReceiveAndDelete
1. PeekLock Mode
PeekLock is the default receive mode in Azure Service Bus. When a consumer receives a message, Service Bus places a temporary lock on it instead of immediately removing it from the queue or subscription.
During this lock period, other consumers cannot receive the same message for processing.After successfully processing the message, the consumer must explicitly acknowledge it by calling CompleteMessageAsync(). Azure Service Bus then removes the message from the queue or subscription.
If processing fails, the consumer can:
- Abandon the message: Releases the lock so the message can be delivered again.
- Allow the lock to expire: Service Bus makes the message available for redelivery after the lock expires.
- Dead-letter the message: Moves the message to the Dead-Letter Queue for further investigation.
Example:
</> C#
var receiver = client.CreateReceiver(
"orders-queue",
new ServiceBusReceiverOptions
{
ReceiveMode = ServiceBusReceiveMode.PeekLock
});
ServiceBusReceivedMessage message =
await receiver.ReceiveMessageAsync();
try
{
// Process the message
Console.WriteLine(message.Body);
// Acknowledge successful processing
await receiver.CompleteMessageAsync(message);
}
catch (Exception)
{
// Release the lock for redelivery
await receiver.AbandonMessageAsync(message);
}Key Points:
- Messages are not deleted immediately after receiving them.
- The consumer must explicitly acknowledge successful processing.
- Failed messages can be delivered again.
- Supports reliable message processing with at-least-once delivery behavior.
- Applications should implement idempotent processing to handle possible duplicate deliveries.
2. ReceiveAndDelete Mode
In ReceiveAndDelete mode, Azure Service Bus removes the message from the queue or subscription as soon as it delivers the message to the consumer.
Unlike PeekLock mode, the consumer does not need to explicitly acknowledge the message using CompleteMessageAsync().
Once the message is delivered, Service Bus considers it consumed. If the consumer encounters an error or crashes while processing the message, the message cannot be recovered through normal Service Bus redelivery.
Example:
</> C#
var receiver = client.CreateReceiver(
"orders-queue",
new ServiceBusReceiverOptions
{
ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete
});
ServiceBusReceivedMessage message =
await receiver.ReceiveMessageAsync();
if (message != null)
{
// Process the message
Console.WriteLine(message.Body);
}
Key Points:
- Messages are deleted immediately after delivery.
- No explicit acknowledgement is required.
- Failed processing does not automatically result in message redelivery.
- Suitable when message loss is acceptable and processing speed is more important than delivery reliability.
- Provides at-most-once delivery behavior.
PeekLock vs ReceiveAndDelete
| Feature | PeekLock | ReceiveAndDelete |
|---|---|---|
| Message deletion | After successful acknowledgement | Immediately after delivery |
| Acknowledgement | Required | Not required |
| Message redelivery | Possible | Not available after delivery |
| Reliability | Higher | Lower |
| Delivery behavior | At-least-once | At-most-once |
| Best suited for | Critical business operations | Non-critical or loss-tolerant processing |
Which Receive Mode Should You Choose?
Use PeekLock when message processing must be reliable, such as order processing, payment handling, inventory updates, and financial transactions.
Use ReceiveAndDelete when losing a message during processing is acceptable, such as certain telemetry or non-critical event-processing scenarios.
For most business applications, PeekLock is the recommended choice because it provides an opportunity to retry failed message processing.
Understanding Subscription Filters in Azure Service Bus
Azure Service Bus Topics support the publish-subscribe messaging pattern, where a producer sends messages to a topic and multiple subscribers receive messages through their respective subscriptions.
However, not every subscriber needs to receive every message published to a topic. For example, in an order management application, the Kitchen team may need order preparation messages, the Billing team may need payment-related messages, and the Delivery team may need delivery-related messages.
Azure Service Bus provides Subscription Filters to control which messages are delivered to each subscription.
A subscription filter evaluates message properties, such as system properties and application properties, to determine whether a message should be delivered to a particular subscription.
How Subscription Filters WorkWhen a producer sends a message to a topic, Azure Service Bus evaluates the configured filters for each subscription.
If a message matches a subscription's filter condition, it is made available to that subscription. Otherwise, it is not delivered to that subscription.
Example:
Consider an order management application with a topic named orders-topic and three subscriptions:
- KitchenSubscription: Receives messages related to food preparation.
- BillingSubscription: Receives messages related to payment processing.
- DeliverySubscription: Receives messages related to order delivery.
The producer sends an order message with the following application property:
message.ApplicationProperties["OrderType"] = "Delivery";
The subscription filters can be configured as follows:
| Subscription | Filter Condition |
|---|---|
| KitchenSubscription | OrderType = 'Kitchen' |
| BillingSubscription | OrderType = 'Billing' |
| DeliverySubscription | OrderType = 'Delivery' |
In this example, the message is delivered only to DeliverySubscription because its filter condition matches the message's OrderType property.
Azure Service Bus supports the following subscription filter types:
TrueFilter
Matches every message sent to the topic. It is useful when a subscription needs to receive all messages.
FalseFilter
Does not match any messages. It can be used when a subscription should not receive messages through that filter rule.
SqlRuleFilter
Uses SQL-like expressions to evaluate message properties and determine whether a message matches a subscription.
For example:
OrderType = 'Delivery' AND Priority = 'High'
This filter matches messages where the order type is Delivery and the priority is High.
CorrelationRuleFilter
Matches messages based on specific system or application property values, such as CorrelationId, MessageId, Subject, or custom application properties.
It is useful when simple property-based matching is sufficient.
Filter ActionsIn addition to filtering messages, Azure Service Bus supports Filter Actions.
A filter action can modify or add message properties when a message matches a subscription rule.
For example, a subscription rule can assign a processing priority to matching messages.
Filter actions are useful when subscribers need additional metadata for downstream processing.
Benefits of Subscription Filters- Selective Message Delivery: Each subscription receives only the messages relevant to its business requirements.
- Reduced Unnecessary Processing: Consumers do not need to inspect and discard irrelevant messages.
- Flexible Routing: Messages can be routed based on system and application properties.
- Improved Scalability: Different application components can process relevant messages independently.
Understanding Azure Service Bus Message Operations
Azure Service Bus provides several operations that allow applications to send, receive, process, and manage messages throughout their lifecycle.
These operations help developers control message delivery, handle processing failures, schedule messages for future delivery, and inspect messages without consuming them.
The following are the commonly used message operations in Azure Service Bus:
Sending MessagesSending is the operation used by a producer application to publish a message to an Azure Service Bus queue or topic.
A message can contain business data in its body along with system and application properties.
The SendMessageAsync() method is used to send an individual message, while SendMessagesAsync() can send a batch of messages.
Example:
</> C#
await using var client = new ServiceBusClient(connectionString);
ServiceBusSender sender =client.CreateSender("orders-queue");
var message = new ServiceBusMessage(BinaryData.FromObjectAsJson(new{OrderId = 1001,CustomerName = "John",Amount = 2500}))
{MessageId = Guid.NewGuid().ToString(),ContentType = "application/json"
};
await sender.SendMessageAsync(message);
In this example, the producer creates a message containing order details and sends it to the orders-queue.
Receiving is the operation used by a consumer application to retrieve messages from a queue or topic subscription.
Azure Service Bus supports two receive modes:
- PeekLock: Locks the message temporarily and requires the consumer to acknowledge successful processing.
- ReceiveAndDelete: Removes the message as soon as it is delivered to the consumer.
The ReceiveMessageAsync() method retrieves a single message, while ReceiveMessagesAsync() retrieves multiple messages.
Example:
</> C#
await using var client = new ServiceBusClient(connectionString);
ServiceBusReceiver receiver =client.CreateReceiver("orders-queue");
ServiceBusReceivedMessage message =await receiver.ReceiveMessageAsync();
if (message != null)
{Console.WriteLine(message.Body);
}
By default, the receiver uses PeekLock mode.
Completing MessagesCompleting a message indicates that the consumer has successfully processed it.
When using PeekLock mode, the consumer must call CompleteMessageAsync() after successful processing. Azure Service Bus then removes the message from the queue or subscription.
Example:
</> C#
ServiceBusReceivedMessage message =await receiver.ReceiveMessageAsync();
if (message != null)
{// Process the messageConsole.WriteLine(message.Body);
// Mark the message as successfully processedawait receiver.CompleteMessageAsync(message);
}
Key Points:
- Used with PeekLock mode.
- Permanently removes the successfully processed message.
- Prevents normal redelivery of the completed message.
- Should be called only after successful business processing.
Abandoning a message releases its lock and makes the message available for another delivery.
This operation is useful when a consumer cannot process a message temporarily and wants Azure Service Bus to make it available for retry.
The AbandonMessageAsync() method is used to abandon a received message.
Example:
</> C#
try
{// Process the messageawait ProcessOrderAsync(message);
await receiver.CompleteMessageAsync(message);
}
catch (Exception)
{// Release the lock for redeliveryawait receiver.AbandonMessageAsync(message);
}
Key Points:
- Releases the message lock.
- Makes the message available for redelivery.
- Increases the message delivery count.
- Repeated failures can eventually cause the message to move to the Dead-Letter Queue when the configured maximum delivery count is exceeded.
Abandoning a message does not guarantee immediate redelivery. Delivery depends on message availability and the receiver's behavior.
Deferring MessagesDeferring a message allows a consumer to postpone processing it when the message cannot be handled immediately.
Unlike abandoning a message, deferring does not make it available for normal message retrieval. Instead, the message remains in the queue or subscription and must be retrieved later using its sequence number.
The DeferMessageAsync() method is used to defer a message.
Example:
// Defer the message
await receiver.DeferMessageAsync(message);
// Store the sequence number for later retrieval
long sequenceNumber = message.SequenceNumber;
Later, the consumer can retrieve the deferred message using its sequence number.
</> C#
ServiceBusReceivedMessage deferredMessage =await receiver.ReceiveDeferredMessageAsync(sequenceNumber);
if (deferredMessage != null)
{// Process the deferred messageConsole.WriteLine(deferredMessage.Body);
await receiver.CompleteMessageAsync(deferredMessage);
}
Key Points:
- Temporarily postpones message processing.
- Deferred messages are not available through normal receive operations.
- The consumer must retain the message sequence number.
- Deferred messages remain subject to their configured Time To Live (TTL).
Deferral is useful when a message depends on another message or business operation that has not yet been completed.
Dead-Lettering MessagesDead-lettering moves a message from its original queue or subscription into its associated Dead-Letter Queue (DLQ).
This operation is useful when a message cannot be processed because of invalid data, business rule violations, or repeated processing failures.
The DeadLetterMessageAsync() method is used to explicitly move a message to the Dead-Letter Queue.
Example:
</> C#
if (!IsValidOrder(message))
{await receiver.DeadLetterMessageAsync(message,"InvalidOrder","Order validation failed.");
return;
}
Azure Service Bus can also automatically dead-letter messages in certain situations, such as when the maximum delivery count is exceeded or when an expired message is configured to be dead-lettered.
Key Points:
- Moves an unprocessable message to the Dead-Letter Queue.
- Supports a dead-letter reason and description.
- Allows failed messages to be inspected and investigated separately.
- Dead-letter messages can be retrieved and processed using a DLQ receiver.
Example of receiving a dead-letter message:
</> C#
ServiceBusReceiver dlqReceiver =client.CreateReceiver("orders-queue",new ServiceBusReceiverOptions{ SubQueue = SubQueue.DeadLetter});
ServiceBusReceivedMessage deadLetterMessage =await dlqReceiver.ReceiveMessageAsync();
if (deadLetterMessage != null)
{Console.WriteLine(deadLetterMessage.DeadLetterReason);
// Complete after investigation or recoveryawait dlqReceiver.CompleteMessageAsync(deadLetterMessage);
}
Scheduling Messages
Scheduling allows a producer to send a message that becomes available for delivery at a specified future date and time.
This is useful when an application needs to execute a business operation at a later time, such as sending payment reminders, appointment notifications, or order follow-ups.
The ScheduleMessageAsync() method is used to schedule a message.
Example:
</> C#
var message = new ServiceBusMessage("Send payment reminder");
DateTimeOffset scheduledTime =DateTimeOffset.UtcNow.AddHours(2);
long sequenceNumber =await sender.ScheduleMessageAsync(message,scheduledTime);
In this example, the message is scheduled to become available approximately two hours later.
The method returns a sequence number that can be used to cancel the scheduled message if required.
Key Points:
- Messages become available at a specified future time.
- Scheduled messages are not immediately available for normal consumption.
- The scheduling operation returns a sequence number.
- Scheduling is useful for reminders, delayed notifications, and time-based business workflows.
Azure Service Bus allows applications to cancel a previously scheduled message before it becomes available for delivery.
The CancelScheduledMessageAsync() method is used to cancel a scheduled message using its sequence number.
Example:
</> C#
long sequenceNumber =await sender.ScheduleMessageAsync(message,DateTimeOffset.UtcNow.AddHours(2));
// Cancel the scheduled message
await sender.CancelScheduledMessageAsync(sequenceNumber);
Key Points:
- Requires the sequence number returned by the scheduling operation.
- Prevents the scheduled message from becoming available for delivery if cancellation succeeds.
- Useful when a business condition changes before the scheduled delivery time.
For example, if a customer completes a payment before a scheduled payment reminder is delivered, the application can cancel the reminder.
Peeking MessagesPeeking allows a consumer to inspect messages in a queue or subscription without locking, consuming, or removing them.
Unlike normal receiving, peeking does not change the message state or increase its delivery count.
The PeekMessageAsync() method retrieves the next available message for inspection.
Example:
</> C#
ServiceBusReceivedMessage message =await receiver.PeekMessageAsync();
if (message != null)
{Console.WriteLine("Message ID: " + message.MessageId);Console.WriteLine("Message Body: " + message.Body);
}
To inspect multiple messages, use PeekMessagesAsync().
</> C#
IReadOnlyList<ServiceBusReceivedMessage> messages =await receiver.PeekMessagesAsync(10);
foreach (var message in messages)
{Console.WriteLine(message.MessageId);
}
Key Points:
- Does not remove messages from the queue or subscription.
- Does not lock messages.
- Does not increase the delivery count.
- Useful for monitoring, debugging, and inspecting message metadata.
Peeking is intended for inspection rather than message processing. It does not guarantee that a message will still be available when a consumer later attempts to receive it.
Summary of Azure Service Bus Message Operations| Operation | Purpose |
|---|---|
| Send | Sends a message to a queue or topic. |
| Receive | Retrieves a message for processing. |
| Complete | Acknowledges successful processing and removes the message. |
| Abandon | Releases the lock and allows redelivery. |
| Defer | Postpones processing until later retrieval. |
| Dead-letter | Moves an unprocessable message to the DLQ. |
| Schedule | Makes a message available at a future time. |
| Cancel Scheduled | Cancels a previously scheduled message. |
| Peek | Inspects messages without consuming them. |
Understanding the Azure Service Bus Message Processing Lifecycle
The Azure Service Bus Message Processing Lifecycle describes how a message moves through different stages, starting from the producer application sending a message and ending with successful processing or an alternative outcome such as retry, deferral, or dead-lettering.
Azure Service Bus provides different message operations to help applications manage message delivery, handle processing failures, and ensure reliable communication between distributed components.
Let's understand the different stages of the message processing lifecycle.
Message SendingThe lifecycle begins when a producer application creates and sends a message to an Azure Service Bus queue or topic.
The message contains the business payload along with system and application properties.
For example, an order management application sends an order message to an orders-queue.
</> C#
var message = new ServiceBusMessage(
BinaryData.FromObjectAsJson(order))
{
MessageId = Guid.NewGuid().ToString(),
ContentType = "application/json"
};
await sender.SendMessageAsync(message);
Once the send operation succeeds, the message is accepted by Azure Service Bus.
Message ReceivingA consumer application receives the message from the queue or topic subscription.
When using PeekLock mode, Azure Service Bus places a temporary lock on the message. This prevents other consumers from processing the same message concurrently while the lock remains valid.
The consumer can now process the message.
</> C#
ServiceBusReceivedMessage message =
await receiver.ReceiveMessageAsync();
if (message != null)
{
// Process the received message
}
Successful Processing – Complete
If the consumer processes the message successfully, it acknowledges the message using CompleteMessageAsync().
Azure Service Bus removes the message from the queue or subscription after successful settlement.
</> C#
await receiver.CompleteMessageAsync(message);
This represents the successful completion of the message processing lifecycle.
Processing Failure – Abandon and RetryIf the consumer cannot process a message, it can abandon the message using AbandonMessageAsync().
Abandoning releases the message lock and makes the message available for another delivery.
The message delivery count increases when it is received again.
</> C#
try
{
await ProcessOrderAsync(message);
await receiver.CompleteMessageAsync(message);
}
catch (Exception)
{
await receiver.AbandonMessageAsync(message);
}
This allows the application to retry processing the message.
However, repeated processing failures can cause the message to exceed the configured maximum delivery count.
When this happens, Azure Service Bus automatically moves the message to the Dead-Letter Queue, provided dead-lettering on maximum delivery count is enabled.
Deferred Message ProcessingSometimes a consumer receives a message that cannot be processed immediately because it depends on another message or business operation.
Instead of abandoning it for normal redelivery, the consumer can defer the message.
</> C#
await receiver.DeferMessageAsync(message);
long sequenceNumber = message.SequenceNumber;
The application must store the sequence number so that the deferred message can be retrieved later.
</> C#
ServiceBusReceivedMessage deferredMessage =
await receiver.ReceiveDeferredMessageAsync(
sequenceNumber);
After the required dependency is resolved, the consumer can process and complete the deferred message.
Dead-LetteringA message may become permanently unprocessable because of invalid data, business rule violations, or repeated processing failures.
In such cases, the consumer can explicitly move the message to the Dead-Letter Queue.
</> C#await receiver.DeadLetterMessageAsync(
message,
"InvalidOrder",
"Order validation failed.");
Azure Service Bus also supports automatic dead-lettering for certain conditions, including exceeding the configured maximum delivery count.
Messages in the Dead-Letter Queue can be inspected, investigated, and optionally reprocessed by a separate application.
Message Processing Lifecycle Summary| Stage | Operation | Result |
|---|---|---|
| 1 | Send | Message is sent to a queue or topic |
| 2 | Receive | Consumer retrieves and locks the message |
| 3 | Complete | Message is successfully processed and removed |
| 4 | Abandon | Message becomes available for redelivery |
| 5 | Defer | Message is set aside for later retrieval |
| 6 | Dead-letter | Message moves to the Dead-Letter Queue |
Best Practices for Message Processing
- Use PeekLock for reliable processing.
- Implement idempotent consumers.
- Configure appropriate lock durations and renewal.
- Handle exceptions and retries.
- Monitor and process dead-letter messages.
- Use filters to route messages efficiently.
Summary
Azure Service Bus provides a powerful messaging platform for building reliable and scalable distributed applications. Understanding how messages are received, filtered, and processed is essential for designing effective messaging workflows.
In this article, we explored the two message receive modes, PeekLock and ReceiveAndDelete, subscription filters, and important message operations such as sending, receiving, completing, abandoning, deferring, dead-lettering, scheduling, cancelling scheduled messages, and peeking.
We also explored the Azure Service Bus message processing lifecycle and how applications handle successful processing, retries, deferred messages, and processing failures.
By understanding these concepts, developers can build more reliable message-driven applications, handle failures effectively, and manage asynchronous communication between distributed services.
In the next article, we will explore Azure Service Bus Subscription Filters in detail, including SQL filters, Correlation filters, filter actions, and their implementation using the Azure Service Bus .NET SDK.
Thanks