LESSON 8 OF 14

8. Error Handling, Retry Policies, and Dead-Letter Queues

Learn how to distinguish transient and permanent failures, apply controlled retry policies, and inspect failed messages in a RabbitMQ Dead-Letter Queue.

70 dk 45

Introduction

In the previous lesson, we built a RabbitMQ consumer that runs inside a BackgroundService and processes messages through a pipeline. In real systems, however, receiving a message does not mean that the business operation has completed successfully. A database may be temporarily unavailable, an external service may time out, or the message itself may be permanently invalid.

In this lesson, we will design explicit failure handling. The goal is not to put every failed message back into the queue forever. Instead, transient failures should be retried in a controlled way, while permanent failures should be separated and moved to a Dead-Letter Queue for inspection.

Our example scenario consumes an OrderCreated message and generates an order report. If the report service is temporarily unavailable, the message will be retried after a delay. If the JSON format is invalid or the order identifier is not valid, the message will be sent directly to the error queue.

1. Distinguishing Transient and Permanent Failures

A retry decision starts with failure classification. Retrying every exception often makes a system less reliable. For example, retrying a malformed JSON message repeatedly wastes CPU, fills the logs, and may prevent other messages from progressing.

Failure typeExampleRecommended behavior
TransientHTTP 503, connection timeout, short SQL lockDelayed retry
PermanentInvalid JSON, missing required field, unknown orderSend to DLQ without retry
UnknownUnexpected application failureLimited retry, then DLQ

Using nack(requeue: true) with no delay is risky. As described in the RabbitMQ documentation, if all consumers immediately requeue the same message, they can create a requeue loop. For that reason, redelivery should include a delay and a maximum retry count.

2. Carrying the Retry Count in Message Metadata

Application-level retry can be implemented by adding a counter to the message headers. For example, the x-retry-count header records how many times the message has already been retried. This application-owned value expresses our business rule independently of RabbitMQ’s built-in x-death metadata.

When republishing a message, copy the relevant headers without changing the body and increment the counter. After the new message is published successfully, acknowledge the original delivery. Otherwise, the old delivery may be redelivered while another copy is already waiting in the retry queue.

private const string MainExchange = "orders.exchange";
private const string RetryExchange = "orders.retry.exchange";
private const string ErrorExchange = "orders.error.exchange";
private const string MainQueue = "orders.queue";
private const string RetryQueue = "orders.retry.queue";
private const string ErrorQueue = "orders.error.queue";

Header values may be represented as different types by AMQP client versions, such as int, long, or byte[]. Keeping this conversion in one helper method makes the consumer easier to read and test.

private static int GetRetryCount(IReadOnlyBasicProperties properties)
{
    if (properties.Headers is null ||
        !properties.Headers.TryGetValue("x-retry-count", out var value))
    {
        return 0;
    }

    return value switch
    {
        int number => number,
        long number => checked((int)number),
        byte[] bytes when int.TryParse(
            Encoding.UTF8.GetString(bytes), out var number) => number,
        _ => 0
    };
}

3. Designing Delayed Redelivery for Retries

RabbitMQ’s direct BasicNackAsync(..., requeue: true) usually makes a message available for immediate redelivery. Instead, we will create a retry queue that uses TTL. The message is published to this queue, waits for the configured period, and is then routed back to the main exchange through the queue’s Dead-Letter Exchange settings.

The topology works as follows:

  1. The message is consumed from orders.queue.
  2. If a transient failure occurs, the message is published to orders.retry.exchange and routed to orders.retry.queue.
  3. The retry queue applies, for example, a five-second TTL.
  4. When the TTL expires, the message is dead-lettered to orders.exchange.
  5. The original routing key routes the message back to orders.queue.

The following topology uses the asynchronous API style of RabbitMQ.Client 7.x.

var mainExchange = await channel.ExchangeDeclareAsync(
    MainExchange, ExchangeType.Direct, durable: true);

var retryExchange = await channel.ExchangeDeclareAsync(
    RetryExchange, ExchangeType.Direct, durable: true);

