Your profile

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

Lesson 21 of 28
❮Prev Next❯

Service Bus Topics, Subscriptions and Dead-Letter Queues

Module 3: Messaging & Functions ⏱ 10 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

    A Service Bus topic is a queue with many readers: every subscription gets its own copy of each message, and filters decide which messages a subscription keeps. SQL filters use a condition such as tier = 'premium'; correlation filters match exact property values and are cheaper to evaluate. Messages that can't be processed land in the dead-letter queue (DLQ), a sub-queue you read in Python with sub_queue=ServiceBusSubQueue.DEAD_LETTER, fix and resubmit.

    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: Topics, filtered subscriptions and the dead-letter queue Add a topic, subscriptions with filters, and read the dead-letter queue.
    </> Embed

    Embed this simulation

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

    Loading the portal…

    A queue gives each message to <strong>one</strong> receiver. A topic gives a <strong>copy to every subscription</strong>. Select <strong>+ Topic</strong>.

    👆 Click the glowing item in the portal to continue

    Read the steps as text
    1. A queue gives each message to one receiver. A topic gives a copy to every subscription. Select + Topic.
    2. Name it order-events.
    3. Open the topic. billing gets every order; add a second subscription just for EU orders.
    4. Each subscription has its own max delivery count and its own dead-letter queue.
    5. Replace the default 1=1 rule with a SQL filter on a custom property. Now only EU orders land here.
    6. Send one order with region = EU and one with region = US. billing gets both; eu-orders gets one.
    7. A buggy worker failed one message 5 times, so Service Bus moved it to the dead-letter queue instead of retrying forever.
    8. Read DeadLetterReason and the error, fix the worker, then re-send. Nothing is lost while you investigate.

    🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.

    😟 THE PROBLEM

    One bad message blocks the worker all day.

    😊 THE SOLUTION

    Dead-letter it after a few tries, and fan out with topics.

    • Poison messages✓ Dead-letter queue
    • Three services need the event✓ Topic subscriptions
    • Each needs only some messages✓ SQL filters
    🛠️ Solved with: Topics and DLQ

    Start with a question

    One upload, three teams. How does each one hear about it?

    Think about a newspaper. The printer prints one edition, but every subscriber gets their own copy. The sports fan reads the cricket page, the investor reads business. Nobody has to fight over the single paper on the table.

    When a document lands in your AI app, the search indexer, the billing team and the audit log all want to know. A Service Bus topic works like that newspaper: one message in, a copy for every subscription. And when a message is broken beyond repair, it goes to a dead-letter queue where you can look at it instead of losing it.

    Explain it like I’m 10

    The technical explanation

    A topic accepts messages from senders exactly like a queue. The difference is on the receiving side: a topic has subscriptions, and each subscription behaves like its own queue with its own receivers, lock settings, max delivery count and dead-letter queue. Topics need the Standard or Premium tier; Basic has queues only.

    Send to a topic, read from a subscription

    from azure.identity import DefaultAzureCredential
    from azure.servicebus import ServiceBusClient, ServiceBusMessage
    
    NAMESPACE = "contoso-ai.servicebus.windows.net"
    
    with ServiceBusClient(NAMESPACE, DefaultAzureCredential()) as client:
        with client.get_topic_sender(topic_name="documents") as sender:
            sender.send_messages(ServiceBusMessage(
                '{"docId": "contract-88", "pages": 64}',
                subject="uploaded",
                application_properties={"tier": "premium", "pages": 64},
            ))
    
        with client.get_subscription_receiver(topic_name="documents",
                                              subscription_name="indexer") as receiver:
            for msg in receiver.receive_messages(max_message_count=20, max_wait_time=5):
                index_document(str(msg))
                receiver.complete_message(msg)

    Senders don’t know or care how many subscriptions exist. You can add a new reader next month without touching the sender.

    Filters decide what each subscription keeps

    Every new subscription starts with a rule called $Default: a true filter (1=1) that lets everything through. To be picky, add your own rule and remove $Default.

    FilterExampleNotes
    SQL filtertier = 'premium' AND pages > 20 or sys.Label LIKE 'invoice%'Conditions, comparisons, LIKE, IN. Application properties by name, system properties with sys.. Most flexible, most work for the broker.
    Correlation filtersubject = uploaded, tier = premiumExact-match on system properties (correlation ID, message ID, subject, content type, to, reply-to, session ID) and application properties. Cheaper and faster.
    True / False filter1=1 / 1=0Accept everything, or nothing.

    A SQL rule can also have an action that changes the copy for that subscription, such as SET priority = 'high'. If a message matches no rule on a subscription, that subscription simply doesn’t get it.

    az servicebus topic subscription rule create \
      --resource-group rg-ai --namespace-name contoso-ai \
      --topic-name documents --subscription-name billing \
      --name PremiumOnly --filter-sql-expression "tier = 'premium'"
    
    az servicebus topic subscription rule delete \
      --resource-group rg-ai --namespace-name contoso-ai \
      --topic-name documents --subscription-name billing --name '$Default'

    The dead-letter queue

    Every queue and every subscription has a dead-letter queue (DLQ), a sub-queue at <entity>/$deadletterqueue. Messages go there when:

    ReasonWhen
    MaxDeliveryCountExceededThe message was delivered more times than the max delivery count (10 by default). This is the classic poison message.
    TTLExpiredExceptionThe message expired and dead-lettering on message expiration is turned on.
    Filter evaluation errorA subscription rule threw an error for this message (on by default for subscriptions).
    Your own reasonYour code called dead_letter_message(msg, reason=..., error_description=...).

    Dead-lettered messages don’t expire and aren’t retried. They wait until you receive and complete them. You read a DLQ like any other queue:

    from azure.servicebus import ServiceBusSubQueue
    
    with ServiceBusClient(NAMESPACE, DefaultAzureCredential()) as client:
        dlq = client.get_subscription_receiver(
            topic_name="documents", subscription_name="indexer",
            sub_queue=ServiceBusSubQueue.DEAD_LETTER)
        sender = client.get_topic_sender(topic_name="documents")
        with dlq, sender:
            for msg in dlq.receive_messages(max_message_count=50, max_wait_time=5):
                print(msg.dead_letter_reason, msg.dead_letter_error_description)
                if can_fix(msg):
                    sender.send_messages(ServiceBusMessage(fix(msg),
                                         application_properties=msg.application_properties))
                    dlq.complete_message(msg)   # resubmitted, remove it from the DLQ
                else:
                    dlq.abandon_message(msg)    # leave it there for a person to check

    For a queue, it’s client.get_queue_receiver(queue_name="summarise-jobs", sub_queue=ServiceBusSubQueue.DEAD_LETTER).

    1. 1 Deliver

      The worker receives the message and fails on a corrupt PDF link.

    2. 2 Retry

      The lock expires or the worker abandons it. Delivery count goes up.

    3. 3 Give up

      Past the max delivery count, Service Bus moves it to the DLQ.

    4. 4 Fix

      You read the DLQ, fix the cause, resubmit a copy and complete the original.

    A poison message on its way to the DLQ
    Architect level Auto-forwarding and alerting on the DLQ

    You can set forward to on a subscription so its messages land in another queue or topic, which helps when one team owns a queue and another owns the topic. You can also set forward dead-lettered messages to so every DLQ in a system feeds one central queue that your support tooling reads.

    Don’t let a DLQ grow unnoticed. Azure Monitor exposes a dead-lettered message count metric for each entity; put a metric alert on it so the team hears about poison messages the same day. When you resubmit, send a new message; there’s no single “move back” call in the SDK. For a handful of messages, Service Bus Explorer in the portal can peek the DLQ and resend selected messages.

    Real-world business scenario

    Healthcare

    Northwind Health (fictional)

    The problem
    Scanned referral letters needed OCR, a billing record and an audit entry. Three teams had built three separate upload hooks, and a broken scan would quietly block one of them for hours.
    What they used
    One Service Bus topic, referrals, on the Standard tier. Subscriptions for ocr, billing (correlation filter on insurer = 'private') and audit (no filter). A metric alert watches each subscription's dead-letter count.
    Why that choice
    Each team reads its own copy at its own pace, filters keep billing away from public-insurance letters, and bad scans land in the DLQ with a reason instead of blocking the line.
    The result
    Adding a fourth consumer for analytics took one new subscription and no change to the upload code, and the support desk clears the DLQ each morning.

    When to use it and when not to

    ✓ Use it when…

    • One message needs to reach several independent consumers.
    • Different consumers want different subsets of messages, chosen by properties.
    • You need a safe place for messages that can't be processed, so you can inspect and resubmit them.

    ✕ Think twice when…

    • Only one worker pool processes each job. A queue is simpler.
    • You only broadcast lightweight "something happened" notifications to many handlers. Event Grid is cheaper and push-based.
    • You're on the Basic tier and can't upgrade. Topics aren't available there.

    ↔ Alternatives to consider

    • Service Bus queues for one consumer pool.
    • Azure Event Grid for push delivery of events with event-type and subject filters.
    • Azure Event Hubs for high-volume streams that many readers replay.
    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

    When a document is uploaded, an indexing service, a billing service, and an audit service must each receive and process their own copy of the same message. Which Azure Service Bus design should you use?

    Question 2

    Question 2 of 5

    A subscription named billing must receive only messages that have an application property named tier with the value premium. Message throughput is high, and filter evaluation must have the lowest possible overhead.

    Which type of rule should you add to the billing subscription?

    Question 3

    Question 3 of 5

    You add a SQL filter rule named PremiumOnly to an existing subscription. The subscription continues to receive every message published to the topic. What should you do?

    Question 4

    Question 4 of 5

    A Python support tool must read messages that were moved from the queue named jobs after they exceeded the maximum delivery count. How should the tool create its receiver?

    Question 5

    Question 5 of 5 · Select 2

    Which TWO conditions can cause Azure Service Bus to move a message to a dead-letter queue?

    Interview preparation

    Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.

    Beginner When would you choose a topic over a queue?

    Model answer

    When more than one system needs the same message. A "document uploaded" message might need to go to the indexer, the billing service and the audit log. With a queue, only one of them would get it. With a topic, each one has its own subscription and its own copy.

    Intermediate What's the difference between a SQL filter and a correlation filter?

    Model answer

    A SQL filter is a condition, so it can use comparisons, AND, OR, LIKE and so on, like pages > 20 AND tier = 'premium'. A correlation filter only checks that properties equal set values, such as subject equals "invoice" and tier equals "premium". Correlation filters are cheaper for the broker, so I use them when equality is enough.

    Interviewer follows up

    Why does a new subscription receive everything?

    You

    Because it starts with the $Default rule, which is a true filter. If I add my own filter, I remove $Default or the subscription keeps receiving every message.

    Experienced developer How do messages end up in a dead-letter queue?

    Model answer

    The common reasons are the delivery count going over the max delivery count (MaxDeliveryCountExceeded), a message expiring when dead-lettering on expiration is turned on, an error evaluating a subscription filter, or my code calling dead_letter_message with its own reason. Service Bus stamps DeadLetterReason and DeadLetterErrorDescription on the message so I can see why.

    Scenario Overnight, 300 messages piled up in a subscription's dead-letter queue. What would you do in the morning?

    Model answer

    Peek a few to read the dead-letter reason. If it's MaxDeliveryCountExceeded, I'd check the worker logs for the bug, fix and deploy it, then read the DLQ with sub_queue set to DEAD_LETTER, send a fresh copy of each message back to the topic and complete the dead-lettered one. Nothing moves out of a DLQ by itself, so if no one reads it, it just grows.

    Quick revision

    Key points

    • A topic copies each message to every subscription whose rules match.
    • New subscriptions start with the $Default true filter. Replace it with a SQL or correlation filter.
    • Correlation filters match exact values and are cheaper. SQL filters allow conditions like > and LIKE.
    • Every queue and subscription has its own DLQ, read with sub_queue=ServiceBusSubQueue.DEAD_LETTER.
    • Dead-lettered messages stay until you receive and complete them. Resubmit by sending a new copy.

    Important terminology

    Topic
    A Service Bus entity that accepts messages from senders and copies each one to every matching subscription.
    Subscription
    A named, queue-like view of a topic. Each subscription has its own receivers, settings and dead-letter queue.
    SQL filter
    A subscription rule written as a SQL-like condition on message properties, such as tier = 'premium' AND pages > 20.
    Correlation filter
    A subscription rule that matches exact values of system or application properties, faster to evaluate than a SQL filter.
    $Default rule
    The rule every new subscription starts with. It's a true filter (1=1) that accepts every message.
    Dead-letter queue (DLQ)
    A sub-queue of each queue and subscription that holds messages that couldn't be delivered or processed.
    Poison message
    A message that fails every time it's processed, for example because its data is corrupt.

    Common mistakes

    • Adding a filter but leaving the $Default rule, so the subscription still gets every message.
    • Expecting dead-lettered messages to retry or expire on their own.
    • Trying to create a topic on the Basic tier.

    Exam tips

    • "Each service needs its own copy of the message" = topic + subscriptions.
    • "Match exact property values, best performance" = correlation filter.
    • "Read messages that failed max delivery count" = dead-letter sub-queue.

    Five quick revision questions

    1. 1.Which tier doesn't support topics?Show

      Basic.

    2. 2.What filter does a new subscription start with?Show

      The $Default rule, a true filter (1=1).

    3. 3.Which filter type is cheapest to evaluate?Show

      Correlation filter.

    4. 4.Which Python argument opens a dead-letter queue?Show

      sub_queue=ServiceBusSubQueue.DEAD_LETTER.

    5. 5.What reason is stamped when the delivery limit is hit?Show

      MaxDeliveryCountExceeded.

    Official references

    Finished this lesson? Tick it off. Your progress is saved in this browser.

    Next up: Azure Event Grid: Custom Events, Filters and Retries

    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.