Table of Contents

Delayed Redelivery

Delayed redelivery (second-level retry) gives a message that failed all of its in-process retries another chance later, after a longer delay, instead of dead-lettering it at once. It is meant for failures that outlast a few seconds of retrying: an unavailable downstream service, a rate limit, a lock held by another process. In-process retry is described in Retry and Dead Letter Queues.

Where the waiting copy lives depends on the transport:

  • RabbitMQ - the copy is published back to the broker and is durable once the broker confirms it. Until then the original delivery keeps its consumer credit and buffer: during the republish (bounded by DelayedRedeliveryConfirmTimeout) and, when the outcome is ambiguous, during the backoff before it is requeued.
  • In-Memory - the copy is held in process memory behind a timer and is lost on restart or crash. Each pending copy keeps a slot of its queue's QueueCapacity for the whole delay. Pending copies are also limited to 1024 for the whole adapter (shared by every endpoint, not configurable); see Transport support.

How it works

  1. A consumer throws and the in-process retry policy of the endpoint is exhausted.
  2. The delayed redelivery stage decides the settlement: if the exception is eligible and levels are left, a copy of the message is scheduled for the next level; otherwise the message goes the usual way, to the dead-letter exchange or queue.
  3. The copy waits for the interval of its level, then returns to the endpoint queue and is consumed again.
  4. If it fails again, the next level is used. After the last level the message is dead-lettered.

The copy carries two counters set by the transport:

Header Meaning
BW-DelayedRedeliveryCount The number of delayed redelivery levels already used
BW-DelayedRedeliveryDeferrals The number of times the copy was deferred on the current level (see Inbox and Outbox)

A failure caused by a serialization error or an unknown payload (BareWireSerializationException, UnknownPayloadException) is never redelivered later, whether it is thrown directly or wrapped in another exception, and no filter changes that. Such a message takes the poison path. The search for a wrapped exception is bounded (a nesting depth of 8 and 32 inspected exceptions); beyond that limit the failure is treated as not excluded.

Counter headers are not trusted input

The two counter names are reserved: only the transport writes them, and MapHeader rejects them. When a counter is read, a value that is not made of ASCII digits counts as 0. The RabbitMQ transport additionally drops a counter longer than 10 characters on receive and matches the header names in their exact letter case; the In-Memory transport saturates the value. Count is clamped to the number of declared levels and Deferrals to 10 per level.

A forged counter cannot move the schedule beyond the declared levels or beyond 10 deferrals per level, but an inflated Count sends a message to the dead-letter queue sooner and skips the full in-process retry sequence of that delivery. Consumer code should not trust these headers. On RabbitMQ, keep in mind that write on the default exchange reaches every queue of the virtual host; restrict untrusted publishers with broker permissions.

Configuration

On RabbitMQ two calls belong together: DeclareDelayedRedelivery in the topology declares the levels, and UseDelayedRedelivery on the receive endpoint enables the policy. Both must use the same intervals.

using BareWire.Transport.RabbitMQ.Topology;

TimeSpan[] intervals = [TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(10), TimeSpan.FromHours(1)];

builder.Services.AddBareWireWithRabbitMq(rmq =>
{
    rmq.Host(builder.Configuration.GetConnectionString("rabbitmq")!);

    rmq.ConfigureTopology(t =>
    {
        t.DeclareQueue("orders", durable: true, arguments: new Dictionary<string, object>
        {
            ["x-queue-type"] = "quorum",
            ["x-dead-letter-exchange"] = string.Empty,
            ["x-dead-letter-routing-key"] = "orders-dlq",
        });
        t.DeclareQueue("orders-dlq", durable: true);

        t.DeclareDelayedRedelivery("orders", d => d
            .Intervals(intervals)
            .MaxLength(10_000));
    });

    rmq.ReceiveEndpoint("orders", e =>
    {
        e.RetryCount = 3;
        e.RetryInterval = TimeSpan.FromSeconds(1);

        e.UseDelayedRedelivery(d => d
            .Intervals(intervals)
            .Handle<TimeoutException>()
            .Ignore<ArgumentException>());

        e.Consumer<OrderConsumer, OrderCreated>();
    });
});

