Service Bus and Event Grid
Azure has two core messaging services: Service Bus for reliable enterprise messaging and Event Grid for lightweight event routing. Use them to decouple services, build event-driven architectures, and process work asynchronously.
Azure Messaging Services at a Glance
Section titled “Azure Messaging Services at a Glance”| Service | Model | Best For | AWS Equivalent |
|---|---|---|---|
| Service Bus Queue | Point-to-point | Task processing, ordered workloads | SQS |
| Service Bus Topic | Pub/Sub (fan-out) | Broadcasting to multiple subscribers | SNS + SQS |
| Event Grid | Event routing (push) | Reacting to Azure resource events, custom events | EventBridge |
| Queue Storage | Simple queue | Basic queueing (high volume, low feature) | SQS (basic) |
| Event Hubs | Streaming | High-throughput telemetry, logs | Kinesis |
Service Bus
Section titled “Service Bus”Service Bus is Azure’s enterprise message broker — feature-rich, reliable, and designed for mission-critical workloads.
Queues (Point-to-Point)
Section titled “Queues (Point-to-Point)”Producer ──send──► [ msg3 msg2 msg1 ] ──receive──► Consumer Service Bus QueueOne producer, one consumer. Messages are processed exactly once (peek-lock) or at-least-once (receive-and-delete).
Topics and Subscriptions (Pub/Sub)
Section titled “Topics and Subscriptions (Pub/Sub)”Producer ──publish──► Topic: order-events ├──► Subscription: payments (filter: amount > 100) ──► Payment service ├──► Subscription: inventory (all messages) ──► Inventory service └──► Subscription: analytics (all messages) ──► Analytics LambdaA topic broadcasts messages to multiple subscriptions. Each subscription gets its own copy and can have filters to receive only relevant messages.
Creating a Service Bus Namespace
Section titled “Creating a Service Bus Namespace”# Create namespace (container for queues and topics)az servicebus namespace create \ --resource-group myapp-rg \ --name myapp-bus \ --sku Standard \ --location eastus
# Create a queueaz servicebus queue create \ --resource-group myapp-rg \ --namespace-name myapp-bus \ --name orders \ --max-delivery-count 10 \ --default-message-time-to-live P14D # 14 days
# Create a topic with subscriptionsaz servicebus topic create \ --resource-group myapp-rg \ --namespace-name myapp-bus \ --name order-events
az servicebus topic subscription create \ --resource-group myapp-rg \ --namespace-name myapp-bus \ --topic-name order-events \ --name payments
az servicebus topic subscription create \ --resource-group myapp-rg \ --namespace-name myapp-bus \ --topic-name order-events \ --name inventorySending and Receiving (Python)
Section titled “Sending and Receiving (Python)”from azure.servicebus import ServiceBusClient, ServiceBusMessagefrom azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()client = ServiceBusClient("myapp-bus.servicebus.windows.net", credential)
# Sendwith client.get_queue_sender("orders") as sender: sender.send_messages(ServiceBusMessage( body='{"order_id": 123, "amount": 49.99}', subject="order.placed", application_properties={"priority": "high"} ))
# Receive (peek-lock: process then complete)with client.get_queue_receiver("orders") as receiver: for msg in receiver.receive_messages(max_message_count=10, max_wait_time=5): process_order(str(msg)) receiver.complete_message(msg) # remove from queue # or: receiver.abandon_message(msg) # return to queue for retry # or: receiver.dead_letter_message(msg, reason="invalid data")Key Features
Section titled “Key Features”| Feature | What It Does |
|---|---|
| Peek-lock | Message is locked while processing; auto-unlocks on timeout if not completed |
| Dead-letter queue (DLQ) | Failed messages move here after max delivery attempts |
| Sessions | Group related messages and process in order (e.g. all messages for one customer) |
| Scheduled delivery | Enqueue a message now, deliver at a future time |
| Duplicate detection | Reject duplicate messages (by message ID, within a time window) |
| Transactions | Send/complete multiple messages atomically |
| Auto-forwarding | Automatically forward messages from one queue/subscription to another |
| Message deferral | Set a message aside and retrieve it later by sequence number |
Sessions (Ordered Processing)
Section titled “Sessions (Ordered Processing)”Sessions guarantee FIFO ordering for messages with the same session ID:
# Send with session IDsender.send_messages(ServiceBusMessage( body='{"step": 1}', session_id="customer-123" # all messages for this customer go to same session))
# Receive from a sessionwith client.get_queue_receiver("orders", session_id="customer-123") as receiver: for msg in receiver.receive_messages(): # guaranteed ordered for this session process(msg) receiver.complete_message(msg)Dead-Letter Queue
Section titled “Dead-Letter Queue”Messages that fail processing repeatedly (up to maxDeliveryCount) are moved to the DLQ:
# Read from the dead-letter queuewith client.get_queue_receiver("orders", sub_queue="deadletter") as receiver: for msg in receiver.receive_messages(): print(f"Failed message: {msg}, reason: {msg.dead_letter_reason}")Service Bus Tiers
Section titled “Service Bus Tiers”| Tier | Features | Throughput | Cost |
|---|---|---|---|
| Basic | Queues only, no topics | Low | ~$0.05/million ops |
| Standard | Queues + topics, sessions, transactions | Moderate | ~$10/month + ops |
| Premium | Dedicated resources, VNet, large messages (100 MB) | High, predictable | ~$670/month per MU |
Subscription Filters
Section titled “Subscription Filters”Filter which messages a subscription receives:
# SQL filter: only high-value ordersaz servicebus topic subscription rule create \ --resource-group myapp-rg \ --namespace-name myapp-bus \ --topic-name order-events \ --subscription-name payments \ --name high-value \ --filter-sql-expression "amount > 100"
# Correlation filter: match on propertiesaz servicebus topic subscription rule create \ --resource-group myapp-rg \ --namespace-name myapp-bus \ --topic-name order-events \ --subscription-name inventory \ --name all-orders \ --filter-sql-expression "1=1"Event Grid
Section titled “Event Grid”Event Grid is a fully managed event routing service — lightweight, push-based, and designed for reacting to events from Azure resources or your applications.
How Event Grid Works
Section titled “How Event Grid Works”Event Source ──► Event Grid Topic ──► Subscription (filter) ──► Event Handler Subscription ──► Event Handler- An event source publishes events (Azure resource or your app).
- Events are routed through a topic.
- Subscriptions filter events and push them to handlers.
Built-In Azure Resource Events
Section titled “Built-In Azure Resource Events”Many Azure services publish events to Event Grid automatically:
| Source | Example Events |
|---|---|
| Blob Storage | Blob created, deleted |
| Resource Groups | Resource created, deleted, updated |
| Azure subscriptions | Resource write/delete operations |
| Container Registry | Image pushed, deleted |
| Key Vault | Secret expiring, certificate renewed |
| IoT Hub | Device connected, telemetry received |
| Media Services | Job completed, encoding finished |
Event Grid Handlers (Destinations)
Section titled “Event Grid Handlers (Destinations)”| Handler | Use Case |
|---|---|
| Azure Functions | Process event with serverless code |
| Event Hubs | Stream events for analytics |
| Service Bus Queue/Topic | Buffer for reliable processing |
| Storage Queue | Simple buffering |
| Webhook | Send to any HTTP endpoint |
| Logic Apps | Low-code workflow |
| Power Automate | Business process automation |
Example: React to Blob Uploads
Section titled “Example: React to Blob Uploads”# Subscribe to blob-created events → trigger a Functionaz eventgrid event-subscription create \ --name process-uploads \ --source-resource-id /subscriptions/<sub>/resourceGroups/myapp-rg/providers/Microsoft.Storage/storageAccounts/mystorage \ --included-event-types Microsoft.Storage.BlobCreated \ --endpoint /subscriptions/<sub>/resourceGroups/myapp-rg/providers/Microsoft.Web/sites/my-func-app/functions/processBlob \ --endpoint-type azurefunction \ --subject-begins-with /blobServices/default/containers/uploads/Custom Topics (Your Own Events)
Section titled “Custom Topics (Your Own Events)”# Create a custom topicaz eventgrid topic create \ --resource-group myapp-rg \ --name myapp-events \ --location eastusfrom azure.eventgrid import EventGridPublisherClientfrom azure.core.messaging import CloudEventfrom azure.identity import DefaultAzureCredential
client = EventGridPublisherClient( "https://myapp-events.eastus-1.eventgrid.azure.net/api/events", DefaultAzureCredential())
client.send([CloudEvent( source="myapp/orders", type="Order.Placed", data={"order_id": 123, "amount": 49.99, "customer": "alice"})])Event Grid vs Service Bus
Section titled “Event Grid vs Service Bus”| Event Grid | Service Bus | |
|---|---|---|
| Model | Push (event notification) | Pull (message processing) |
| Delivery | At-least-once, push to handler | At-least-once or exactly-once (peek-lock) |
| Ordering | No guarantee | FIFO with sessions |
| Retention | 24 hours (retry) | Up to 14 days (Standard) or unlimited (Premium) |
| Message size | 1 MB (Cloud Events) | 256 KB (Standard), 100 MB (Premium) |
| Features | Filtering, retry, dead-letter | Sessions, transactions, dead-letter, scheduling |
| Best for | Reacting to events (lightweight) | Reliable message processing (heavyweight) |
When to Use Which
Section titled “When to Use Which”| Scenario | Choose |
|---|---|
| React to Azure resource changes (blob uploaded, VM created) | Event Grid |
| Reliable task queue with ordering | Service Bus Queue |
| Fan-out one event to multiple consumers with filters | Service Bus Topic |
| Lightweight event notifications (webhooks) | Event Grid |
| Enterprise messaging (sessions, transactions, dead-letter) | Service Bus |
| Simple, high-volume queue (no advanced features) | Queue Storage |
| High-throughput streaming / telemetry | Event Hubs |
Key Takeaways
Section titled “Key Takeaways”- Service Bus is for reliable enterprise messaging — queues (point-to-point) and topics (pub/sub) with sessions, dead-letter, transactions, and scheduling.
- Event Grid is for lightweight event routing — react to Azure resource events or publish custom events with push delivery to handlers.
- Use Service Bus when you need guaranteed delivery, ordering, or advanced processing features.
- Use Event Grid when you need to react to events quickly with minimal infrastructure.
- Both integrate natively with Azure Functions for serverless event processing.