Skip to content

Service Bus and Event Grid

First PublishedByAtif Alam

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.

ServiceModelBest ForAWS Equivalent
Service Bus QueuePoint-to-pointTask processing, ordered workloadsSQS
Service Bus TopicPub/Sub (fan-out)Broadcasting to multiple subscribersSNS + SQS
Event GridEvent routing (push)Reacting to Azure resource events, custom eventsEventBridge
Queue StorageSimple queueBasic queueing (high volume, low feature)SQS (basic)
Event HubsStreamingHigh-throughput telemetry, logsKinesis

Service Bus is Azure’s enterprise message broker — feature-rich, reliable, and designed for mission-critical workloads.

Producer ──send──► [ msg3 msg2 msg1 ] ──receive──► Consumer
Service Bus Queue

One producer, one consumer. Messages are processed exactly once (peek-lock) or at-least-once (receive-and-delete).

Producer ──publish──► Topic: order-events
├──► Subscription: payments (filter: amount > 100) ──► Payment service
├──► Subscription: inventory (all messages) ──► Inventory service
└──► Subscription: analytics (all messages) ──► Analytics Lambda

A topic broadcasts messages to multiple subscriptions. Each subscription gets its own copy and can have filters to receive only relevant messages.

Terminal window
# Create namespace (container for queues and topics)
az servicebus namespace create \
--resource-group myapp-rg \
--name myapp-bus \
--sku Standard \
--location eastus
# Create a queue
az 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 subscriptions
az 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 inventory
from azure.servicebus import ServiceBusClient, ServiceBusMessage
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
client = ServiceBusClient("myapp-bus.servicebus.windows.net", credential)
# Send
with 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")
FeatureWhat It Does
Peek-lockMessage is locked while processing; auto-unlocks on timeout if not completed
Dead-letter queue (DLQ)Failed messages move here after max delivery attempts
SessionsGroup related messages and process in order (e.g. all messages for one customer)
Scheduled deliveryEnqueue a message now, deliver at a future time
Duplicate detectionReject duplicate messages (by message ID, within a time window)
TransactionsSend/complete multiple messages atomically
Auto-forwardingAutomatically forward messages from one queue/subscription to another
Message deferralSet a message aside and retrieve it later by sequence number

Sessions guarantee FIFO ordering for messages with the same session ID:

# Send with session ID
sender.send_messages(ServiceBusMessage(
body='{"step": 1}',
session_id="customer-123" # all messages for this customer go to same session
))
# Receive from a session
with 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)

Messages that fail processing repeatedly (up to maxDeliveryCount) are moved to the DLQ:

# Read from the dead-letter queue
with 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}")
TierFeaturesThroughputCost
BasicQueues only, no topicsLow~$0.05/million ops
StandardQueues + topics, sessions, transactionsModerate~$10/month + ops
PremiumDedicated resources, VNet, large messages (100 MB)High, predictable~$670/month per MU

Filter which messages a subscription receives:

Terminal window
# SQL filter: only high-value orders
az 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 properties
az 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 is a fully managed event routing service — lightweight, push-based, and designed for reacting to events from Azure resources or your applications.

Event Source ──► Event Grid Topic ──► Subscription (filter) ──► Event Handler
Subscription ──► Event Handler
  1. An event source publishes events (Azure resource or your app).
  2. Events are routed through a topic.
  3. Subscriptions filter events and push them to handlers.

Many Azure services publish events to Event Grid automatically:

SourceExample Events
Blob StorageBlob created, deleted
Resource GroupsResource created, deleted, updated
Azure subscriptionsResource write/delete operations
Container RegistryImage pushed, deleted
Key VaultSecret expiring, certificate renewed
IoT HubDevice connected, telemetry received
Media ServicesJob completed, encoding finished
HandlerUse Case
Azure FunctionsProcess event with serverless code
Event HubsStream events for analytics
Service Bus Queue/TopicBuffer for reliable processing
Storage QueueSimple buffering
WebhookSend to any HTTP endpoint
Logic AppsLow-code workflow
Power AutomateBusiness process automation
Terminal window
# Subscribe to blob-created events → trigger a Function
az 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/
Terminal window
# Create a custom topic
az eventgrid topic create \
--resource-group myapp-rg \
--name myapp-events \
--location eastus
from azure.eventgrid import EventGridPublisherClient
from azure.core.messaging import CloudEvent
from 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 GridService Bus
ModelPush (event notification)Pull (message processing)
DeliveryAt-least-once, push to handlerAt-least-once or exactly-once (peek-lock)
OrderingNo guaranteeFIFO with sessions
Retention24 hours (retry)Up to 14 days (Standard) or unlimited (Premium)
Message size1 MB (Cloud Events)256 KB (Standard), 100 MB (Premium)
FeaturesFiltering, retry, dead-letterSessions, transactions, dead-letter, scheduling
Best forReacting to events (lightweight)Reliable message processing (heavyweight)
ScenarioChoose
React to Azure resource changes (blob uploaded, VM created)Event Grid
Reliable task queue with orderingService Bus Queue
Fan-out one event to multiple consumers with filtersService 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 / telemetryEvent Hubs
  • 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.