var errorExchange = await channel.ExchangeDeclareAsync(
    ErrorExchange, ExchangeType.Direct, durable: true);

var mainQueue = await channel.QueueDeclareAsync(
    MainQueue, durable: true, exclusive: false, autoDelete: false,
    arguments: new Dictionary<string, object?>
    {
        ["x-dead-letter-exchange"] = ErrorExchange,
        ["x-dead-letter-routing-key"] = "orders.failed"
    });

var retryQueue = await channel.QueueDeclareAsync(
    RetryQueue, durable: true, exclusive: false, autoDelete: false,
    arguments: new Dictionary<string, object?>
    {
        ["x-message-ttl"] = 5000,
        ["x-dead-letter-exchange"] = MainExchange,
        ["x-dead-letter-routing-key"] = "orders.created"
    });

var errorQueue = await channel.QueueDeclareAsync(
    ErrorQueue, durable: true, exclusive: false, autoDelete: false);

await channel.QueueBindAsync(MainQueue, MainExchange, "orders.created");
await channel.QueueBindAsync(RetryQueue, RetryExchange, "orders.retry");
await channel.QueueBindAsync(ErrorQueue, ErrorExchange, "orders.failed");

In production, queue arguments can also be managed with RabbitMQ policies. This allows TTL or DLX settings to be changed without redeploying the application. In this course project, declaring the topology in code keeps the configuration visible and reproducible.

4. Making the Retry Decision in the Consumer Pipeline

Our processing code will produce three outcomes: successful processing, delayed retry, and permanent failure. If publishing to the retry queue fails, we should negatively acknowledge the original delivery with requeue: true so that it is not lost. If the retry message is published successfully, we acknowledge the original delivery.

private async Task HandleMessageAsync(
    IChannel channel,
    BasicDeliverEventArgs delivery,
    CancellationToken cancellationToken)
{
    var body = delivery.Body.ToArray();
    var properties = delivery.BasicProperties;
    var retryCount = GetRetryCount(properties);

    try
    {
        var message = JsonSerializer.Deserialize<OrderCreated>(body)
            ?? throw new PermanentMessageException("Message body is empty.");

        await orderProcessor.ProcessAsync(message, cancellationToken);
        await channel.BasicAckAsync(delivery.DeliveryTag, multiple: false);
    }
    catch (PermanentMessageException exception)
    {
        logger.LogWarning(exception, "Permanent message failure.");
        await channel.BasicNackAsync(
            delivery.DeliveryTag, multiple: false, requeue: false);
    }
    catch (Exception exception) when (IsTransient(exception))
    {
        if (retryCount >= 3)
        {
            logger.LogError(exception,
                "Maximum retry count reached. Sending message to DLQ.");

            await channel.BasicNackAsync(
                delivery.DeliveryTag, multiple: false, requeue: false);
            return;
        }

        try
        {
            var retryProperties = new BasicProperties
            {
                Persistent = true,
                MessageId = properties.MessageId,
                ContentType = properties.ContentType,
                ContentEncoding = properties.ContentEncoding,
                Headers = new Dictionary<string, object?>
                {
                    ["x-retry-count"] = retryCount + 1,
                    ["x-original-queue"] = MainQueue
                }
            };

            await channel.BasicPublishAsync(
                RetryExchange,
                "orders.retry",
                mandatory: false,
                basicProperties: retryProperties,
                body: body,
                cancellationToken: cancellationToken);

            await channel.BasicAckAsync(
                delivery.DeliveryTag, multiple: false);
        }
        catch (Exception publishException)
        {
            logger.LogError(publishException,
                "Publishing to the retry queue failed.");

            await channel.BasicNackAsync(
                delivery.DeliveryTag, multiple: false, requeue: true);
        }
    }
    catch (Exception exception)
    {
        logger.LogError(exception, "Unexpected message failure.");
        await channel.BasicNackAsync(
            delivery.DeliveryTag, multiple: false, requeue: false);
    }
}

