Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 20 of 28
❮Prev Next❯

Azure Service Bus Queues: Send, Receive and Settle Messages

Module 3: Messaging & Functions ⏱ 11 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    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 needed

    Exam 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.

    Azure portal: Create a Service Bus queue and send messages Create a namespace and a queue, then send and peek messages.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    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
    1. Open Service Bus and select + Create to make a namespace.
    2. Choose Standard. Basic can’t do topics, and you’ll want them next.
    3. Review and Create.
    4. In the namespace, open Entities → Queues and select + Queue.
    5. 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.
    6. Open the queue’s Service Bus Explorer and send a test order.
    7. Peek reads messages without locking or removing them. Handy for debugging; workers use receive with peek-lock.
    8. 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.

    😟 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
    🛠️ Solved with: Service Bus queues

    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.

    ▶ Explainer video See it in motion 7 steps · 1 min 30 sec

    An animation of an Azure Service Bus queue. An upload API sends three messages and replies 202 Accepted. Worker A receives invoice-42 in peek-lock mode, it stays locked in the queue, then complete removes it. Worker B abandons contract-88 so it returns with a higher delivery count, a crashed worker lets its lock expire, and after the default max delivery count of 10 the message moves to the dead-letter queue.
    Read the video script
    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. 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.
    6. 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.
    7. 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

    TierWhat you getUse it for
    BasicQueues only. No topics, sessions, transactions or duplicate detection.Simple dev/test or one-way job queues
    StandardQueues and topics, sessions, duplicate detection, transactions. Shared capacity, messages up to 256 KB.Most apps
    PremiumDedicated 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))
    SettlementWhat happens
    complete_messageThe message is removed from the queue.
    abandon_messageThe lock is released and the message is available again. Delivery count goes up by one.
    dead_letter_messageThe message moves to the queue’s dead-letter sub-queue with your reason.
    defer_messageThe 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. 1 Send

      The API sends a ServiceBusMessage and replies 202 Accepted.

    2. 2 Lock

      A worker receives it. Other workers can't see it while the lock lasts.

    3. 3 Work

      The worker summarises the PDF, renewing the lock if it takes long.

    4. 4 Settle

      complete removes it. abandon or a lost lock sends it back for another try.

    One job through a queue in peek-lock mode

    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_id on each message. One receiver locks a whole session at a time, so all messages for customer-17 are handled in order. Receive with client.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_id inside the window is quietly dropped, which protects you when a sender retries after a timeout.
    • Scheduled messages: set scheduled_enqueue_time_utc or call sender.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

    Legal services

    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.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    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.

    Question 1

    Question 1 of 5

    A Python worker receives summarization jobs from an Azure Service Bus queue. A job must not be lost if the worker process stops unexpectedly while it is processing the message. Which approach should you use?

    Question 2

    Question 2 of 5

    A function receives a message in peek-lock mode. A downstream model endpoint returns a temporary throttling error.

    You need the message to become available for another delivery attempt immediately. Which method should you call?

    Question 3

    Question 3 of 5

    You are creating an Azure Service Bus queue for order messages. Messages for the same customer must be processed in the order in which they were sent, while messages for different customers can be processed in parallel. What should you configure?

    Question 4

    Question 4 of 5 · Select 2

    A Python application must send messages to an Azure Service Bus queue by using Microsoft Entra ID authentication. No secrets can be stored in the application configuration. Which TWO actions should you perform?

    Question 5

    Question 5 of 5

    A worker takes approximately three minutes to process each message from a queue that uses the default settings. The same message is often processed by two workers. What is the most likely cause?

    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. 1.What is the default receive mode in Service Bus?Show

      Peek-lock.

    2. 2.What is the default max delivery count?Show

      10.

    3. 3.What is the default lock duration?Show

      1 minute (maximum 5 minutes).

    4. 4.Which method makes a locked message available again straight away?Show

      abandon_message.

    5. 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

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.