Service Bus & Event Grid
queues · topics and subscriptions · peek-lock and settlement · dead-letter queues · rules and filters · Event Grid custom topics, filters and retries
By the tools4free.dev team · Last reviewed November 13, 2026
Practice questions for this topic →
Service Bus queues, topics and subscriptions
| Queue | Topic and subscriptions | |
|---|---|---|
| Pattern | Point-to-point | Publish/subscribe (one-to-many) |
| Delivery | Single consumer per message (competing consumers) | Each subscription receives a copy |
| Filtering | Not supported | Subscription rules and filters |
| Typical use | Task distribution, load leveling | Event broadcasting, fan-out |
- Queues offer First In, First Out (FIFO) delivery to one or more competing consumers, and only one consumer receives and processes each message. Sessions give the FIFO guarantee for ordered processing.
- A sender sends to a topic exactly as to a queue. Consumers do not receive from the topic: they receive from its subscriptions, each a virtual queue that holds a copy.
- By default a subscription receives all messages sent to the topic; filters narrow that.
- Other features named on the overview page: autoforwarding (chain a queue or subscription to a queue or topic in the same namespace), scheduled delivery, message deferral, transactions, duplicate detection and auto-delete on idle.
Receive modes
| Mode | What happens | Failure result |
|---|---|---|
| Receive and delete | The message is settled when the broker sends it | A consumer crash before processing loses the message (at-most-once) |
| Peek lock | Two stages: the message is locked, then you settle it | A crash after processing but before completing leads to redelivery (at-least-once) |
Send and receive with the Python SDK
The Python quickstarts use the azure-servicebus package. The passwordless tab creates DefaultAzureCredential() (from azure.identity.aio) and passes it to ServiceBusClient with the fully qualified namespace.
| Task | Call |
|---|---|
| Queue sender | servicebus_client.get_queue_sender(queue_name=QUEUE_NAME) |
| Topic sender | servicebus_client.get_topic_sender(topic_name=TOPIC_NAME) |
| Send one message | message = ServiceBusMessage("Single Message") then await sender.send_messages(message) |
| Send a batch | batch_message = await sender.create_message_batch(), then batch_message.add_message(...); a ValueError means the batch reached max_size |
| Queue receiver | servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME) |
| Subscription receiver | servicebus_client.get_subscription_receiver(topic_name=TOPIC_NAME, subscription_name=SUBSCRIPTION_NAME, max_wait_time=5) |
| Receive | await receiver.receive_messages(max_wait_time=5, max_message_count=20) |
| Settle (complete) | await receiver.complete_message(msg) removes the message from the queue |
The quickstart receiver reads until no new message arrives for 5 seconds (max_wait_time).
Settlement, locks and dead-letter queues
| Settlement | Effect in peek-lock mode |
|---|---|
| Complete | Success: the message is removed from the queue or subscription |
| Abandon | Releases and unlocks the message at once so it can be delivered again |
| Let the lock expire | The message goes back to the front of the retrieval order for redelivery |
| Dead-letter | Moves the message to the dead-letter queue; you can set a reason code |
| Renew lock | The lock owner extends the lock (for example RenewMessageLockAsync in .NET) |
- Default lock duration is 1 minute; the maximum is 5 minutes, so renew the lock for longer processing.
- Settle a message while the receiver and its connection are open. If you close the receiver first, the settlement does not reach the service, the lock expires and the message is redelivered.
- Max delivery count defaults to 10. When the delivery count exceeds it, the message moves to the DLQ with reason
MaxDeliveryCountExceeded. This cannot be disabled; you can set a large number. - Duplicate deliveries are identified by checking
message-id; design handlers to be idempotent.
Dead-letter queue (DLQ)
- Each queue and each subscription has its own DLQ sub-queue. It needs no explicit creation and cannot be deleted or managed independently of the main entity.
- Paths:
<queue path>/$deadletterqueueand<topic path>/Subscriptions/<subscription path>/$deadletterqueue. There is no topic-level DLQ count: count messages on the subscription's DLQ. - Messages enter the DLQ from the engine (for example
TTLExpiredException,MaxDeliveryCountExceeded,HeaderSizeExceeded,MaxTransferHopCountExceeded) or when the application dead-letters them (for example malformed payloads). - Expiring messages go to the DLQ when dead-lettering is enabled on the queue or subscription. Deferred messages are not purged to the DLQ when they expire.
- The DLQ is not cleaned up automatically: messages stay until you retrieve them and complete them. Time-to-live is not observed in the DLQ, and you cannot dead-letter a message from a DLQ.
- Messages that cannot be forwarded in autoforward or send-via scenarios go to the transfer dead-letter queue (
$Transfer/$DeadLetterQueue) of the source entity that forwarded them, not the destination. The hop limit is 4.
Subscription rules and filters
A subscription has named rules. A rule has a filter condition and optionally an action that annotates the selected message. A new subscription gets a default rule with a true filter and no action, so it receives everything until you change it.
| Filter | Matches on | Notes |
|---|---|---|
| SqlFilter | SQL-like condition on user and system properties | System properties are prefixed with sys. |
| Boolean (TrueFilter, FalseFilter) | Everything / nothing | Derive from the SQL filter |
| CorrelationFilter | Equality on properties such as CorrelationId, ContentType, Label, MessageId, ReplyTo, SessionId, To and user-defined properties | Several properties combine with AND; string comparison is case-sensitive |
- Rules without actions are combined with OR and produce a single message on the subscription, even if several match.
- Each rule with an action produces its own copy of the message (with a
RuleNameproperty). Five matching rules, two with actions and three without, give three messages. - Filters evaluate message properties only; they cannot evaluate the message body.
Event Grid: events, topics and custom events
- An Event Grid topic holds events a publisher sends. Kinds: custom topics (your own endpoint), system topics (built in for Azure services such as Storage, Event Hubs and Service Bus) and partner topics.
- An event subscription tells Event Grid which events on a topic you want and where to send them; the endpoint can be a webhook or an Azure service resource. A subscription can have an expiration time.
- Event Grid supports push delivery (events sent to a destination in the event subscription) and pull delivery (subscribers read events; pull is supported for topics in a namespace).
- The Event Grid schema is proprietary and nonextensible; CloudEvents is the recommended format. An Event Grid-schema event has four required string properties. Maximum event size is 1 MB; events over 64 KB are charged in 64-KB increments; an oversize event or array returns 413 Payload Too Large.
- Events are posted to a topic in an array. Subscribers get an array with a single event by default.
Custom event quickstart, in order
- Create a resource group.
- Register the Event Grid resource provider if needed:
az provider register --namespace Microsoft.EventGrid. - Create the custom topic:
az eventgrid topic create --name $topicname -l westus2 -g gridResourceGroup. - Create the message endpoint (the quickstart deploys a web app).
- Subscribe the endpoint with
az eventgrid event-subscription create; Event Grid sends a validation event so the endpoint can confirm it wants events. - Get the topic endpoint and key, then POST the event with the header
aeg-sas-key.
- Custom topic names must be unique (they are part of DNS), 3-50 characters, and contain only a-z, A-Z, 0-9 and "-".
- The quickstart web app endpoint must end with
/api/updates/. - Sample event fields:
id,eventType,subject,eventTime,data(any well-formed JSON) anddataVersion.
Event Grid filters, retries and dead-lettering
| Filter option | Detail |
|---|---|
| Event types | Default: all event types of the source. Use includedEventTypes with an array, or All |
| Subject begins with / ends with | Simple prefix or suffix on the subject; design subjects as paths (for example /A/B/C) so subscribers can filter on /A |
| Advanced fields and operators | Operator type, key (number, boolean, string or array) and values; reach data fields with dot notation such as data.counter. Arrays need enableAdvancedFilteringOnArrays; arrays of objects are not supported |
| Retry setting | Range / default |
|---|---|
| Maximum number of attempts | 1 to 30; default 30 |
| Event time-to-live (TTL) | 1 to 1440 minutes; default 1440 minutes |
| Batching (off by default) | Max events per batch 1 to 5,000; preferred batch size 1 to 1,024 KB; all-or-none delivery |
- Delivery is at least once per matching subscription, with no ordering guarantee, so handlers must tolerate duplicates and out-of-order events.
- Event Grid waits 30 seconds for a response, then retries with exponential backoff on a best-effort schedule (10 seconds, 30 seconds, 1 minute, 5 minutes, 10 minutes, 30 minutes, 1 hour, 3 hours, 6 hours, then every 12 hours up to 24 hours). Retries have small randomization and might be skipped for consistently unhealthy endpoints.
- The event is dropped or dead-lettered when either limit (attempts or TTL) is reached, whichever comes first. TTL is checked only at the next scheduled delivery attempt.
- Errors that are not retried: 400 and 413 and 403 for Azure resource endpoints; 400, 413, 401 and 403 for webhooks. With a 400 or 413, Event Grid immediately schedules the event for dead-lettering; without dead-lettering configured, the event is dropped.
- Dead-lettering is off by default. Enable it by giving a storage account container when you create the event subscription. There is a five-minute delay between the last attempt and the write to the dead-letter location; if that location is unavailable for four hours, the event is dropped.
- With a managed identity for dead-lettering, give the identity the right RBAC role on the storage account.
- As an endpoint fails repeatedly, Event Grid delays later retries and new deliveries to it to protect the endpoint.
CLI and PowerShell
| Task | Azure CLI | PowerShell |
|---|---|---|
| Register the Event Grid provider | az provider register --namespace Microsoft.EventGrid | - |
| Create a custom topic | az eventgrid topic create --name $topicname -l westus2 -g gridResourceGroup | - |
| Get a custom topic key | az eventgrid topic key list --name $topicname -g gridResourceGroup --query "key1" --output tsv | - |
| Post a custom event | curl -X POST -H "aeg-sas-key: $key" -d "$event" $endpoint | - |
| Send one Service Bus message | - | await sender.send_messages(message) |
| Get a Service Bus queue receiver | - | receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME) |
| Receive messages | - | received_msgs = await receiver.receive_messages(max_wait_time=5, max_message_count=20) |
| Complete a message | - | await receiver.complete_message(msg) |
Exam Tips
Tick each tip once you can answer it without looking.
“One consumer must process each message; workers share the load” → Service Bus queue (competing consumers). Trap: A topic with subscriptions gives every subscription its own copy.
“Several back-end services each need a copy of every order message” → Topic with one subscription per service. Trap: Consumers read from subscriptions, not from the topic. A queue would split messages between them.
“A consumer crash before processing must not lose the message” → Peek lock mode, then complete. Trap: Receive and delete settles on send, so a crash loses the message.
“Message processing fails but may succeed on retry” → Abandon (or let the lock expire) so it is redelivered. Trap: Dead-letter is for messages that retrying will not fix. Delivery count rises with each abandon.
“Message keeps failing and reaches the max delivery count (default 10)” → It moves to the DLQ with reason MaxDeliveryCountExceeded. Trap: This behavior cannot be disabled; you can only raise the count.
“Read dead-lettered messages of a subscription” → <topic path>/Subscriptions/<subscription path>/$deadletterqueue. Trap: The topic has no DLQ count; the DLQ belongs to the subscription. Nothing empties the DLQ automatically.
“Messages that could not be auto-forwarded” → Transfer dead-letter queue of the source entity. Trap: They are not placed on the destination entity.
“Processing takes longer than the lock duration (default 1 minute, max 5)” → Renew the lock, or set a lock duration above normal processing time. Trap: Lock duration cannot exceed 5 minutes, so renewal is the way to go longer.
“Message was received but the receiver was closed before settling” → Settlement is lost; the lock expires and the message is redelivered (repeats lead to the DLQ). Trap: Settle before closing the receiver or client.
“Processed twice after a failed Complete” → Idempotent handler; check message-id. Trap: Peek lock is at-least-once, not exactly-once, unless you add duplicate handling or duplicate detection.
“FIFO ordered processing in a queue or subscription” → Message sessions. Trap: Queues deliver messages in order to competing consumers, but the overview names sessions as the way to realize the FIFO guarantee in processing.
“Subscription must receive only red orders; one message copy per matching rule with an action” → SQL or correlation filter rule; rules with actions each produce a copy. Trap: Rules without actions merge into one message. Filters cannot look at the message body.
“Match on CorrelationId and several properties together” → Correlation filter (properties combine with AND, string compare is case-sensitive). Trap: A SQL filter must prefix system properties with sys..
“Python: receive from a subscription” → get_subscription_receiver(topic_name=..., subscription_name=...), receive_messages, then complete_message. Trap: get_queue_receiver reads queues; get_topic_sender only sends.
“Event Grid retries a failing webhook” → Exponential backoff; max attempts 1-30 (default 30) and TTL 1-1440 minutes (default 1440); whichever expires first ends delivery. Trap: 400 and 413 responses are not retried; the event is dead-lettered if configured, otherwise dropped.
“Undelivered Event Grid events must be kept” → Configure dead-lettering with a storage account container on the event subscription. Trap: It is off by default, so the events are dropped. Writes happen five minutes after the last attempt.
“Only some Event Grid events to a subscriber” → Filter on event type, subject begins/ends with, or advanced fields (data.key with an operator). Trap: Array keys need enableAdvancedFilteringOnArrays; arrays of objects cannot be filtered.
“Publish your own application events to Event Grid” → Custom topic, event subscription, POST with aeg-sas-key. Trap: System topics are built in for Azure services. The endpoint first receives a subscription validation event.
Sources
- Service Bus queues, topics, and subscriptions
- Service Bus overview
- Service Bus dead-letter queues
- Message transfers, locks, and settlement
- Service Bus topic filters
- Service Bus queues (Python)
- Service Bus topics and subscriptions (Python)
- Event Grid delivery and retry
- Event Grid event filtering
- Send custom events with Event Grid and Azure CLI
- Event Grid concepts (push delivery)
- Event Grid event schema
- Introduction to Azure Event Grid
Checked against Microsoft Learn on November 13, 2026.