Skip to content

Step 07 — Retry failures and dead-letter poison messages ​

What you'll do: give each outbox row its own retry schedule with exponential backoff, and send messages the worker cannot process to a dead-letter queue instead of retrying them forever.

Two kinds of failure ​

FailureExampleWhat should happen
TransientThe database or broker is down for a minute.Try again later, with growing pauses.
PoisonThe message body is not valid JSON, or has no message id.Stop trying. Park it where a person can look at it.

A poison message is one that fails every time, whatever you do. Retrying it forever wastes work and, in a queue, can block everything behind it.

Steps ​

Outbox: back off per message ​

  1. Add three columns to OutboxMessage.cs and a method that records a failure:

    csharp
    public int Attempts { get; set; }
    public DateTimeOffset? NextAttemptAt { get; set; }
    public string? LastError { get; set; }
    
    public void RecordFailure(string error, DateTimeOffset nextAttemptAt)
    {
        Attempts++;
        LastError = error.Length > MaxErrorLength ? error[..MaxErrorLength] : error;
        NextAttemptAt = nextAttemptAt;
    }

    Limit the column in OrdersDbContext.cs with message.Property(m => m.LastError).HasMaxLength(OutboxMessage.MaxErrorLength);.

  2. Add the retry settings to OutboxOptions.cs and appsettings.json:

    SettingDefaultMeaning
    MaxAttempts10After this many failures the row is left alone for a person to check.
    RetryBaseDelay00:00:02Wait after the first failure. Doubles each time.
    RetryMaxDelay00:05:00The wait never grows beyond this.
  3. In OutboxPublisher.cs, only pick rows that are due:

    csharp
    var batch = await db.OutboxMessages
        .Where(m => m.ProcessedAt == null
            && m.Attempts < settings.MaxAttempts
            && (m.NextAttemptAt == null || m.NextAttemptAt <= now))
        .OrderBy(m => m.OccurredAt)
        .Take(settings.BatchSize)
        .ToListAsync(ct);

    and when the broker refuses a message, schedule its next try and move on to the next row (continue instead of the break from step 04):

    csharp
    catch (PublishException ex)
    {
        message.RecordFailure(ex.Message, clock.GetUtcNow() + RetryDelay(message.Attempts + 1, settings));
        // logs a warning, or an error when MaxAttempts is reached
        continue;
    }
    csharp
    private static TimeSpan RetryDelay(int attempt, OutboxOptions settings)
    {
        var exponential = settings.RetryBaseDelay * Math.Pow(2, attempt - 1);
        var capped = exponential < settings.RetryMaxDelay ? exponential : settings.RetryMaxDelay;
        return capped * (0.8 + Random.Shared.NextDouble() * 0.4);
    }
  4. Create the migration:

    bash
    dotnet ef migrations add AddOutboxRetries --project src/Orders.Api --output-dir Data/Migrations

