Azure Service Bus for Decoupled Messaging
Create a Service Bus namespace with queues and topics, send and receive messages from an application, and configure dead-letter queues for failed message handling.
Azure Service Bus for Decoupled Messaging is a free Cloud & IT Cert Prep lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Cloud & IT Cert Prep learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Decouple with Messaging?
In tightly coupled architectures, services call each other synchronously — if the downstream service is slow or down, the caller blocks or fails too. Messaging queues introduce an asynchronous buffer between producers and consumers, so that a slow downstream service does not cascade failures upstream. Azure Service Bus is Microsoft's enterprise-grade messaging service, providing queues (point-to-point) and topics (publish-subscribe) with guaranteed delivery, ordering, and dead-lettering capabilities.
Service Bus Namespaces and Tiers
A Service Bus namespace is the top-level container for all messaging entities (queues and topics) and provides the FQDN endpoint (e.g., myns.servicebus.windows.net). Namespaces come in three tiers: Basic (queues only, no topics, max 256 KB message size), Standard (queues + topics, 256 KB max), and Premium (queues + topics, up to 100 MB messages, dedicated capacity, VNet integration, geo-disaster recovery). Premium is required for production workloads needing SLA-backed performance.
# Create a Service Bus namespace (Standard tier)
az servicebus namespace create \
--resource-group myRG \
--name myservicebusns \
--location eastus \
--sku StandardQueues: Point-to-Point Messaging
A Service Bus queue stores messages in FIFO order and delivers each message to exactly one consumer. Consumers receive messages using a peek-lock mechanism: the message is temporarily hidden from other consumers while being processed. If the consumer completes successfully, it calls CompleteMessage() to remove it from the queue. If processing fails, the consumer calls AbandonMessage() and the message becomes visible again for another attempt. After a configurable number of delivery attempts, unprocessable messages are moved to the dead-letter queue (DLQ).
# Create a Service Bus queue with DLQ enabled
az servicebus queue create \
--resource-group myRG \
--namespace-name myservicebusns \
--name orders \
--max-delivery-count 5 \
--default-message-time-to-live P7D \
--dead-lettering-on-message-expiration trueTopics and Subscriptions
Topics implement the publish-subscribe pattern: a producer sends a message to a topic, and any number of subscriptions on that topic each receive a copy of the message. Subscriptions can have filters (SQL or correlation expressions) to receive only a subset of messages — for example, a HighPriority subscription that only receives messages where the Priority property equals High. This allows a single topic to fan out to many downstream services, each interested in a different subset of events.
# Create a topic and two subscriptions with filters
az servicebus topic create \
--resource-group myRG \
--namespace-name myservicebusns \
--name order-events
az servicebus topic subscription create \
--resource-group myRG \
--namespace-name myservicebusns \
--topic-name order-events \
--name high-priority-sub
az servicebus topic subscription rule create \
--resource-group myRG \
--namespace-name myservicebusns \
--topic-name order-events \
--subscription-name high-priority-sub \
--name PriorityFilter \
--filter-sql-expression 'Priority = '"'"'High'"'"''Sending and Receiving Messages
The Azure Service Bus SDK provides a ServiceBusClient for sending and receiving. To send, create a ServiceBusSender and call SendMessageAsync(). To receive, create a ServiceBusReceiver and call ReceiveMessageAsync() (pull-based) or use a ServiceBusProcessor with an event handler for push-based continuous processing. Using DefaultAzureCredential with the Service Bus SDK eliminates the need for connection strings, maintaining the passwordless pattern.
# Python: Send a message to a Service Bus queue
from azure.servicebus import ServiceBusClient, ServiceBusMessage
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
client = ServiceBusClient(
fully_qualified_namespace='myservicebusns.servicebus.windows.net',
credential=credential
)
with client.get_queue_sender(queue_name='orders') as sender:
msg = ServiceBusMessage('{ 'orderId': '12345', 'amount': 99.99 }')
sender.send_messages(msg)
print('Message sent')Dead-Letter Queue
The dead-letter queue (DLQ) is a sub-queue that automatically receives messages that cannot be delivered. Messages are dead-lettered when: they exceed the maximum delivery count, they expire (TTL elapsed), or they fail a topic subscription filter evaluation. Monitoring the DLQ is essential — a growing DLQ indicates a systematic processing failure. DLQ messages retain their original content plus dead-letter reason and description properties added by Service Bus to help diagnose the root cause.
# Read messages from the dead-letter queue
az servicebus queue show \
--resource-group myRG \
--namespace-name myservicebusns \
--name 'orders/$DeadLetterQueue' \
--query 'countDetails.deadLetterMessageCount'Message Sessions for Ordering
Sessions enable strict ordering of messages that belong to the same logical group. Each message is tagged with a SessionId (e.g., a customer ID or order ID), and a session-aware consumer receives all messages for a given session in FIFO order, exclusively. Sessions are essential for workflows where steps must execute in sequence — such as processing all events for a specific order: Created → PaymentReceived → Shipped → Delivered. Sessions are enabled at queue or subscription creation time.
Service Bus vs. Event Grid vs. Event Hubs
These three Azure messaging services are often confused: Service Bus is for reliable, transactional enterprise messaging with ordering, sessions, and DLQ — suitable for order processing, financial transactions, and workflow orchestration. Event Grid is for reactive event routing (a blob was uploaded, a VM was deleted) with fan-out to multiple handlers but no ordering or replay. Event Hubs is for high-throughput event streaming (millions of events per second) with replay capability — suitable for IoT telemetry and log ingestion. Choose based on ordering, throughput, and durability requirements.
Geo-Disaster Recovery
Service Bus Geo-Disaster Recovery (Geo-DR) replicates the namespace metadata (queues, topics, subscriptions, and access policies) to a secondary region. The paired regions share a single alias hostname; if the primary fails, you initiate a failover and the alias resolves to the secondary. Note that message data (in-flight messages) is not replicated in the Standard tier — only the Premium tier's Geo-DR replicates messages. For mission-critical messaging, use Premium + Geo-DR to meet RTO and RPO requirements.
Scaling and Partitioned Entities
For high-throughput scenarios, enable partitioning on queues and topics at creation time. Partitioned entities use multiple message brokers and storage fragments internally, multiplying throughput capacity. In the Standard tier, partitioned entities have up to 80 GB total size. Each message is routed to a partition based on its PartitionKey property (defaults to the session ID if sessions are enabled). Partitioning is a one-time decision at creation — you cannot partition an existing queue. Use the Premium tier for the highest guaranteed throughput without partitioning complexity.
# Create a partitioned queue (Standard tier)
az servicebus queue create \
--resource-group myRG \
--namespace-name myservicebusns \
--name orders-partitioned \
--enable-partitioning trueMonitoring Service Bus Health
Key Service Bus metrics to monitor in Azure Monitor: Active Messages (queue depth — rising depth indicates consumer lag), Dead-lettered Messages (processing failures), Server Errors and User Errors (authentication and throttling issues), and Incoming Requests (overall throughput). Configure metric alerts so that operations teams are notified when the dead-letter queue grows beyond a threshold or when active messages are not being consumed for a sustained period.
Quick Check
Test your understanding of Microsoft Azure Fundamentals (AZ-900) concepts from this lesson.
Lesson Recap
In this lesson you learned: Service Bus queues provide point-to-point messaging with peek-lock delivery and a dead-letter queue for failed messages, topics and subscriptions fan messages out to multiple consumers with filter rules, and sessions enable ordered processing for messages belonging to the same logical group. Next up we explore Azure Container Apps for deploying modern microservices.
Frequently asked questions
Is the “Azure Service Bus for Decoupled Messaging” lesson free?
Yes — the full text of “Azure Service Bus for Decoupled Messaging” is free to read here on the web, and the Cloud & IT Cert Prep course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Cloud & IT Cert Prep course, upgrade to CoddyKit PRO.
What will I learn in “Azure Service Bus for Decoupled Messaging”?
Create a Service Bus namespace with queues and topics, send and receive messages from an application, and configure dead-letter queues for failed message handling. You practise Cloud & IT Cert Prep with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Cloud & IT Cert Prep?
No prior experience is required. Cloud & IT Cert Prep on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Azure Service Bus for Decoupled Messaging” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Cloud & IT Cert Prep lesson?
Yes. Every Cloud & IT Cert Prep lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Managed Identity for Passwordless Auth
- Azure Service Bus for Decoupled Messaging
- Azure Container Apps
- End-to-End Developer Workflow