DeclareDelayedRedelivery has three overloads: intervals only, a strategy plus intervals, and a configuration delegate with Intervals, Strategy, MaxLength and MaxLengthBytes. When the intervals of UseDelayedRedelivery differ from the declared ones, StartAsync fails ({endpoint}.DelayedRedelivery.Intervals.Declaration); when the endpoint queue has no DeclareDelayedRedelivery at all, it fails with {endpoint}.DelayedRedelivery.

UseDelayedRedelivery options:

Method Effect
Intervals(params TimeSpan[]) The delay of each level, in order. Required: there is no default schedule.
Handle<TException>() Redeliver only failures of this type (or a derived type). Can be called more than once.
Ignore<TException>() Never redeliver failures of this type (or a derived type). Can be called more than once.
FullRetryEachCycle() Run the full in-process retry sequence on every cycle (see below).

Handle and Ignore match the thrown exception only; inner exceptions are not inspected. OperationCanceledException gets no special treatment; add Ignore<OperationCanceledException>() to keep it out.

Limits, by where they are checked:

  • StartAsync, every transport - 1 to 20 intervals, each greater than zero and at most the maximum delay of the transport (see Transport support).
  • DeclareDelayedRedelivery, RabbitMQ - intervals are whole seconds (both strategies) and distinct (TTL plus dead-letter cascade only), at most 2^32 - 1 ms, so the longest configurable interval is 4 294 967 seconds; the level queue name is at most 255 bytes of UTF-8 (TTL plus dead-letter cascade only).
  • In-Memory - fractions of a second and repeated intervals are accepted.

A single consumer can override the endpoint settings with UseDelayedRedelivery inside e.Consumer<TConsumer, TMessage>(c => ...). That member exists only on the two-parameter consumer configurator, so it is available only on an endpoint with a single consumer and cannot be set from a ConsumerDefinition.

On RabbitMQ the wait for the confirm of each copy is bounded by DelayedRedeliveryConfirmTimeout (5 seconds by default; a value greater than zero and at most 60 seconds).

Interaction with in-process retry

The first delivery runs the full in-process retry sequence. Every later cycle, a delivery that carries a positive BW-DelayedRedeliveryCount, runs a single attempt, unless the policy calls FullRetryEachCycle(). With RetryCount = 3 and three intervals, a message is attempted 4 + 1 + 1 + 1 times by default before it is dead-lettered.

Topology and level queue limits

With the default RabbitMQ strategy (TTL plus dead-letter cascade), DeclareDelayedRedelivery declares one level queue per interval, named {queue}.delayed-redelivery.{interval} (for example orders.delayed-redelivery.10m). Every level queue is:

  • a durable quorum queue with x-message-ttl equal to its interval;
  • dead-lettered through the default exchange back to the endpoint queue, with x-dead-letter-strategy: at-least-once;
  • x-overflow: reject-publish.

Level queues must not have consumers.

MaxLength and MaxLengthBytes are optional and set x-max-length and x-max-length-bytes on every level queue. Without them the level queues have no broker-side limit and the bus logs a startup warning. With a limit, a full level queue makes the broker nack the copy, and the original message is dead-lettered at once (barewire.messages.redelivery_failed with reason=confirm_nack). Changing MaxLength or MaxLengthBytes of an existing level queue fails the next declaration with PRECONDITION_FAILED (406). Changing an interval creates a new level queue and orphans the old one: drain the old queue before deleting it.

The endpoint queue:

  • With the TTL plus dead-letter cascade, a classic endpoint queue is a startup warning; with NativeDeliveryTime a non-quorum endpoint queue fails the start. A quorum endpoint queue without x-dead-letter-exchange is a startup warning with both strategies.
  • An endpoint queue with x-overflow: drop-head, or with a length limit and no x-overflow, fails the start, because a full queue would silently drop the oldest redelivered copy.
  • Without a dead-letter exchange on the endpoint queue, a message that has used every level is lost.

Replaying a message from the dead-letter queue keeps its counters: the replayed message gets one attempt and, if it fails, goes back to the dead-letter queue. A message republished through BareWire starts with fresh counters. A copy moved by a shovel or federation to an endpoint with fewer levels is clamped to that endpoint's levels and goes to the dead-letter queue on its next failure; this is the expected result.

The full list of startup checks is in RabbitMQ Transport - Startup topology validation.

Delivery guarantees