Consumer: dead-letter queue and delivery limit ​

  1. Add the settings to the worker's RabbitMqOptions.cs and appsettings.json:

    json
    "DeadLetterExchange": "shipping.dlx",
    "DeadLetterQueue": "shipping.order-placed.dlq",
    "DeliveryLimit": 5,
    "RequeueDelay": "00:00:01",
  2. In OrderPlacedConsumer.cs, declare the dead-letter exchange and queue, and point the main queue at them:

    csharp
    await channel.ExchangeDeclareAsync(settings.DeadLetterExchange, ExchangeType.Fanout, durable: true, cancellationToken: stoppingToken);
    await channel.QueueDeclareAsync(
        settings.DeadLetterQueue,
        durable: true,
        exclusive: false,
        autoDelete: false,
        arguments: new Dictionary<string, object?> { ["x-queue-type"] = "quorum" },
        cancellationToken: stoppingToken);
    await channel.QueueBindAsync(settings.DeadLetterQueue, settings.DeadLetterExchange, routingKey: "", cancellationToken: stoppingToken);
    
    await channel.QueueDeclareAsync(
        settings.Queue,
        durable: true,
        exclusive: false,
        autoDelete: false,
        arguments: new Dictionary<string, object?>
        {
            ["x-queue-type"] = "quorum",
            ["x-dead-letter-exchange"] = settings.DeadLetterExchange,
            ["x-delivery-limit"] = settings.DeliveryLimit,
        },
        cancellationToken: stoppingToken);
  3. Use BasicRejectAsync instead of BasicNackAsync for both failure paths. Poison messages are rejected without requeue; transient failures are rejected with requeue after a short pause:

    csharp
    // poison
    await channel.BasicRejectAsync(delivery.DeliveryTag, requeue: false, ct);
    
    // transient
    logger.LogError(ex, "Failed to handle message {MessageId} (attempt {Attempt} of {MaxAttempts}), requeueing it",
        messageId, DeliveryCount(delivery) + 1, options.Value.DeliveryLimit + 1);
    await Task.Delay(options.Value.RequeueDelay, ct);
    await channel.BasicRejectAsync(delivery.DeliveryTag, requeue: true, ct);

    DeliveryCount reads the x-delivery-count header that quorum queues add to redelivered messages.

  4. Delete the old queue. Queue arguments are fixed when a queue is created, and the worker now declares shipping.order-placed with new ones. Declaring it again would fail with PRECONDITION_FAILED - inequivalent arg 'x-dead-letter-exchange'. Stop the worker first, then:

    bash
    docker compose exec rabbitmq rabbitmqctl delete_queue shipping.order-placed

    (In production you would change these settings with a RabbitMQ policy, which can be updated on a live queue, instead of queue arguments.)

Check it works ​

bash
dotnet build OutboxInbox.slnx -warnaserror

1. Outbox backoff. With the worker still stopped and its queue deleted, nothing is bound to the exchange. Start the API and place an order:

bash
dotnet run --project src/Orders.Api
curl -X POST localhost:5080/orders -H 'content-type: application/json' \
  -d '{"customerEmail":"alex@contoso.com","items":[{"sku":"BOOK-1","quantity":1}]}'

The waits double (about 2 s, 4 s, 8 s, with jitter):

Broker did not accept outbox message 01a21a91-06d7-... (orders.order-placed.v1), attempt 1, next try at 11/27/2026 01:14:04 +00:00
Broker did not accept outbox message 01a21a91-06d7-... (orders.order-placed.v1), attempt 2, next try at 11/27/2026 01:14:08 +00:00
Broker did not accept outbox message 01a21a91-06d7-... (orders.order-placed.v1), attempt 3, next try at 11/27/2026 01:14:18 +00:00
bash
docker compose exec postgres psql -U postgres -d orders \
  -c "select attempts, next_attempt_at, last_error from outbox_messages where processed_at is null"
 attempts |        next_attempt_at        |                            last_error
----------+-------------------------------+-------------------------------------------------------------------
        3 | 2026-11-27 01:14:18.256712+00 | 312 NO_ROUTE Exchange: orders Routing Key: orders.order-placed.v1

Start the worker. It creates the queue with the new arguments, and on the next scheduled try the API logs Published outbox message ... and the worker logs Created shipment ....

2. A poison message. Publish a body that is not JSON:

bash
curl -u guest:guest -X POST localhost:15672/api/exchanges/%2F/orders/publish \
  -H 'content-type: application/json' \
  -d '{"properties":{"message_id":"bad-2"},"routing_key":"orders.order-placed.v1","payload":"not json","payload_encoding":"string"}'

The worker logs Dead-lettered unreadable message bad-2. Look in the dead-letter queue (this peek puts the message back):

bash
curl -u guest:guest -X POST localhost:15672/api/queues/%2F/shipping.order-placed.dlq/get \
  -H 'content-type: application/json' -d '{"count":1,"ackmode":"ack_requeue_true","encoding":"auto"}'

The broker added an x-death header saying where the message came from and why:

json
"headers": {
  "x-death": [{ "count": 1, "exchange": "orders", "queue": "shipping.order-placed", "reason": "rejected" }],
  "x-first-death-reason": "rejected"
}

