In this post we are going to cover dead-letter queues and poison messages in Azure Service Bus. These are 7 real Service Bus interview questions for data engineers, asked the way they come up on a real project, and the last one is a scenario: a partner sends malformed messages every night and the order pipeline stalls, and you make it resilient.
A dead-letter queue is where Service Bus puts a message that can't be processed, so the good messages keep flowing. A poison message is one that fails every time it's delivered. Interviewers ask about this because every real pipeline gets bad data sooner or later. What matters is what happens next: does the queue stall, does anyone notice, and how do we get the fixed messages processed again?
Part 5 of the Real Time Azure Service Bus Interview Questions and Answers series on TechBrothersIT.
- The short answer
- Let's set up the project
- Question 1: One bad message keeps failing and blocks the queue. How does dead-lettering help?
- Question 2: A teammate asks when Service Bus moves a message to the dead-letter queue by itself. What are the reasons?
- Question 3: The dead-letter queue fills up and nobody notices. How do you monitor and alert on it?
- Question 4: A bug is fixed and the dead-lettered messages must be processed. How do you resubmit them safely?
- Question 5: Someone asks whether expired messages go to the dead-letter queue. How do you control it?
- Question 6: Your manager asks when to retry and when to dead-letter. How do you classify errors?
- Scenario 7: A partner sends malformed messages every night and the order pipeline stalls. How do you make it resilient?
- The full script
The short answer
Every queue and subscription has a dead-letter queue. Service Bus moves a message there after the max delivery count, on expiry when that's enabled, and for a few other documented reasons, and your code can dead-letter bad data with its own reason. Alert on the DeadletteredMessages metric, and resubmit a copy only after the fix, to an idempotent consumer.
Let's set up the project
We run Microsoft's official Service Bus emulator locally, with SQL Server next to it, and small Python scripts that use the azure-servicebus client, so every output is real. Features the emulator doesn't support are shown as code. The emulator reads its queues from Config.json. orders has a max delivery count of 3, cart-reminders and price-updates have a 5 second time to live, and partner-orders forwards its dead-lettered messages to partner-errors. common.py has client() and props(), which decodes application properties.
{
"UserConfig": {
"Namespaces": [
{
"Name": "sbemulatorns",
"Queues": [
{
"Name": "orders",
"Properties": {
"DeadLetteringOnMessageExpiration": false,
"DefaultMessageTimeToLive": "PT1H",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "",
"ForwardTo": "",
"LockDuration": "PT1M",
"MaxDeliveryCount": 3,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
},
{
"Name": "payments",
"Properties": {
"DeadLetteringOnMessageExpiration": false,
"DefaultMessageTimeToLive": "PT1H",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "",
"ForwardTo": "",
"LockDuration": "PT1M",
"MaxDeliveryCount": 3,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
},
{
"Name": "cart-reminders",
"Properties": {
"DeadLetteringOnMessageExpiration": true,
"DefaultMessageTimeToLive": "PT5S",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "",
"ForwardTo": "",
"LockDuration": "PT1M",
"MaxDeliveryCount": 3,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
},
{
"Name": "price-updates",
"Properties": {
"DeadLetteringOnMessageExpiration": false,
"DefaultMessageTimeToLive": "PT5S",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "",
"ForwardTo": "",
"LockDuration": "PT1M",
"MaxDeliveryCount": 3,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
},
{
"Name": "partner-orders",
"Properties": {
"DeadLetteringOnMessageExpiration": false,
"DefaultMessageTimeToLive": "PT1H",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "partner-errors",
"ForwardTo": "",
"LockDuration": "PT1M",
"MaxDeliveryCount": 5,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
},
{
"Name": "partner-errors",
"Properties": {
"DeadLetteringOnMessageExpiration": false,
"DefaultMessageTimeToLive": "PT1H",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "",
"ForwardTo": "",
"LockDuration": "PT1M",
"MaxDeliveryCount": 3,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
}
],
"Topics": []
}
],
"Logging": {
"Type": "File"
}
}
}import os
from azure.servicebus import ServiceBusClient
def client():
return ServiceBusClient.from_connection_string(
os.environ["SERVICEBUS_CONNECTION_STRING"])
def props(msg):
"""Application properties: keys and text values come as bytes."""
return {k.decode(): v.decode() if isinstance(v, bytes) else v
for k, v in (msg.application_properties or {}).items()}Question 1: One bad message keeps failing and blocks the queue. How does dead-lettering help?
Dead-lettering moves the poison message out of the way. Every queue and subscription has a dead-letter queue, a secondary subqueue. When a message reaches the max delivery count, Service Bus moves it there, and good messages keep flowing.
Let's send five orders to the orders queue with python send_orders.py. Order 1003 has an amount with a comma, "49,90", which version 1 of our consumer can't parse. When processing fails, consume.py abandons the message, so it comes straight back. We run python consume.py.
import json
from azure.servicebus import ServiceBusMessage
from common import client
orders = [{"id": 1001, "amount": "25.00"},
{"id": 1002, "amount": "18.50"},
{"id": 1003, "amount": "49,90"}, # v1 can't parse it
{"id": 1004, "amount": "12.00"},
{"id": 1005, "amount": "99.99"}]
with client() as sb, sb.get_queue_sender("orders") as sender:
sender.send_messages([ServiceBusMessage(
json.dumps(o), message_id=f"order-{o['id']}",
subject="order.created") for o in orders])
print("sent", len(orders), "orders")import json, sys
from common import client, props
fixed = "--fixed" in sys.argv # the release with the fix
def amount(order):
text = order["amount"]
return float(text.replace(",", ".") if fixed else text)
done, tries = [], {}
with client() as sb, sb.get_queue_receiver("orders") as receiver:
while batch := receiver.receive_messages(max_message_count=10,
max_wait_time=3):
for msg in batch:
try:
amount(json.loads(str(msg))) # process the order
receiver.complete_message(msg)
note = (f" seq {msg.sequence_number} (resubmitted)"
if "resubmitted" in props(msg) else "")
done.append(msg.message_id + note)
except ValueError:
tries.setdefault(msg.message_id, []).append(
msg.delivery_count)
receiver.abandon_message(msg) # let it come back
print("completed:", sorted(done))
print("failed, delivery_count on each try:", tries)$ python send_orders.py
sent 5 orders
$ python consume.py
completed: ['order-1001', 'order-1002', 'order-1004', 'order-1005']
failed, delivery_count on each try: {'order-1003': [0, 1, 2]}Four orders are completed: order-1001, order-1002, order-1004 and order-1005. Order 1003 fails with delivery_count [0, 1, 2]. The queue's max delivery count is 3, so the third abandon moved it to the dead-letter queue.
| MaxDeliveryCount | Value |
|---|---|
| Azure default | 10 |
| Turn it off? | No: only raise it |
| This demo (emulator config) | 3 |
On Azure, the max delivery count defaults to 10, and we can't turn it off, only raise it. Three is just our demo setting in the emulator's config.
A consumer that crashes on the bad message and gets it again after every restart. Catch the error, settle the message, and let the dead-letter queue hold it.
Question 2: A teammate asks when Service Bus moves a message to the dead-letter queue by itself. What are the reasons?
Service Bus dead-letters a message by itself for a few documented reasons, and stores the reason with it. Our code can also dead-letter a message, with its own reason.
| Dead-letter reason | When |
|---|---|
| your own reason | your code calls dead_letter_message(msg, reason=..., error_description=...) |
| MaxDeliveryCountExceeded | the message could not be consumed within the max delivery count |
| TTLExpiredException | the message expired, and dead-lettering on expiration is on |
| MaxTransferHopCountExceeded | auto-forwarding went past the limit of 4 hops |
| HeaderSizeExceeded | the size quota for the stream was exceeded |
| Session ID is null | a session-enabled entity got a message with a null session ID |
Let's look at order 1003. dlq.py peeks the dead-letter queue of the queue we name. We run python dlq.py orders.
import sys
from azure.servicebus import ServiceBusSubQueue
from common import client, props
queue = sys.argv[1]
with client() as sb, sb.get_queue_receiver(
queue, sub_queue=ServiceBusSubQueue.DEAD_LETTER) as dlq:
for msg in dlq.peek_messages(50, sequence_number=1): # no lock
print(msg.message_id, "seq", msg.sequence_number, "body", msg)
print(" dead_letter_reason:", msg.dead_letter_reason)
print(" dead_letter_error_description:",
msg.dead_letter_error_description)
print(" delivery_count:", msg.delivery_count,
" dead_letter_source:", msg.dead_letter_source)
print(" stored as properties:", sorted(props(msg)))$ python dlq.py orders
order-1003 seq 3 body {"id": 1003, "amount": "49,90"}
dead_letter_reason: MaxDeliveryCountExceeded
dead_letter_error_description: Message could not be consumed after 3 delivery attempts.
delivery_count: 3 dead_letter_source: None
stored as properties: ['DeadLetterErrorDescription', 'DeadLetterReason']Order 1003 kept its message ID, body and sequence number: order-1003 seq 3 body {"id": 1003, "amount": "49,90"}. The reason is MaxDeliveryCountExceeded, and the description is Message could not be consumed after 3 delivery attempts.
Reason and description are stored as application properties: ['DeadLetterErrorDescription', 'DeadLetterReason']. And dead_letter_source: None: it's only set when dead-lettered messages are auto-forwarded to another entity, as in the scenario.
There's no automatic cleanup, and time to live isn't observed in a dead-letter queue. Messages stay until someone completes them.
Question 3: The dead-letter queue fills up and nobody notices. How do you monitor and alert on it?
On Azure, alert on the DeadletteredMessages metric in Azure Monitor. It has an EntityName dimension, so one rule can watch one specific queue.
Here's the alert as Azure CLI code: maximum dead-lettered messages above zero, where entity name includes orders, with an action group that pages the team.
# Azure Monitor: alert on dead letters in the orders queue
COND="max DeadletteredMessages > 0 where EntityName includes orders"
az monitor metrics alert create --name dlq-orders \
--resource-group rg-shop --scopes "$NAMESPACE_ID" \
--condition "$COND" --window-size 5m --evaluation-frequency 5m \
--action "$ACTION_GROUP_ID" --severity 2In code, the administration client returns the dead-letter message count.
# Python admin client: Azure only, not on the emulator
from azure.identity import DefaultAzureCredential
from azure.servicebus.management import (
ServiceBusAdministrationClient)
admin = ServiceBusAdministrationClient(
"shop-sb.servicebus.windows.net", DefaultAzureCredential())
info = admin.get_queue_runtime_properties("orders")
print(info.dead_letter_message_count)The emulator has no metrics or runtime counts, so we count with peek: no locks, at most 250 messages per call, paging by sequence number. We ran this after the demos in questions 5 and 6, which show where these dead letters came from. We run python dlq_count.py orders payments cart-reminders price-updates.
import collections, sys
from azure.servicebus import ServiceBusSubQueue
from common import client
def dead_letters(sb, queue):
"""Count a DLQ with peek: no lock, at most 250 per call."""
reasons, seq = collections.Counter(), 1
with sb.get_queue_receiver(
queue, sub_queue=ServiceBusSubQueue.DEAD_LETTER) as dlq:
while page := dlq.peek_messages(250, sequence_number=seq):
reasons.update(m.dead_letter_reason for m in page)
seq = page[-1].sequence_number + 1 # next page
return reasons
with client() as sb:
for queue in sys.argv[1:]:
reasons = dead_letters(sb, queue)
print(f"{queue}: {sum(reasons.values())} dead-lettered",
dict(sorted(reasons.items())))$ python dlq_count.py orders payments cart-reminders price-updates
orders: 1 dead-lettered {'MaxDeliveryCountExceeded': 1}
payments: 2 dead-lettered {'KeyError': 1, 'ValueError': 1}
cart-reminders: 3 dead-lettered {'TTLExpiredException': 3}
price-updates: 0 dead-lettered {}orders: 1 dead-lettered, payments: 2 dead-lettered with KeyError and ValueError, cart-reminders: 3 dead-lettered as TTLExpiredException, and price-updates: 0 dead-lettered.
How I set the alerts:
- Above zero: alert - critical queues
- Watch the trend - noisy queues
- Topics - DLQs live on each subscription
For topics, alert on the topic, then check its subscriptions, because each subscription has its own dead-letter queue.
Question 4: A bug is fixed and the dead-lettered messages must be processed. How do you resubmit them safely?
Fix and deploy first, then resubmit a copy. The portal's Service Bus Explorer can resend, but it leaves the original in the dead-letter queue. From a subscription's dead-letter queue, it resends to the topic, so every subscription gets a copy.
For volume, we use a small tool. resubmit.py reads the dead-letter queue in peek-lock and takes only the reason we fixed. It copies body, message ID and subject, drops the dead-letter properties, adds a resubmitted marker, sends the copy, and only then completes the dead-letter copy. Then the fixed consumer runs. We run python resubmit.py orders MaxDeliveryCountExceeded, python consume.py --fixed and python dlq_count.py orders.
import sys
from azure.servicebus import ServiceBusMessage, ServiceBusSubQueue
from common import client, props
queue, reason = sys.argv[1], sys.argv[2] # only the reason we fixed
with client() as sb, sb.get_queue_sender(queue) as sender, \
sb.get_queue_receiver(
queue, sub_queue=ServiceBusSubQueue.DEAD_LETTER) as dlq:
for msg in dlq.receive_messages(max_message_count=100,
max_wait_time=3): # one pass
p = props(msg)
if msg.dead_letter_reason != reason or "resubmitted" in p:
dlq.abandon_message(msg) # not ours: leave it
continue
p.pop("DeadLetterReason", None)
p.pop("DeadLetterErrorDescription", None)
p["resubmitted"] = reason # marker: only once
sender.send_messages(ServiceBusMessage(
str(msg), message_id=msg.message_id, subject=msg.subject,
application_properties=p))
dlq.complete_message(msg) # after the send worked
print("resubmitted", msg.message_id,
"from DLQ seq", msg.sequence_number)$ python resubmit.py orders MaxDeliveryCountExceeded
resubmitted order-1003 from DLQ seq 3
$ python consume.py --fixed
completed: ['order-1003 seq 6 (resubmitted)']
failed, delivery_count on each try: {}
$ python dlq_count.py orders
orders: 0 dead-lettered {}resubmitted order-1003 from DLQ seq 3. The fixed consumer completes it as seq 6 (resubmitted), and the count is back to orders: 0 dead-lettered.
The copy is a new message with a new sequence number. Python has no transactions, so a crash between send and complete can duplicate it. Keep the consumer idempotent by message ID.
A failed resubmit stays for a human. And with duplicate detection on, wait out its window, or the copy with the same ID is silently dropped.
Question 5: Someone asks whether expired messages go to the dead-letter queue. How do you control it?
Only when we turn it on. Dead-lettering on message expiration is a setting per queue and subscription. On: expired messages move to the dead-letter queue as TTLExpiredException. Off: they're dropped.
| Queue | TTL | DLQ on expiry |
|---|---|---|
| cart-reminders | 5 s | true |
| price-updates | 5 s | false |
Let's try both. ttl.py sends three messages to each queue, waits 8 seconds, then peeks, receives and peeks the dead-letter queue. We run python ttl.py.
import time
from azure.servicebus import ServiceBusMessage, ServiceBusSubQueue
from common import client
queues = ["cart-reminders", "price-updates"] # both: TTL 5 seconds
with client() as sb:
for q in queues:
with sb.get_queue_sender(q) as sender:
sender.send_messages([ServiceBusMessage(
f"{q} {i}", message_id=f"{q}-{i}")
for i in (1, 2, 3)])
time.sleep(8) # all six have expired
for q in queues:
with sb.get_queue_receiver(q) as r:
peeked = r.peek_messages(10, sequence_number=1)
got = r.receive_messages(max_message_count=10,
max_wait_time=3)
print(q, "| peek:", len(peeked), "| receive:", len(got))
with sb.get_queue_receiver(
q, sub_queue=ServiceBusSubQueue.DEAD_LETTER) as dlq:
dead = dlq.peek_messages(10, sequence_number=1)
print(q, "| DLQ:", len(dead),
sorted({m.dead_letter_reason for m in dead}))$ python ttl.py
cart-reminders | peek: 3 | receive: 0
cart-reminders | DLQ: 3 ['TTLExpiredException']
price-updates | peek: 3 | receive: 0
price-updates | DLQ: 0 []The peek still shows peek: 3 in each queue: expiry is lazy, and Microsoft notes peek can still show expired messages. But receive: 0. Then cart-reminders has DLQ: 3 ['TTLExpiredException'], and price-updates has DLQ: 0 [].
Two more rules:
- Message TTL is capped - by the entity default
- Deferred messages - not moved to the DLQ on expiry
A message's own time to live can't exceed the entity default: Service Bus silently lowers it. On Azure, it's one flag.
# Azure: one flag on the queue (or the subscription)
az servicebus queue update --resource-group rg-shop \
--namespace-name shop-sb --name orders \
--enable-dead-lettering-on-message-expiration trueOn for anything you'd have to explain if it vanished, like orders and payments. Off for data a newer message replaces anyway, like price updates.
Question 6: Your manager asks when to retry and when to dead-letter. How do you classify errors?
Ask one thing: can a retry ever succeed? Timeouts and throttling are transient, so retry. Bad data never gets better, so dead-letter it right away. Unknown errors get a few retries, with the max delivery count as the safety net.
| Error | Examples | What to do |
|---|---|---|
| Transient | a timeout, throttling, a deadlock | retry: abandon, ideally with backoff |
| Permanent: bad data | invalid JSON, a missing field, a negative amount | dead-letter now, with a reason |
| Unknown | a bug, an unexpected exception | retry; the max delivery count dead-letters it |
Let's build it. payments.py catches errors by type. A ValueError or KeyError means bad data: dead-letter now, with the exception type as reason and its message as description. A timeout, or anything else, means abandon, and the message comes back. We run python send_payments.py, python payments.py and python dlq.py payments.
import json
from azure.servicebus import ServiceBusMessage
from common import client
payments = {"pay-1": {"customer": "C7", "amount": 40},
"pay-2": {"customer": "C8", "amount": -5},
"pay-3": {"customer": "C9", "amount": 25, "bank": "slow"},
"pay-4": {"amount": 60}} # no customer
with client() as sb, sb.get_queue_sender("payments") as sender:
sender.send_messages([ServiceBusMessage(json.dumps(p),
message_id=k)
for k, p in payments.items()])
print("sent", len(payments), "payments")import json
from common import client
def charge(payment, attempt):
payment["customer"] # KeyError when missing
if payment["amount"] <= 0:
raise ValueError("amount must be positive")
if payment.get("bank") == "slow" and attempt == 0:
raise TimeoutError("bank API timed out") # simulated, once
log = []
with client() as sb, sb.get_queue_receiver("payments") as receiver:
while batch := receiver.receive_messages(max_message_count=10,
max_wait_time=3):
for msg in batch:
name, attempt = msg.message_id, msg.delivery_count
try:
charge(json.loads(str(msg)), attempt)
receiver.complete_message(msg)
log.append(f"{name}: completed on try {attempt}")
except (ValueError, KeyError) as e: # bad data
kind = type(e).__name__
receiver.dead_letter_message(
msg, reason=kind, error_description=str(e))
log.append(f"{name}: dead-lettered now, {kind}")
except Exception as e: # transient or unknown
receiver.abandon_message(msg) # retry it
kind = type(e).__name__
log.append(f"{name}: {kind} on try {attempt}")
print(*sorted(log), sep="\n")$ python send_payments.py
sent 4 payments
$ python payments.py
pay-1: completed on try 0
pay-2: dead-lettered now, ValueError
pay-3: TimeoutError on try 0
pay-3: completed on try 1
pay-4: dead-lettered now, KeyError
$ python dlq.py payments
pay-2 seq 2 body {"customer": "C8", "amount": -5}
dead_letter_reason: ValueError
dead_letter_error_description: amount must be positive
delivery_count: 0 dead_letter_source: None
stored as properties: ['DeadLetterErrorDescription', 'DeadLetterReason']
pay-4 seq 4 body {"amount": 60}
dead_letter_reason: KeyError
dead_letter_error_description: 'customer'
delivery_count: 0 dead_letter_source: None
stored as properties: ['DeadLetterErrorDescription', 'DeadLetterReason']pay-1: completed on try 0. pay-3 times out once, then completed on try 1. pay-2 and pay-4 are dead-lettered right away, without burning any retries.
The dead-letter queue shows ValueError with amount must be positive, and KeyError with 'customer', both at delivery_count: 0. That's Microsoft's advice: exception type in the reason, details like the stack trace in the description, within the message size limit.
When a downstream system is down for an hour, every message fails, and retries just flood the dead-letter queue. Back off, or pause the consumer.
Scenario 7: A partner sends malformed messages every night and the order pipeline stalls. How do you make it resilient?
A stall usually means the consumer crashes on a bad message, restarts, and gets it again. The fix: validate every message, dead-letter the bad ones at once with a clear reason, and keep the good ones flowing.
Then give the errors one home. The partner-orders queue sets forward dead-lettered messages to a central queue, partner-errors. On Azure that's one flag, and the target queue must exist first.
# Azure: partner-errors must exist first
az servicebus queue create --resource-group rg-shop \
--namespace-name shop-sb --name partner-orders \
--max-delivery-count 5 \
--forward-dead-lettered-messages-to partner-errorsLet's run tonight's batch of six messages. partner_consume.py checks the JSON, then the required fields, and triage.py reads the central queue. We run python partner_send.py, python partner_consume.py and python triage.py.
from azure.servicebus import ServiceBusMessage
from common import client
nightly = ['{"order": "P-1", "sku": "MUG-01", "qty": 2}',
'{"order": "P-2", "sku": "TEE-07", "qty": 1}',
'{"order": "P-3", "sku": "CAP-03", "qty": 4', # cut off
'{"order": "P-4", "qty": 3}', # no sku
'{"order": "P-5", "sku": "MUG-01", "qty": 1}',
'{"order": "P-6", "sku": "BAG-02", "qty": 2}']
with client() as sb, sb.get_queue_sender("partner-orders") as s:
s.send_messages([ServiceBusMessage(body,
message_id=f"partner-{i}")
for i, body in enumerate(nightly, 1)])
print("the partner sent", len(nightly), "messages")import json
from common import client
REQUIRED = ("order", "sku", "qty")
done, bad = [], []
with client() as sb, sb.get_queue_receiver("partner-orders") as r:
while batch := r.receive_messages(max_message_count=50,
max_wait_time=3):
for msg in batch:
try:
order = json.loads(str(msg))
except json.JSONDecodeError as e: # not JSON at all
r.dead_letter_message(msg, reason="InvalidJson",
error_description=e.msg)
bad.append(msg.message_id); continue
missing = [f for f in REQUIRED if f not in order]
if missing: # JSON, wrong shape
r.dead_letter_message(msg, reason="SchemaValidation",
error_description="missing " + ", ".join(missing))
bad.append(msg.message_id); continue
r.complete_message(msg) # the order is loaded
done.append(msg.message_id)
print("completed:", sorted(done))
print("dead-lettered:", sorted(bad))from common import client
with client() as sb:
with sb.get_queue_receiver("partner-errors") as r: # the target
found = []
while batch := r.receive_messages(max_message_count=50,
max_wait_time=3):
for msg in batch:
found.append(f"{msg.message_id} | "
f"{msg.dead_letter_reason} | "
f"{msg.dead_letter_error_description} | "
f"from {msg.dead_letter_source}")
r.complete_message(msg) # ticket logged
print(*sorted(found), sep="\n")
with sb.get_queue_receiver("partner-orders") as r:
print("partner-orders left:",
len(r.peek_messages(50, sequence_number=1)))$ python partner_send.py
the partner sent 6 messages
$ python partner_consume.py
completed: ['partner-1', 'partner-2', 'partner-5', 'partner-6']
dead-lettered: ['partner-3', 'partner-4']
$ python triage.py
partner-3 | InvalidJson | Expecting ',' delimiter | from partner-orders
partner-4 | SchemaValidation | missing sku | from partner-orders
partner-orders left: 0Four are valid and completed. partner-3 is cut off mid-JSON and partner-4 has no SKU, so both are dead-lettered, as InvalidJson and SchemaValidation.
In partner-errors, they're active messages with reason, description and from partner-orders, the dead-letter source, so triage knows the origin. And partner-orders left: 0: the pipeline never stalled.
Then close the loop:
- Alert on the central queue
- Daily error report - to the partner
- Resubmit after their fix - same safe tool
Resubmit only after the partner fixes the data, with the same safe tool as in question 4.
Key points to remember
- Every queue and subscription has a dead-letter queue; Azure max delivery count default 10
- System reasons: MaxDeliveryCountExceeded, TTLExpiredException, hop count, header size
- Alert on DeadletteredMessages by EntityName; no cleanup, no TTL in a DLQ
- Resubmit a copy after the fix, with a marker; complete the DLQ copy last
- Dead-letter bad data now, retry transient errors; forward DLQs to a central queue
The full script
This is a Python script that writes every file and runs every command above against the Service Bus emulator, in the order we ran them (questions 5 and 6 before the count in question 3): start the emulator with the Config.json above, run pip install azure-servicebus first, and set SERVICEBUS_CONNECTION_STRING.
Show the full script that writes the files and runs every step
# ========================================================================
# Service Bus Interview Q&A #5 - Dead-letter queues and poison messages
# TechBrothersIT. Names and sample data are invented for teaching.
# Every step below was run on the official Azure Service Bus emulator (Docker image, version 2.0.1) with
# SQL Server 2022 and azure-servicebus 7.15.0; the outputs in the video and the blog post are the real outputs.
# To run it yourself:
# 1. Start the emulator with Microsoft's installer (github.com/Azure/azure-service-bus-emulator-installer),
# using the Config.json this script writes first (Step 0) as the emulator's config file; it holds every
# queue, topic, subscription, rule and setting (lock duration, max delivery count, duplicate detection...)
# the steps depend on.
# 2. pip install azure-servicebus
# 3. Set SERVICEBUS_CONNECTION_STRING to the emulator connection string (Endpoint=sb://localhost;
# SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;)
# then run python ServiceBus_Interview_QA_05_Code.py.
# Run it in an empty folder and on a freshly started emulator: it creates its files (and any SQLite
# databases) there, and a second run on old files or old messages gives different output.
# Steps that restart the emulator say so in a comment: stop and start it by hand at that point.
# ========================================================================
import os, subprocess, time
def write(path, text):
if text is None:
if os.path.exists(path): os.remove(path)
return
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write(text.strip("\n") + "\n")
def run(cmd, expect_error=False, allow_error=False, env=None):
print("\n$ " + cmd, flush=True)
rc = subprocess.run(cmd, shell=True, env=dict(os.environ, **(env or {}))).returncode
if rc != 0 and not (expect_error or allow_error):
raise SystemExit("stopped: this command was expected to succeed")
# Step 0: the emulator config (mount it as ServiceBus_Emulator/ConfigFiles/Config.json, then start the emulator)
write('Config.json', """\
{
"UserConfig": {
"Namespaces": [
{
"Name": "sbemulatorns",
"Queues": [
{
"Name": "orders",
"Properties": {
"DeadLetteringOnMessageExpiration": false,
"DefaultMessageTimeToLive": "PT1H",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "",
"ForwardTo": "",
"LockDuration": "PT1M",
"MaxDeliveryCount": 3,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
},
{
"Name": "payments",
"Properties": {
"DeadLetteringOnMessageExpiration": false,
"DefaultMessageTimeToLive": "PT1H",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "",
"ForwardTo": "",
"LockDuration": "PT1M",
"MaxDeliveryCount": 3,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
},
{
"Name": "cart-reminders",
"Properties": {
"DeadLetteringOnMessageExpiration": true,
"DefaultMessageTimeToLive": "PT5S",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "",
"ForwardTo": "",
"LockDuration": "PT1M",
"MaxDeliveryCount": 3,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
},
{
"Name": "price-updates",
"Properties": {
"DeadLetteringOnMessageExpiration": false,
"DefaultMessageTimeToLive": "PT5S",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "",
"ForwardTo": "",
"LockDuration": "PT1M",
"MaxDeliveryCount": 3,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
},
{
"Name": "partner-orders",
"Properties": {
"DeadLetteringOnMessageExpiration": false,
"DefaultMessageTimeToLive": "PT1H",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "partner-errors",
"ForwardTo": "",
"LockDuration": "PT1M",
"MaxDeliveryCount": 5,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
},
{
"Name": "partner-errors",
"Properties": {
"DeadLetteringOnMessageExpiration": false,
"DefaultMessageTimeToLive": "PT1H",
"DuplicateDetectionHistoryTimeWindow": "PT20S",
"ForwardDeadLetteredMessagesTo": "",
"ForwardTo": "",
"LockDuration": "PT1M",
"MaxDeliveryCount": 3,
"RequiresDuplicateDetection": false,
"RequiresSession": false
}
}
],
"Topics": []
}
],
"Logging": {
"Type": "File"
}
}
}
""")
# Step 0: the starting files
write('common.py', 'import os\nfrom azure.servicebus import ServiceBusClient\n\n\ndef client():\n return ServiceBusClient.from_connection_string(\n os.environ["SERVICEBUS_CONNECTION_STRING"])\n\n\ndef props(msg):\n """Application properties: keys and text values come as bytes."""\n return {k.decode(): v.decode() if isinstance(v, bytes) else v\n for k, v in (msg.application_properties or {}).items()}\n')
# Step 1: A poison order: abandoned three times, then moved to the dead-letter queue
write('send_orders.py', """\
import json
from azure.servicebus import ServiceBusMessage
from common import client
orders = [{"id": 1001, "amount": "25.00"},
{"id": 1002, "amount": "18.50"},
{"id": 1003, "amount": "49,90"}, # v1 can't parse it
{"id": 1004, "amount": "12.00"},
{"id": 1005, "amount": "99.99"}]
with client() as sb, sb.get_queue_sender("orders") as sender:
sender.send_messages([ServiceBusMessage(
json.dumps(o), message_id=f"order-{o['id']}",
subject="order.created") for o in orders])
print("sent", len(orders), "orders")
""")
write('consume.py', """\
import json, sys
from common import client, props
fixed = "--fixed" in sys.argv # the release with the fix
def amount(order):
text = order["amount"]
return float(text.replace(",", ".") if fixed else text)
done, tries = [], {}
with client() as sb, sb.get_queue_receiver("orders") as receiver:
while batch := receiver.receive_messages(max_message_count=10,
max_wait_time=3):
for msg in batch:
try:
amount(json.loads(str(msg))) # process the order
receiver.complete_message(msg)
note = (f" seq {msg.sequence_number} (resubmitted)"
if "resubmitted" in props(msg) else "")
done.append(msg.message_id + note)
except ValueError:
tries.setdefault(msg.message_id, []).append(
msg.delivery_count)
receiver.abandon_message(msg) # let it come back
print("completed:", sorted(done))
print("failed, delivery_count on each try:", tries)
""")
run('python send_orders.py')
run('python consume.py')
# Step 2: Peek the dead-letter queue: reason, description, delivery count, source
write('dlq.py', """\
import sys
from azure.servicebus import ServiceBusSubQueue
from common import client, props
queue = sys.argv[1]
with client() as sb, sb.get_queue_receiver(
queue, sub_queue=ServiceBusSubQueue.DEAD_LETTER) as dlq:
for msg in dlq.peek_messages(50, sequence_number=1): # no lock
print(msg.message_id, "seq", msg.sequence_number, "body", msg)
print(" dead_letter_reason:", msg.dead_letter_reason)
print(" dead_letter_error_description:",
msg.dead_letter_error_description)
print(" delivery_count:", msg.delivery_count,
" dead_letter_source:", msg.dead_letter_source)
print(" stored as properties:", sorted(props(msg)))
""")
run('python dlq.py orders')
# Step 3: TTL 5 seconds: DeadLetteringOnMessageExpiration true vs false
write('ttl.py', """\
import time
from azure.servicebus import ServiceBusMessage, ServiceBusSubQueue
from common import client
queues = ["cart-reminders", "price-updates"] # both: TTL 5 seconds
with client() as sb:
for q in queues:
with sb.get_queue_sender(q) as sender:
sender.send_messages([ServiceBusMessage(
f"{q} {i}", message_id=f"{q}-{i}")
for i in (1, 2, 3)])
time.sleep(8) # all six have expired
for q in queues:
with sb.get_queue_receiver(q) as r:
peeked = r.peek_messages(10, sequence_number=1)
got = r.receive_messages(max_message_count=10,
max_wait_time=3)
print(q, "| peek:", len(peeked), "| receive:", len(got))
with sb.get_queue_receiver(
q, sub_queue=ServiceBusSubQueue.DEAD_LETTER) as dlq:
dead = dlq.peek_messages(10, sequence_number=1)
print(q, "| DLQ:", len(dead),
sorted({m.dead_letter_reason for m in dead}))
""")
run('python ttl.py')
# Step 4: Classify errors: dead-letter bad data now, retry transient errors
write('send_payments.py', """\
import json
from azure.servicebus import ServiceBusMessage
from common import client
payments = {"pay-1": {"customer": "C7", "amount": 40},
"pay-2": {"customer": "C8", "amount": -5},
"pay-3": {"customer": "C9", "amount": 25, "bank": "slow"},
"pay-4": {"amount": 60}} # no customer
with client() as sb, sb.get_queue_sender("payments") as sender:
sender.send_messages([ServiceBusMessage(json.dumps(p),
message_id=k)
for k, p in payments.items()])
print("sent", len(payments), "payments")
""")
write('payments.py', 'import json\nfrom common import client\n\ndef charge(payment, attempt):\n payment["customer"] # KeyError when missing\n if payment["amount"] <= 0:\n raise ValueError("amount must be positive")\n if payment.get("bank") == "slow" and attempt == 0:\n raise TimeoutError("bank API timed out") # simulated, once\n\nlog = []\nwith client() as sb, sb.get_queue_receiver("payments") as receiver:\n while batch := receiver.receive_messages(max_message_count=10,\n max_wait_time=3):\n for msg in batch:\n name, attempt = msg.message_id, msg.delivery_count\n try:\n charge(json.loads(str(msg)), attempt)\n receiver.complete_message(msg)\n log.append(f"{name}: completed on try {attempt}")\n except (ValueError, KeyError) as e: # bad data\n kind = type(e).__name__\n receiver.dead_letter_message(\n msg, reason=kind, error_description=str(e))\n log.append(f"{name}: dead-lettered now, {kind}")\n except Exception as e: # transient or unknown\n receiver.abandon_message(msg) # retry it\n kind = type(e).__name__\n log.append(f"{name}: {kind} on try {attempt}")\nprint(*sorted(log), sep="\\n")\n')
run('python send_payments.py')
run('python payments.py')
run('python dlq.py payments')
# Step 5: Count dead-lettered messages with peek, grouped by reason
write('dlq_count.py', 'import collections, sys\nfrom azure.servicebus import ServiceBusSubQueue\nfrom common import client\n\ndef dead_letters(sb, queue):\n """Count a DLQ with peek: no lock, at most 250 per call."""\n reasons, seq = collections.Counter(), 1\n with sb.get_queue_receiver(\n queue, sub_queue=ServiceBusSubQueue.DEAD_LETTER) as dlq:\n while page := dlq.peek_messages(250, sequence_number=seq):\n reasons.update(m.dead_letter_reason for m in page)\n seq = page[-1].sequence_number + 1 # next page\n return reasons\n\nwith client() as sb:\n for queue in sys.argv[1:]:\n reasons = dead_letters(sb, queue)\n print(f"{queue}: {sum(reasons.values())} dead-lettered",\n dict(sorted(reasons.items())))\n')
run('python dlq_count.py orders payments cart-reminders price-updates')
# Step 6: Resubmit after the fix: copy with a marker, then complete the DLQ copy
write('resubmit.py', 'import sys\nfrom azure.servicebus import ServiceBusMessage, ServiceBusSubQueue\nfrom common import client, props\n\nqueue, reason = sys.argv[1], sys.argv[2] # only the reason we fixed\nwith client() as sb, sb.get_queue_sender(queue) as sender, \\\n sb.get_queue_receiver(\n queue, sub_queue=ServiceBusSubQueue.DEAD_LETTER) as dlq:\n for msg in dlq.receive_messages(max_message_count=100,\n max_wait_time=3): # one pass\n p = props(msg)\n if msg.dead_letter_reason != reason or "resubmitted" in p:\n dlq.abandon_message(msg) # not ours: leave it\n continue\n p.pop("DeadLetterReason", None)\n p.pop("DeadLetterErrorDescription", None)\n p["resubmitted"] = reason # marker: only once\n sender.send_messages(ServiceBusMessage(\n str(msg), message_id=msg.message_id, subject=msg.subject,\n application_properties=p))\n dlq.complete_message(msg) # after the send worked\n print("resubmitted", msg.message_id,\n "from DLQ seq", msg.sequence_number)\n')
run('python resubmit.py orders MaxDeliveryCountExceeded')
run('python consume.py --fixed')
run('python dlq_count.py orders')
# Step 7: Nightly partner feed: validate, dead-letter with a reason, forward to a central queue
write('partner_send.py', """\
from azure.servicebus import ServiceBusMessage
from common import client
nightly = ['{"order": "P-1", "sku": "MUG-01", "qty": 2}',
'{"order": "P-2", "sku": "TEE-07", "qty": 1}',
'{"order": "P-3", "sku": "CAP-03", "qty": 4', # cut off
'{"order": "P-4", "qty": 3}', # no sku
'{"order": "P-5", "sku": "MUG-01", "qty": 1}',
'{"order": "P-6", "sku": "BAG-02", "qty": 2}']
with client() as sb, sb.get_queue_sender("partner-orders") as s:
s.send_messages([ServiceBusMessage(body,
message_id=f"partner-{i}")
for i, body in enumerate(nightly, 1)])
print("the partner sent", len(nightly), "messages")
""")
write('partner_consume.py', """\
import json
from common import client
REQUIRED = ("order", "sku", "qty")
done, bad = [], []
with client() as sb, sb.get_queue_receiver("partner-orders") as r:
while batch := r.receive_messages(max_message_count=50,
max_wait_time=3):
for msg in batch:
try:
order = json.loads(str(msg))
except json.JSONDecodeError as e: # not JSON at all
r.dead_letter_message(msg, reason="InvalidJson",
error_description=e.msg)
bad.append(msg.message_id); continue
missing = [f for f in REQUIRED if f not in order]
if missing: # JSON, wrong shape
r.dead_letter_message(msg, reason="SchemaValidation",
error_description="missing " + ", ".join(missing))
bad.append(msg.message_id); continue
r.complete_message(msg) # the order is loaded
done.append(msg.message_id)
print("completed:", sorted(done))
print("dead-lettered:", sorted(bad))
""")
write('triage.py', 'from common import client\n\nwith client() as sb:\n with sb.get_queue_receiver("partner-errors") as r: # the target\n found = []\n while batch := r.receive_messages(max_message_count=50,\n max_wait_time=3):\n for msg in batch:\n found.append(f"{msg.message_id} | "\n f"{msg.dead_letter_reason} | "\n f"{msg.dead_letter_error_description} | "\n f"from {msg.dead_letter_source}")\n r.complete_message(msg) # ticket logged\n print(*sorted(found), sep="\\n")\n with sb.get_queue_receiver("partner-orders") as r:\n print("partner-orders left:",\n len(r.peek_messages(50, sequence_number=1)))\n')
run('python partner_send.py')
run('python partner_consume.py')
run('python triage.py')
Part 6: Sessions and Message Ordering
The sample data on this page is invented for teaching. Every terminal output is the real output of the command above it, run on the official Azure Service Bus emulator (2.0.1) with SQL Server and azure-servicebus 7.15.0. Features the emulator does not support are shown as code. Part of the Real Time Azure Service Bus Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of October 2026; check the official Azure Service Bus documentation (learn.microsoft.com/azure/service-bus-messaging) for anything you quote in an interview.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.