One detail is especially important: BasicNackAsync(..., requeue: false) routes the message to the DLX only when the source queue has a x-dead-letter-exchange configuration. Without a DLX, the message can be discarded by the broker. Critical systems should therefore verify that the DLX topology and error queue exist before the application begins consuming.

5. Dead-Letter Exchanges and Dead-Letter Queues

A Dead-Letter Exchange behaves like a normal exchange. A message can be routed to it when it is negatively acknowledged without requeueing, when its TTL expires, or when it is dropped because of queue limits. A queue bound to that exchange becomes the Dead-Letter Queue used for inspection and controlled recovery.

A DLQ should not be treated as a simple trash bin. To understand why a message failed, record or carry information such as:

  • MessageId and correlation identifier
  • Original routing key and source queue
  • Retry count
  • Failure type and error message
  • Processing time and consumer service name

RabbitMQ can add x-death information containing dead-letter history. For application decisions, however, an explicit x-retry-count header is usually clearer and more portable.

6. Poison Message Handling

A poison message is a message that keeps failing and prevents the normal flow from progressing. For example, malformed JSON will produce the same error every time it is consumed. Instead of requeueing the message forever, move it to the DLQ after a defined threshold.

Useful poison-message rules include:

  • Treat deserialization and validation errors as permanent failures in most cases.
  • Limit the maximum retry count.
  • Do not automatically move DLQ messages back to the main queue.
  • Verify that the underlying problem is fixed before replaying a message.
  • Keep idempotency protections enabled during manual replay.

7. Reprocessing a DLQ Message

A DLQ message can be reprocessed by a small administration tool, an admin endpoint, or a controlled command-line application. During replay, it is usually better to publish the body to the main exchange and clear old failure metadata so that the message starts a new processing attempt.

var replayProperties = new BasicProperties
{
    Persistent = true,
    MessageId = failedMessage.MessageId,
    Headers = new Dictionary<string, object?>
    {
        ["x-replayed"] = true,
        ["x-retry-count"] = 0
    }
};

await channel.BasicPublishAsync(
    MainExchange,
    "orders.created",
    mandatory: false,
    basicProperties: replayProperties,
    body: failedMessage.Body,
    cancellationToken: cancellationToken);

After the replay is published successfully, acknowledge the original message in the DLQ. If you acknowledge first and publish second, a process shutdown can lose the message. If you publish first and acknowledge later, the message may be processed twice; therefore, the consumer’s business operation must be idempotent.

8. Common Mistakes

  • Infinite requeue: Using requeue: true for every exception creates a continuous retry loop.
  • Immediate retry: Retrying thousands of messages while an external service is down overloads the system.
  • Confusing retry and DLQ: Transient failures belong in the retry queue; permanent or exhausted failures belong in the DLQ.
  • Incorrect acknowledgement order: Acknowledging the original delivery before publishing the retry message can cause message loss.
  • Ignoring idempotency: Connection loss or consumer restarts can cause the same message to be delivered more than once.
  • Logging sensitive data: Logging the complete message body may expose personal or commercial information.

Short Practice Exercise

Add the following behavior to the project:

  1. Declare orders.error.exchange and orders.error.queue for orders.queue.
  2. Retry transient failures three times, increasing x-retry-count and waiting five seconds between attempts.
  3. Send malformed JSON directly to the DLQ.
  4. Move a message to the DLQ when the retry count reaches three.
  5. Use the RabbitMQ Management UI to observe message counts in the main queue, retry queue, and DLQ.
  6. Replay one DLQ message to the main exchange in a controlled way.

For testing, use a feature flag that produces a transient failure for one message and malformed JSON for another. Confirm that the logs show the message identifier, retry count, and final failure type.

Conclusion

A reliable RabbitMQ consumer does more than receive and process messages; it explicitly manages failure. Transient failures should use delayed and limited retries, while permanent failures and poison messages should be moved to a DLQ. Publishing the retry message before acknowledging the original delivery, creating the DLX topology in advance, and designing consumer operations to be idempotent all reduce the risk of data loss and infinite loops.

In the next step, we will extend this reliability approach with idempotency, correlation IDs, observability, and cross-service operation tracking.

Sources