Azure Service BusMessaging
What it is. Azure Service Bus is a fully managed enterprise message broker: it hosts queues for point-to-point delivery and topics with subscriptions for publish-subscribe fan-out. Applications and services exchange messages through it instead of calling each other directly, which decouples producers from consumers and lets each side scale, fail and deploy on its own.
Architecture Diagram
End-to-end architectural topology of Azure Service Bus, demonstrating the namespace isolation boundary, supported ingress protocols, point-to-point Queues (with duplicate detection, sessions, and Dead-Letter Queue), publish-subscribe Topics with Subscription filtering rules, competing consumer scaling, and the complete Peek-Lock message settlement lifecycle.
Core concepts
- Namespace
- Deployment and billing container that gives you a unique host name (
<namespace>.servicebus.windows.net); all queues and topics live inside it. - Queue
- Point-to-point destination: each message is delivered to a single competing consumer. Multiple readers can be attached; the broker hands each message to only one of them.
- Topic and subscription
- Publish-subscribe destination: a topic accepts messages and each subscription receives its own copy, so several downstream systems can react to the same publication independently.
- Filters and actions
- Subscriptions can carry SQL or correlation filters so they only receive a subset of the messages; actions can annotate the message properties on the way in.
- Sessions
- Messages that share a
SessionIdare handled in order by a single receiver, which gives ordered processing for a related stream of work without locking the whole queue. - Peek-lock and settlement
- Receivers take a message under a lock and then complete, abandon, defer or dead-letter it. Abandoning returns the message to the queue and increments its delivery count.
- Dead-letter queue
- Each queue and subscription has a secondary sub-queue where messages land when they expire or exceed the maximum delivery count — the place to inspect poison messages instead of losing them.
- Duplicate detection
- The broker discards a message whose
MessageIdwas already seen inside a configurable detection window, which makes retries from the sender safe. - Scheduled messages and deferral
- A message can be enqueued with a future enqueue time, or deferred and later retrieved by sequence number — useful for time-based workflows and out-of-order handling.
- Auto-forwarding and transactions
- Entities can chain into each other (a queue forwarding to a topic, for example), and send/receive operations can be grouped in a transaction that commits or rolls back as a unit.
Service tiers
| Tier | Entities | Typical use |
|---|---|---|
| Basic | Queues only | Cheap queueing for development, tests and simple one-way work; no topics, no duplicate detection. |
| Standard | Queues and topics | General production messaging with the full feature set (sessions, dead-lettering, filters, duplicate detection) on shared infrastructure. |
| Premium | Queues and topics | Dedicated resources for predictable latency and throughput, isolation through private networking, and the largest message sizes. |
Feature availability changes over time — check the current tier matrix before sizing a production namespace.
Step-by-Step Configuration & Usage Guide (with Screenshots)
A complete, screenshot-driven walkthrough for configuring and using Azure Service Bus from scratch: provisioning namespaces, setting up queues with dead-lettering and deduplication, configuring pub/sub topics with SQL filtering, establishing security credentials, testing with Service Bus Explorer, and implementing production-ready .NET 8 producers and consumers.
| # | Phase | Action Summary | Key Focus |
|---|---|---|---|
| 1 | Create Namespace | Provision namespace in Azure Portal with Standard/Premium tier. | DNS host, region, tier |
| 2 | Verify Dashboard | Inspect deployment completion, Essentials bar, and throughput metrics. | Endpoint validation |
| 3 | Configure Queue | Create orders-queue with duplicate detection, lock duration, and DLQ. |
Point-to-point, max deliveries |
| 4 | Create Topic & Subscriptions | Create events-topic and subscriptions with SQL/correlation rules. |
1:N Fan-out, content routing |
| 5 | Configure Security | Grant Entra ID RBAC roles (Data Sender/Receiver) or generate SAS policy keys. | Zero-trust authentication |
| 6 | Service Bus Explorer | Send JSON test payloads and peek/settle messages in the browser. | In-portal validation |
| 7 | Programmatic .NET Code | Build C# producer (batch send) and processor with peek-lock completion loop. | Complete/Abandon/DLQ |
| 8 | Monitoring & DLQ Alerts | Configure Azure Monitor metrics and set automated alerts on DLQ spikes. | Poison message observation |
Create Azure Service Bus Namespace in Portal
The namespace is the root management, billing, and DNS container (<namespace>.servicebus.windows.net) that houses all your queues and topics.
- Navigate to the Azure Portal and sign in with your administrator account.
- In the top global search bar, type Service Bus and select Service Bus under Services. Alternatively, click + Create a resource → Integration → Service Bus.
- Click + Create to open the Create namespace provisioning wizard.
- Under Project Details, select your active Subscription and pick or create a target Resource group (e.g.
rg-messaging-prod). - Under Instance Details:
- Namespace name: Enter a globally unique name (e.g.
sb-ecommerce-prod). A green checkmark confirms availability. - Location: Choose your target Azure region (e.g.
East US) close to your client workloads. - Pricing tier: Choose Standard for production publish-subscribe topics, queues, sessions, and deduplication. (Select Premium if you require private link isolation and dedicated messaging units).
- Namespace name: Enter a globally unique name (e.g.
- Click Review + create, verify the validation passed, and click Create.
Verify Provisioning & Explore Namespace Dashboard
Once Azure Resource Manager completes deployment, access the namespace overview to inspect endpoint addresses, resource status, and operational telemetry.
- When the notification banner confirms “Your deployment is complete”, click Go to resource.
- Inspect the Essentials top card:
- Status: Ensure it shows Active.
- Host name: Note your primary DNS endpoint (e.g.
sb-ecommerce-prod.servicebus.windows.net). - Resource group:
rg-messaging-prod.
- Examine the left navigation pane: identify Entities (Queues and Topics) and Settings (Shared access policies, Networking).
- Review the built-in real-time charts in the Overview page displaying Incoming Messages and Outgoing Messages.
Create and Configure a Point-to-Point Queue
Queues implement point-to-point decoupling where multiple workers can read from the queue, but each message is exclusively delivered to and processed by a single competing consumer.
- In the left sidebar under Entities, click Queues, then click + Queue on the command bar.
- In the Add queue side blade, configure the following core parameters:
- Name:
orders-queue. - Max queue size:
1 GB(or up to 80 GB in Premium). - Max delivery count:
10. After 10 failed/abandoned delivery attempts, the message is automatically sequestered in the Dead-Letter Queue (DLQ). - Message time to live (TTL):
14 Days. - Lock duration:
30 Seconds(time a consumer has to process and settle before the lock expires).
- Name:
- Select the advanced feature flags:
- Check Enable duplicate detection with a
10 minutesdetection window (broker discards duplicateMessageIds). - Check Enable dead lettering on message expiration so expired orders are never silently lost.
- (Optional) Check Enable sessions if strict FIFO per
SessionIdis required.
- Check Enable duplicate detection with a
- Click Create at the bottom of the blade.
RenewMessageLockAsync() in code rather than setting an excessively long default lock duration.
Create a Topic with Filtered Subscriptions (Pub/Sub)
Topics provide 1:N publish-subscribe fan-out: publishers send to a single topic, and each attached subscription receives an independent copy according to configurable rule filters.
- In the left sidebar under Entities, click Topics, then click + Topic. Enter name
events-topicand click Create. - Click on the newly created events-topic to open its blade, then click + Subscription.
- In the Add subscription blade, configure subscription
sub-billing:- Subscription name:
sub-billing. - Max delivery count:
10.
- Subscription name:
- Open the subscription’s Filters & actions tab:
- Add a SQL Filter:
sys.Label = 'OrderPlaced' AND Amount >= 100.00. - Add an optional Rule Action:
SET RoutedBy = 'EnterpriseBus';to annotate message headers before queuing.
- Add a SQL Filter:
- Repeat the process to add other independent subscriptions (e.g.
sub-shippingwith correlation filter orsub-auditwith TrueFilter1=1).
Configure Access Security: Microsoft Entra ID & SAS
Grant client applications permission to send or receive messages securely using either passwordless RBAC (recommended) or Shared Access Signature (SAS) connection strings.
- Option A — Microsoft Entra ID (Recommended for Production & Cloud Apps):
- Go to Access control (IAM) → + Add → Add role assignment.
- For producers, assign the Azure Service Bus Data Sender role to your App Service, Azure Function, or User Managed Identity.
- For consumers, assign the Azure Service Bus Data Receiver role.
- Option B — Shared Access Policies (SAS Connection Strings):
- In the left sidebar under Settings, click Shared access policies.
- Click + Add, specify name
SendListenPolicy, check Send and Listen (avoid checking Manage unless granting administrative privileges), then click Create. - Click the policy to open its drawer and copy the Primary Connection String (starts with
Endpoint=sb://...).
DefaultAzureCredential with Managed Identities.
Test and Settle Messages via Service Bus Explorer
The Azure Portal embeds Service Bus Explorer, a powerful tool for publishing test payloads, peeking at queue depth, and testing settlement without writing code.
- Navigate to Entities → Queues → click on orders-queue.
- In the queue’s left menu, select Service Bus Explorer.
- Send a Test Message:
- Select the Send messages sub-tab.
- Set Content Type to application/json.
- Paste sample JSON payload in the message body:
{ "orderId": "ORD-2026-904", "customer": "Fabrikam Retail", "amount": 250.00, "status": "APPROVED" } - Under Custom Properties, add key
sys.Labelwith valuePriority. - Click Send. A green notification confirms successful ingress.
- Peek and Settle Messages:
- Switch to the Peek from start tab to view the active message queue without removing messages.
- Inspect Message ID
msg-9041, Sequence Number, Enqueued Time, and Delivery Count. - Click into the message to inspect headers and simulate Dead-lettering or settlement.
Programmatic Implementation: C# .NET Producer & Consumer
Implement a production-grade publisher and asynchronous message processor using the official Azure.Messaging.ServiceBus SDK with the complete Peek-Lock settlement lifecycle.
- Install official client and identity packages in your .NET project:
dotnet add package Azure.Messaging.ServiceBus dotnet add package Azure.Identity - Sender (Producer): Creates a batch of messages and sends them atomically:
using Azure.Identity; using Azure.Messaging.ServiceBus; // Authenticate via Microsoft Entra ID (or connection string) await using var client = new ServiceBusClient( "sb-ecommerce-prod.servicebus.windows.net", new DefaultAzureCredential()); ServiceBusSender sender = client.CreateSender("orders-queue"); // Build message batch for optimal AMQP throughput using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync(); var order = new ServiceBusMessage("payload-json-bytes") { ContentType = "application/json", MessageId = "msg-9041", // Enables duplicate detection Subject = "OrderPlaced" // Used for subscription filter routing }; if (batch.TryAddMessage(order)) { await sender.SendMessagesAsync(batch); Console.WriteLine("[PRODUCER] Sent message batch successfully."); } - Processor (Consumer) with Peek-Lock Settlement:
ServiceBusProcessor processor = client.CreateProcessor("orders-queue", new ServiceBusProcessorOptions { ReceiveMode = ServiceBusReceiveMode.PeekLock, // Message stays locked until settled MaxConcurrentCalls = 4, // Concurrent competing worker threads AutoCompleteMessages = false // Explicit settlement control }); processor.ProcessMessageAsync += async args => { string payload = args.Message.Body.ToString(); Console.WriteLine($"[CONSUMER] Received order: {payload}"); try { // 1. Execute business logic await ProcessOrderAsync(payload); // 2. Success: Complete and delete from queue await args.CompleteMessageAsync(args.Message); Console.WriteLine("[ACK] Message completed successfully."); } catch (TransientNetworkException) { // 3. Transient failure: Release lock for retry (+1 delivery count) await args.AbandonMessageAsync(args.Message); } catch (InvalidOrderDataException ex) { // 4. Poison message: Move directly to Dead-Letter Queue with error reason await args.DeadLetterMessageAsync(args.Message, "InvalidOrderPayload", ex.Message); } }; processor.ProcessErrorAsync += args => { Console.WriteLine($"[ERROR] {args.Exception.Message}"); return Task.CompletedTask; }; await processor.StartProcessingAsync(); Console.WriteLine("Worker listening for orders. Press [Enter] to exit."); Console.ReadLine(); await processor.StopProcessingAsync();
Monitor Queue Depth & Configure Dead-Letter Alerts
Operational excellence in Service Bus requires observing active queue depth, latency, and setting proactive alerts whenever poison messages arrive in the Dead-Letter Queue.
- In the namespace left sidebar under Monitoring, select Metrics.
- Add the key operational metrics:
- Incoming Messages (Sum): Ingress message rate from senders.
- Outgoing Messages (Sum): Consumption and settlement rate by workers.
- Dead-lettered Messages (Average): Messages quarantined in the DLQ.
- Create a Poison Message Alert Rule:
- Click + New alert rule on the metrics toolbar.
- Signal: Dead-lettered Messages.
- Threshold: Set Greater than 0 over a 5-minute aggregation window.
- Action Group: Assign your DevOps PagerDuty / Email on-call group.
- Severity:
Sev 2 (Warning)orSev 1 (Error).
- Save the alert rule to ensure operational teams are notified immediately when a poison message arrives for manual root-cause inspection.
When to use it
- Decoupling services — the producer does not need the consumer to be online, and each side scales on its own.
- Competing consumers — several instances of a worker drain the same queue, so throughput grows by adding replicas.
- Ordered work streams — sessions keep messages with the same key in order without serializing the whole queue.
- Poison-message handling — retries plus a dead-letter queue make failures observable instead of silent.
Related in this knowledge base
- Azure Functions — has a Service Bus trigger and output binding, the usual way to consume messages without hosting a worker.
- Azure Logic Apps — Service Bus connectors let a workflow send, receive and peek messages.
- Azure Monitor — where namespace metrics and diagnostic logs are surfaced.