Delayed redelivery is at-least-once. A consumer can see the same message twice:

  • between the confirm of the copy and the acknowledgement of the original delivery, for example after a crash in between;
  • after a confirm timeout: the copy may already exist, but the original is requeued after a backoff of 2, 4, 8, 16 and then 30 seconds. The backoff counter is one per endpoint, saturates at 30 seconds and resets after a confirmed copy. After 3 consecutive confirm timeouts the confirm channel of the endpoint is closed and recreated.

Make consumers idempotent, or use the Inbox. Inbox deduplication across cycles needs a producer-assigned MessageId; without one every cycle is a new message for the Inbox.

Inbox and Outbox

The Inbox deduplicates per receive endpoint, keyed by MessageId and the endpoint name, and marks a message processed only after every consumer of the delivery has succeeded. It removes a duplicate copy of a delivery that already committed, such as the copy left behind by a confirm timeout. It does not prevent a redelivered copy from running again a consumer that already succeeded while another consumer of the same endpoint failed: their transactional work rolls back together, but the non-transactional side effects of each consumer must be idempotent.

When an endpoint with delayed redelivery uses the Inbox, the schedule is checked at start:

  • every level must be at least InboxLockTimeout + max(5 s, 10 %) (35 seconds with the defaults);
  • the sum of all intervals must be strictly less than InboxRetention.

A violation fails StartAsync with BareWireConfigurationException. When a copy returns while another delivery of the same message still holds the Inbox claim, the copy is deferred instead of rejected (barewire.messages.redelivery_deferred with reason=inbox_claim_active), at most 10 times per level. See also Inbox - Delayed redelivery intervals.

Endpoints with multiple consumers

The copy returns to the endpoint queue, not to a single consumer. On an endpoint with several consumers, every consumer sees the redelivered copy again, including the ones that succeeded the first time, and the bus logs a startup warning for such an endpoint. A per-consumer policy is possible only on an endpoint with a single consumer. Give each consumer that must be retried independently its own endpoint, or make every consumer idempotent.

Transport support

Transport Strategy Status Maximum delay Notes
RabbitMQ TTL plus dead-letter cascade Supported (default) 4 294 967 s (whole seconds, below the 2^32 - 1 ms x-message-ttl limit) One quorum level queue per interval
RabbitMQ NativeDeliveryTime Experimental (diagnostic BWEXP0043) 4 294 967 s, as above RabbitMQ 4.4 or later, quorum endpoint queue; measured up to 4 294 907 295 ms on RabbitMQ 4.4.1; the broker documents no limit
In-Memory In-process timer Supported 4 294 967 294 ms (about 49.7 days) Copy held in memory, keeps a QueueCapacity slot, lost on restart
Azure Service Bus - Not yet supported, fails at startup -
AWS SQS - Not yet supported, fails at startup -
Google Pub/Sub - Not yet supported, fails at startup -
Kafka - Not yet supported, fails at startup -

On an unsupported transport, UseDelayedRedelivery is rejected with BareWireConfigurationException: either when the endpoint is configured, or at the latest by StartAsync, which requires the TransportCapabilities.DelayedRedelivery capability.

RabbitMQ NativeDeliveryTime. Selected with DeclareDelayedRedelivery(queue, d => d.Strategy(RabbitMqDelayedRedeliveryStrategy.NativeDeliveryTime).Intervals(...)). No level queues are declared: the transport republishes the copy to the endpoint queue with the x-opt-delivery-time header, and the broker holds it until that time. The strategy is marked [Experimental], so using it requires #pragma warning disable BWEXP0043 or <NoWarn>BWEXP0043</NoWarn>. MaxLength and MaxLengthBytes are rejected. Delayed copies count towards x-max-length / x-max-length-bytes of the endpoint queue: with reject-publish a full endpoint queue nacks the copy and the original is dead-lettered.

In-Memory. Two limits apply and they are independent: QueueCapacity per queue (1000 by default), where a pending copy keeps its slot for the whole delay, and 1024 pending copies for the whole adapter, shared by every endpoint and not configurable. Which one is reached first depends on the number of endpoints and their backlog. When the adapter limit is reached, a new redelivery waits for a free place while it keeps its queue slot and the consumer credit; on an endpoint that settles sequentially the whole pump waits, so a backlog on one endpoint can stall redelivery on the others. A full queue that latches rejects new publications until it drains below 50% (see In-Memory Transport).

Operations