3. A transient failure that never goes away (optional). With the worker running, stop the database, then publish a valid message by hand:

bash
docker compose stop postgres
curl -u guest:guest -X POST localhost:15672/api/exchanges/%2F/orders/publish \
  -H 'content-type: application/json' \
  -d '{"properties":{"message_id":"01a21a99-0000-7000-8000-000000000001"},"routing_key":"orders.order-placed.v1","payload":"{\"orderId\":\"01a21a99-0000-7000-8000-0000000000aa\",\"customerEmail\":\"sam@contoso.com\",\"placedAt\":\"2026-11-27T01:20:00+00:00\",\"lines\":[{\"sku\":\"PEN-3\",\"quantity\":1}]}","payload_encoding":"string"}'

The worker tries six times, one second apart, then the broker dead-letters the message:

Failed to handle message 01a21a99-0000-7000-8000-000000000001 (attempt 1 of 6), requeueing it
...
Failed to handle message 01a21a99-0000-7000-8000-000000000001 (attempt 6 of 6), requeueing it

The copy in shipping.order-placed.dlq has "reason": "delivery_limit" and "x-delivery-count": 6. Start the database again with docker compose up -d --wait postgres.

In the management UI, Queues and Streams now lists both quorum queues. The main queue shows the DLX (dead-letter exchange) and DIL (delivery limit) features:

RabbitMQ management UI listing two quorum queues: shipping.order-placed with features D, DR, DIL, DLX and Args and 0 messages, and shipping.order-placed.dlq with 1 ready message

Open shipping.order-placed.dlq, expand Get messages and click Get Message(s) (the default ack mode puts the message back):

A dead-lettered message in the RabbitMQ UI: exchange shipping.dlx, an x-death header with reason delivery_limit from queue shipping.order-placed, x-delivery-count 6, and the OrderPlaced JSON payload

Why it works ​

Backoff per row. Each outbox row carries its own attempts and next_attempt_at, so one message that keeps failing does not stop the others: the query simply skips it until it is due. Exponential backoff doubles the wait after every failure, so a broken dependency gets fewer and fewer calls. Jitter (a random ±20%) spreads out retries of messages that failed at the same time. After MaxAttempts the row stays in the table with its last_error, for a person to fix and reset.

The trade-off: with per-message backoff, a later message can be published before an earlier one that is waiting. Consumers should not depend on strict ordering across messages; the inbox from step 06 already makes each message safe on its own.

Dead-letter exchange. x-dead-letter-exchange tells the queue where to send messages that are rejected without requeue, or that pass the delivery limit. A dead-letter queue (DLQ) bound to that exchange keeps them. Nothing is lost: you can inspect a message, fix the cause and move it back (for example with the management UI's Move messages, which appears once you enable the rabbitmq_shovel and rabbitmq_shovel_management plugins).

Delivery limit. Quorum queues count how often each message was handed back (x-delivery-count). With x-delivery-limit: 5, the sixth failed delivery dead-letters the message with reason delivery_limit. That turns "transient" failures that are really permanent into inspectable dead letters instead of an endless loop.

basic.reject, not basic.nack. Since RabbitMQ 4.3, only basic.reject with requeue: true counts towards a quorum queue's delivery limit. basic.nack with requeue: true does not, so a failing message would loop forever. This guide hit exactly that on RabbitMQ 4.4: a first version of this step used BasicNackAsync and redelivered one message more than 2,000 times in a few seconds, despite the limit of 5. For single messages, BasicRejectAsync is the right call anyway; BasicNackAsync exists to reject many deliveries at once (multiple: true).

The pause before requeue. Without RequeueDelay, the six attempts would happen within milliseconds, far too fast for a database to come back. The pause blocks this consumer for a second, which is fine: while the database is down, nothing else would succeed either. For long delays (minutes), use a separate retry queue with a message TTL that dead-letters back into the main queue, so the consumer is not blocked.

MIT licensed. Every step is a commit: git checkout step-01.