Azure Service Bus Queues: Send, Receive and Settle Messages
30-second answer
An Azure Service Bus queue holds messages until one receiver takes each one, so a web API can hand slow AI work to a background worker. In Python you create a ServiceBusClient with the fully qualified namespace and DefaultAzureCredential, send a ServiceBusMessage with a queue sender, and read with a queue receiver. In the default peek-lock mode the receiver must complete the message when it's done; abandon makes it available again, and after the max delivery count (10 by default) it goes to the dead-letter queue.
Simulate it » No Azure account neededExam objective: 3.1.1 Queue and process back-end operations by using Azure Service Bus, including dead-letter queue handling, messages, topics, and subscriptions. (Skills measured as of October 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
Open <strong>Service Bus</strong> and select <strong>+ Create</strong> to make a namespace.
👆 Click the glowing item in the portal to continue
Read the steps as text
- Open Service Bus and select + Create to make a namespace.
- Choose Standard. Basic can’t do topics, and you’ll want them next.
- Review and Create.
- In the namespace, open Entities → Queues and select + Queue.
- Max delivery count is how many tries a message gets before it moves to the dead-letter queue. Lock duration is how long a receiver has to finish.
- Open the queue’s Service Bus Explorer and send a test order.
- Peek reads messages without locking or removing them. Handy for debugging; workers use receive with peek-lock.
- Open a message to see its body and properties. A worker calls complete when done, or abandon to let it come back later.
🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.
🖱️ Drag to rotate · scroll or pinch to zoom
Service Bus queue: peek-lock
An Azure Service Bus queue hands each message to one receiver. In peek-lock mode the message is locked, not removed. The worker completes it when done, or abandons it so it can be tried again. If the worker crashes, the lock expires and the message comes back.
🤔 What happens if…
Read this tour as text
- Don’t make users wait. Summarising a 40-page PDF takes a minute. If the web API does it inline, requests pile up and time out. Put a message on a queue instead, reply "accepted", and let a worker do the slow part.
- Service Bus queue: peek-lock. An Azure Service Bus queue hands each message to one receiver. In peek-lock mode the message is locked, not removed. The worker completes it when done, or abandons it so it can be tried again. If the worker crashes, the lock expires and the message comes back.
- Dead-letter queue. A poison message fails every time. After max delivery count attempts (10 by default) Service Bus moves it to the dead-letter queue (DLQ), a sub-queue you read, fix and resubmit. Expired messages can go there too.
- Topics and subscriptions. A topic is a queue with many readers. Each subscription gets its own copy of every message, and filters (SQL or correlation) decide which messages a subscription keeps. One "document uploaded" message can feed indexing, billing and audit.
- Event Grid: something happened. Azure Event Grid pushes events (small facts: "blob created") to handlers. You can publish custom events to a custom topic. Event subscriptions pick the handler, and filters (event type, subject begins/ends with, advanced) cut out the noise.
- Event Grid retries. If the handler is down, Event Grid retries with exponential backoff, by default up to 30 attempts within 24 hours (you can lower both). After that it drops the event, unless you configured dead-lettering to a storage container.
- Functions: triggers and bindings. An Azure Function runs when its trigger fires: HTTP, Service Bus, Event Grid, timer, Cosmos DB and more. Bindings connect inputs and outputs without client code: an HTTP-triggered API can write a message to a queue with an output binding.
- Functions scale with the work. On the Flex Consumption plan a function app adds instances as messages arrive and scales to zero when idle. Premium keeps warm instances to avoid cold starts. Settings live in app settings, and you deploy a zip package or a container.
Send orders through a queue, find out what happens to a message your code can't read, then fan orders out to a topic where one subscription only wants the big ones.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
Uploads time out while the API summarises each PDF.
😊 THE SOLUTION
Queue the job in Service Bus and let a worker finish it.
- Requests time out✓ Reply fast, process later
- Worker crashes mid-job✓ Peek-lock redelivers
- Duplicate sends✓ Duplicate detection
Start with a question
Why does the upload page freeze every time someone sends a big PDF?
Picture a busy photocopy shop. If the person at the counter made every copy while you stood there, the queue out the door would never move. Instead they take your order, give you a token and say “come back in ten minutes”. The copying happens at the back.
Your AI app has the same problem. Summarising a 40-page PDF takes a minute. If the web API does it inline, requests pile up and time out. An Azure Service Bus queue is the token system: the API drops a job on the queue, replies straight away, and a worker at the back does the slow part.
Explain it like I’m 10
Visual: a Service Bus queue in motion
Follow three jobs through a queue in peek-lock mode, including one that ends up in the dead-letter queue.
Read the video script
- Reply now, work laterThree PDFs get uploaded. Instead of summarising while the user waits, the API sends one message per file to a Service Bus queue and replies 202 Accepted.
- Peek-lock: take it, keep it lockedWorker A receives invoice-42 in peek-lock mode. It isn't deleted. It stays in the queue, locked to Worker A for a minute by default and hidden from other workers.
- Complete: gone for goodWorker A saves the summary, then calls complete. Only now is the message removed. If the worker had died halfway, the job would still be there.
- Abandon: back in the queueWorker B takes contract-88, hits a temporary error and abandons it. The lock's released, the message is back for anyone, and its delivery count goes up by one.
- A crash? The lock runs outNow Worker A takes it and crashes before settling. Nobody has to tell Service Bus. When the lock runs out, the message reappears and the count goes up again.
- Ten tries, then dead-lettercontract-88 keeps failing. After ten deliveries, the default max, Service Bus moves it to the dead-letter queue so it can't cycle forever. You inspect it there and fix the cause.
- Built for at-least-oncePeek-lock never loses a job, but a job can arrive twice, say if a worker crashes right after finishing. So make running it twice harmless, like an upsert keyed on the document id.
The technical explanation
Service Bus is a message broker. You create a namespace (contoso-ai.servicebus.windows.net) and inside it one or more queues. A queue keeps messages in the order they arrived and hands each message to one receiver. If you run five workers on the same queue, they compete and share the load.
Pick a tier
| Tier | What you get | Use it for |
|---|---|---|
| Basic | Queues only. No topics, sessions, transactions or duplicate detection. | Simple dev/test or one-way job queues |
| Standard | Queues and topics, sessions, duplicate detection, transactions. Shared capacity, messages up to 256 KB. | Most apps |
| Premium | Dedicated messaging units, predictable latency, larger messages, network isolation. | Production with steady high volume |
Send a message
Install azure-servicebus and azure-identity. Give the sender the Azure Service Bus Data Sender role, then sign in with Microsoft Entra ID instead of a connection string:
import json
from azure.identity import DefaultAzureCredential
from azure.servicebus import ServiceBusClient, ServiceBusMessage
NAMESPACE = "contoso-ai.servicebus.windows.net"
credential = DefaultAzureCredential()
with ServiceBusClient(fully_qualified_namespace=NAMESPACE, credential=credential) as client:
with client.get_queue_sender(queue_name="summarise-jobs") as sender:
msg = ServiceBusMessage(
json.dumps({"docId": "invoice-42", "blob": "uploads/invoice-42.pdf"}),
content_type="application/json",
subject="summarise",
message_id="invoice-42", # used by duplicate detection
application_properties={"tier": "premium"},
)
sender.send_messages(msg)
You can pass a list of messages, or build a batch with sender.create_message_batch() so you don’t go over the size limit.
Receive and settle
The worker gets the Azure Service Bus Data Receiver role. In the default peek-lock mode, each message you receive is locked for you and stays in the queue until you settle it:
with ServiceBusClient(fully_qualified_namespace=NAMESPACE, credential=credential) as client:
with client.get_queue_receiver(queue_name="summarise-jobs", max_wait_time=5) as receiver:
for msg in receiver.receive_messages(max_message_count=10, max_wait_time=5):
job = json.loads(str(msg))
try:
summarise(job["blob"])
receiver.complete_message(msg) # done, remove it
except TemporaryError:
receiver.abandon_message(msg) # unlock, try again later
except BadInputError as e:
receiver.dead_letter_message(msg, reason="BadInput", error_description=str(e))
| Settlement | What happens |
|---|---|
complete_message | The message is removed from the queue. |
abandon_message | The lock is released and the message is available again. Delivery count goes up by one. |
dead_letter_message | The message moves to the queue’s dead-letter sub-queue with your reason. |
defer_message | The message stays in the queue but is set aside. You fetch it later with receive_deferred_messages(sequence_numbers=[...]). |
If you don’t settle in time, the lock duration runs out (1 minute by default, 5 minutes at most) and the message becomes visible to other receivers. Long jobs should renew the lock, for example with AutoLockRenewer, rather than relying on a huge lock. Every time a message is delivered its delivery count goes up. When it passes the max delivery count (10 by default), Service Bus moves it to the dead-letter queue.
Receive-and-delete (receive_mode=ServiceBusReceiveMode.RECEIVE_AND_DELETE) skips the lock and removes the message on delivery. It’s faster but a crash loses the message. Use it only for data you can afford to drop, such as live telemetry samples.
-
1 Send
The API sends a ServiceBusMessage and replies 202 Accepted.
-
2 Lock
A worker receives it. Other workers can't see it while the lock lasts.
-
3 Work
The worker summarises the PDF, renewing the lock if it takes long.
-
4 Settle
complete removes it. abandon or a lost lock sends it back for another try.
Queue settings worth knowing
- Message time to live (TTL): a message that isn’t processed in time expires. Set it per message (
time_to_live) or as a queue default. Turn on dead-lettering on message expiration if you want expired messages kept instead of dropped. - Sessions: turn on requires session when you create the queue, then set
session_idon each message. One receiver locks a whole session at a time, so all messages forcustomer-17are handled in order. Receive withclient.get_queue_receiver(queue_name=..., session_id="customer-17"). - Duplicate detection: turn it on when you create the queue and choose a window (10 minutes by default). A second message with the same
message_idinside the window is quietly dropped, which protects you when a sender retries after a timeout. - Scheduled messages: set
scheduled_enqueue_time_utcor callsender.schedule_messages()to deliver later. - Peek:
receiver.peek_messages()reads messages without locking them. Handy for debugging.
Architect level At-least-once means your handler must be idempotent
Peek-lock gives you at-least-once delivery. A worker can finish the summary, then crash before complete_message reaches Service Bus. The lock expires and another worker processes the same job again. So design for repeats: write the summary with an upsert keyed on docId, or check a “processed” marker before doing paid model calls. Duplicate detection only stops duplicate sends; it doesn’t stop a message being delivered twice.
For high throughput, use the async client in azure.servicebus.aio, receive in batches, and set prefetch_count so the next messages are already on their way while you work. Keep prefetch modest with long jobs, because prefetched messages are locked too and their locks keep ticking.
Real-world business scenario
Fabrikam Legal (fictional)
- The problem
- Lawyers uploaded contracts for an AI summary and the web app timed out whenever a 100-page contract arrived during the morning rush.
- What they used
- The upload API now sends a ServiceBusMessage to a summarise-jobs queue on the Standard tier and returns 202 Accepted. Three Python workers receive in peek-lock mode with managed identities, renew locks on long contracts and complete each message after saving the summary.
- Why that choice
- The queue absorbs the morning burst, peek-lock means a crashed worker never loses a contract, and duplicate detection stops a retried upload from being summarised (and billed) twice.
- The result
- Uploads return in under a second, summaries arrive a minute or two later, and the team scales workers instead of making the web tier bigger.
When to use it and when not to
✓ Use it when…
- A web API needs to hand slow or bursty AI work to a background worker.
- Each job must be processed once by one worker, and must not be lost if a worker fails.
- You need ordering per customer (sessions), duplicate protection or scheduled delivery.
✕ Think twice when…
- Several different systems each need their own copy of the message. Use a topic with subscriptions.
- You only want to announce that something happened, like a blob being created. Event Grid fits better.
- You need to stream millions of telemetry events per second for analytics. That's Azure Event Hubs.
↔ Alternatives to consider
- Service Bus topics for one message, many independent readers.
- Azure Queue Storage for very simple, cheap queues without sessions or dead-lettering features.
- Azure Event Grid for reactive, push-style event notifications.
Test yourself with exercises
5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner Why would an AI web API put work on a Service Bus queue instead of doing it straight away?
Model answer
Because some AI work is slow. Summarising a long PDF can take a minute, and an HTTP request shouldn't hang that long. The API drops a message on the queue, replies "accepted" right away, and a worker processes the job at its own pace. If the worker is down, the messages wait in the queue instead of being lost.
Interviewer follows up
What happens if the worker crashes halfway through a message?
You
In peek-lock mode nothing is lost. The lock expires after the lock duration and the message becomes visible again, so another worker picks it up. Its delivery count goes up by one.
Intermediate What's the difference between peek-lock and receive-and-delete?
Model answer
Peek-lock locks the message and waits for me to settle it: complete, abandon, dead-letter or defer. Receive-and-delete removes it the moment it's handed over. It's a bit faster, but if my code crashes after receiving, that message is gone. For anything that matters, like a paid summarisation job, I use peek-lock.
Experienced developer How would you authenticate a Python worker to Service Bus without a connection string?
Model answer
I'd create the ServiceBusClient with fully_qualified_namespace set to mynamespace.servicebus.windows.net and DefaultAzureCredential. In Azure the worker's managed identity gets the Azure Service Bus Data Receiver role on the queue, and the API that sends gets Azure Service Bus Data Sender. Locally the same code uses my az login.
Scenario Your worker takes about three minutes per document and you keep seeing the same document processed twice. What's going on?
Model answer
The lock is expiring before the worker finishes. The default lock duration is one minute, so the message becomes visible again and a second worker grabs it. I'd raise the lock duration (up to five minutes), renew the lock while processing with AutoLockRenewer, and make the handler idempotent so a repeat does no harm.
Quick revision
Key points
- A queue delivers each message to one receiver (competing consumers).
- ServiceBusClient(fully_qualified_namespace, DefaultAzureCredential()) then get_queue_sender and get_queue_receiver.
- Peek-lock is the default. Settle with complete_message, abandon_message, dead_letter_message or defer_message.
- Lock duration defaults to 1 minute (max 5). Max delivery count defaults to 10, then the message is dead-lettered.
- Sessions give ordered handling per session ID. Duplicate detection drops repeats by MessageId. Basic tier has queues only.
Important terminology
- Service Bus namespace
- The container for queues and topics, reached at <name>.servicebus.windows.net, with a pricing tier of Basic, Standard or Premium.
- Queue
- A Service Bus entity that stores messages in order and delivers each message to one competing receiver.
- Peek-lock
- The default receive mode. The message is locked for the receiver and only removed when the receiver completes it.
- Receive-and-delete
- A receive mode that removes the message as soon as it's delivered, so a crash loses it.
- Lock duration
- How long a peek-locked message stays hidden from other receivers. The default is 1 minute and the maximum is 5 minutes.
- Max delivery count
- How many times a message can be delivered before Service Bus moves it to the dead-letter queue. The default is 10.
- Message session
- A group of messages that share a session ID and are handled in order by one receiver at a time.
- Duplicate detection
- A queue option that drops a second message with the same MessageId sent within the detection window.
Common mistakes
- Forgetting to complete the message in peek-lock mode, so it comes back again and again until it's dead-lettered.
- Choosing receive-and-delete for work that can't be lost.
Exam tips
- "Message must not be lost if the worker fails" = peek-lock, then complete after processing.
- "Process messages for one customer in order" = sessions (session ID).
- "Basic tier" can't do topics, sessions or duplicate detection.
Five quick revision questions
-
1.What is the default receive mode in Service Bus?Show
Peek-lock.
-
2.What is the default max delivery count?Show
10.
-
3.What is the default lock duration?Show
1 minute (maximum 5 minutes).
-
4.Which method makes a locked message available again straight away?Show
abandon_message.
-
5.Which role does a worker need to read messages with Entra ID?Show
Azure Service Bus Data Receiver.
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: Service Bus Topics, Subscriptions and Dead-Letter Queues
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.