Operator checklist:

  • Permissions (RabbitMQ). Every copy is published to the default exchange, so the application user needs write on amq.default for as long as delayed redelivery is enabled; do not remove it while the feature is on. Declaring a level queue for the first time needs configure and read on that queue and write on amq.default; re-declaring an existing queue needs only configure. Level queues are never consumed, so read on them can be withheld after the first deployment (or for a user that does not create them); a later new level queue needs read again at its first declaration, and the startup check of level queues deployed outside the bus needs, on RabbitMQ 4.3.1 and later, at least one of configure, write or read: if you withhold read, keep configure or write on the level queues, or the start fails with 403. The details are in RabbitMQ Transport.
  • No consumers on level queues. Messages leave a level queue only through its TTL and dead-lettering.
  • Queue depth. Monitor the depth of level queues and of the dead-letter queue. With the TTL plus dead-letter cascade, each pair of endpoint and interval is one replicated quorum queue on the broker.
  • Shovel and federation. The counter headers travel with the message; the receiving endpoint clamps them to its own levels.
  • Not checked by BareWire. Broker policies and the arguments of queues declared outside BareWire cannot be read over AMQP 0-9-1; keeping them consistent is the operator's responsibility.
  • Quorum delivery-limit. Every Nack with requeue, for example after a confirm timeout, counts towards the delivery-limit of a quorum endpoint queue.
  • NativeDeliveryTime. The delivery time is an absolute time taken from the application clock and compared with the broker clock: keep application hosts and broker nodes synchronised (NTP). Run RabbitMQ 4.4 or later on every node: the start checks only the version of the node the consume connection reaches, and a broker that ignores the header returns copies at once, so they use up their levels early.

Startup checks and warnings

Delayed redelivery adds checks to StartAsync on every transport (interval count and range, Inbox schedule, transport capability) and, on RabbitMQ, topology checks of the endpoint and level queues. A failed check stops the start with BareWireConfigurationException and the option name; warnings are logged and the bus still starts. See RabbitMQ Transport - Startup topology validation.

Metrics and alerts

An endpoint with delayed redelivery reports four counters:

Counter Suggested alert
barewire.messages.redelivery_scheduled A sustained rise: a dependency is failing
barewire.messages.redelivery_exhausted Any increase: messages were dead-lettered after every level, or after the deferrals of a level ran out
barewire.messages.redelivery_failed Any increase, by reason (timeout and confirm_nack point at the broker)
barewire.messages.redelivery_deferred A sustained rise: Inbox claims are held longer than the levels

Alert also on the depth of the level queues and of the dead-letter queue. Tags and the delayed_redelivery span are described in Observability.

Connection blocked

RabbitMQ consumption and publication use separate connections, so acknowledgements keep flowing while the broker blocks publishing. The republish of a copy does not wait for the block to end: it waits at most DelayedRedeliveryConfirmTimeout, then records redelivery_failed with reason=timeout, backs off and requeues the original, and the confirm channel is recreated after 3 consecutive timeouts.

Two groups of consumers slow down during a block:

  • consumers that publish through the bus, once the bounded outgoing channel is full (with the default FullMode = Wait), because the pending batch waits for connection.unblocked;
  • endpoints with delayed redelivery whose messages fail: the original keeps its credit for the timeout plus the backoff, and an endpoint that settles sequentially waits with its whole pump.

Every copy published during a block can produce a duplicate after the block ends; the number grows with the length of the block and with concurrency. Consumers that publish should use the Outbox: a delivery that was acknowledged can still have publications in the outgoing channel of the process, and those are lost if the process crashes.

Startup connections

The RabbitMQ bus opens both connections, consume and publish, in StartAsync. See RabbitMQ Transport - Bus start.

Comparison with MassTransit

Aspect BareWire
API naming UseDelayedRedelivery with Intervals, Handle, Ignore, in MassTransit style, with no dependency on MassTransit
Delay mechanism Level queues declared explicitly with DeclareDelayedRedelivery (manual topology), or the experimental broker delivery time; no scheduler and no broker plugin
Message format The copy keeps the raw message; no envelope is added
Exclusions Serialization errors and unknown payloads are never redelivered later, whatever the filters
Startup Schedule, topology and transport support are validated when the bus starts

Sample

See: samples/BareWire.Samples.DelayedRedelivery/

Run the sample through the Aspire AppHost, which provides the RabbitMQ connection string. The guest/guest connection string in the sample is only a local fallback; in production use dedicated credentials and TLS.

See also