Lesson 3 of 3 Message Queuing with Azure Service Bus

Handling Dead Letters and Reliable Processing

This lesson explains dead-letter queues and how to handle them, and the sessions, duplicate detection, scheduling and transactions that make processing reliable.

Learning outcomes

After completing this lesson, you will be able to:

  • Identify the reasons a message is dead-lettered.
  • Explain when to dead-letter a message explicitly.
  • Describe how to resubmit dead-lettered messages.
  • Choose between sessions, duplicate detection and transactions.

What the dead-letter queue is

Every queue and every subscription has a secondary subqueue called the dead-letter queue (DLQ), at the path ENTITY/$deadletterqueue. It holds messages that cannot or should not be delivered, so that they do not block other messages or disappear silently. Messages in the DLQ do not expire, are not delivered to normal receivers, and stay until an application or operator receives them.

Messages are moved to the DLQ for several reasons, each recorded in the DeadLetterReason property, often with a DeadLetterErrorDescription.

ReasonWhen it happens
MaxDeliveryCountExceededThe message was delivered more times than the entity's maximum delivery count (default 10), usually because processing kept failing
TTLExpiredExceptionThe message's time to live expired and dead-lettering on expiration is enabled
Filter evaluation errorsA subscription filter threw an exception and dead-lettering on filter evaluation errors is enabled
Application-definedThe receiver called dead_letter_message with its own reason, such as InvalidPayload
Session or size problemsFor example, a message without a session ID sent to a session-enabled entity
Match the pairs

Dead-letter reasons

Exam skills 3.1.1

Match each event with the dead-letter reason it produces.

Log in to try this activity Interactive activities are free with an account.

Poison messages and explicit dead-lettering

A poison message is one that fails every time, such as malformed JSON or a reference to a document that no longer exists. Without a DLQ it would be retried forever, wasting resources and, with sessions, blocking later messages. The maximum delivery count handles this automatically: after the tenth failed delivery, the message moves to the DLQ.

When a handler can tell that retrying is pointless, it should dead-letter the message immediately with a clear reason rather than abandon it ten times. Transient failures, such as a throttled model endpoint, are the opposite case and should be abandoned (or left to lock expiry) so that the message is retried.

for msg in receiver.receive_messages(max_message_count=10, max_wait_time=5):
    try:
        job = json.loads(str(msg))
        process(job)
        receiver.complete_message(msg)
    except json.JSONDecodeError as err:
        receiver.dead_letter_message(msg, reason="InvalidPayload", error_description=str(err))
    except TransientModelError:
        receiver.abandon_message(msg)          # retry later; counts towards MaxDeliveryCount

The following diagram shows how failed requests are kept and duplicates removed.

Keeping failed requests and removing duplicates. The worker dead-letters unsupported requests at once with a reason, and an alert on the dead-letter queue count tells operators to inspect, resubmit or discard them. For duplicates, the sender sets a stable message_id, and a new queue created with duplicate detection discards repeated sends.
Duplicate detection can be enabled only when a queue is created.
Sort into groups

Abandon or dead-letter?

Exam skills 3.1.1

Decide how a worker should settle each failed message.

Log in to try this activity Interactive activities are free with an account.

Handling the dead-letter queue

A DLQ that nobody reads is a slow data loss. A production design monitors the DLQ message count with an Azure Monitor alert, and an operator or a repair process reads dead-lettered messages, inspects their reasons, fixes the cause, and either resubmits a corrected copy to the main entity or discards the message. A dead-lettered message cannot be moved back; resubmission means sending a new message with the same body and properties and completing the dead-lettered one.

from azure.servicebus import ServiceBusSubQueue, ServiceBusMessage

with client.get_queue_receiver("embed-jobs", sub_queue=ServiceBusSubQueue.DEAD_LETTER) as dlq, \
     client.get_queue_sender("embed-jobs") as sender:
    for msg in dlq.receive_messages(max_message_count=20, max_wait_time=5):
        print(msg.dead_letter_reason, msg.dead_letter_error_description)
        if fixable(msg):
            sender.send_messages(ServiceBusMessage(str(msg), application_properties=msg.application_properties))
        dlq.complete_message(msg)
Put in order

Repairing a dead-lettered message

Exam skills 3.1.1

Put the steps for handling dead-lettered messages in order.

Log in to try this activity Interactive activities are free with an account.

Sessions, duplicate detection, scheduling and transactions

Several further features address specific reliability needs, and exam scenarios usually describe one of them precisely.

  • Sessions provide first-in, first-out ordering per key. Messages carry a session_id, such as a customer or conversation ID; a session-enabled entity delivers all messages of one session to one receiver at a time, in order, while different sessions are processed in parallel. Session state can store progress. Sessions must be enabled when the entity is created.
  • Duplicate detection discards a message whose message_id matches one sent within the detection window (default 10 minutes, configurable). It protects against senders that retry after a timeout and send the same message twice. It must be enabled at creation.
  • Scheduled messages are enqueued but become visible only at a set time, with schedule_messages or scheduled_enqueue_time_utc, which suits delayed retries and reminders.
  • Transactions group operations on entities in one namespace, such as completing a received message and sending a follow-up message, so that both happen or neither does.
Sessions
Problem solvedOrdering per key
ConfiguredAt entity creation
Key propertysession_id
Choose when Process each customer's events in order
Duplicate detection
Problem solvedRepeated sends by the sender
ConfiguredAt entity creation, with a time window
Key propertymessage_id
Choose when Senders may retry the same send
Dead-letter queue
Problem solvedMessages that cannot be processed
ConfiguredAlways present; options for expiry and filter errors
Key propertyDeadLetterReason
Choose when Isolate and inspect failures
Scenario questions

Reliability features

Exam skills 3.1.1

Choose the Service Bus feature that meets each requirement.

Log in to try this activity Interactive activities are free with an account.
Worked example

Messages that disappear and repeat

A worker processes model fine-tuning requests from a queue. Some requests contain an unsupported model name and fail every time; operators later find no trace of them. Other requests appear twice, because the sending API retries when its send times out. The team wants failed requests kept for inspection and duplicates removed.

Failed requests are not gone: after ten failed deliveries they moved to the dead-letter queue, which nobody reads. The worker should dead-letter unsupported requests immediately with a reason such as UnsupportedModel, and an alert on the DLQ count should notify operators, who inspect and resubmit or discard. For duplicates, the queue needs duplicate detection with the sender setting a stable message_id, such as the request ID; because the setting must be chosen at creation, a new queue is created with it enabled.

Raising the maximum delivery count would only delay dead-lettering. Using receive-and-delete would lose failed messages entirely. Sessions order messages but do not remove duplicates.

Check yourself

Can a dead-lettered message be moved back to its queue?

Show answer

No. Resubmission means sending a new message with the same body and properties to the main entity, then completing the dead-lettered message.

Exam Tips

Remember for the exam

  • Every queue and subscription has a DLQ at ENTITY/$deadletterqueue; DLQ messages do not expire.
  • MaxDeliveryCount (default 10) moves poison messages to the DLQ; dead-letter unrecoverable messages at once.
  • Resubmit by sending a new copy and completing the dead-lettered message; alert on DLQ counts.
  • Sessions give ordering per key; duplicate detection uses message_id; both are set at creation.