Introduction
Message brokers are widely used in distributed applications to help services communicate reliably. An application can publish a message to a broker, and another service can process it independently. This approach allows services to work without waiting for each other and makes it easier to scale individual components.
However, message processing does not always succeed on the first attempt. A consumer may encounter a temporary database failure, an unavailable external service, invalid message data, or an unexpected application error. In many cases, retrying the message can solve the problem. But what happens when the message continues to fail?
Repeatedly processing the same failed message is not a reliable solution. It can waste application resources, create unnecessary network traffic, and delay other messages. In some situations, a single problematic message can repeatedly block a queue or partition.
This is where a Dead-Letter Queue, commonly called a DLQ, becomes useful.
A Dead-Letter Queue provides a separate location for messages that cannot be processed successfully under the configured delivery and retry rules. Instead of retrying a problematic message indefinitely, the broker or application moves it to a separate queue where it can be investigated and handled safely.
In this article, we will understand how dead-letter queues work and implement a practical dead-letter processing workflow in an ASP.NET Core application. We will also explore retry policies, message failure classification, dead-letter storage, monitoring, and safe message replay.
What Is a Dead-Letter Queue?
A Dead-Letter Queue is a separate queue or message destination used to store messages that cannot be processed successfully through the normal message-processing workflow.
Normally, a consumer receives a message, performs the required business operation, and acknowledges the message to the broker. If processing fails, the message may be retried according to the broker's delivery policy.
However, some messages continue to fail even after multiple attempts. Rather than allowing these messages to retry forever, the messaging system can move them to a Dead-Letter Queue.
For example, imagine an order service publishes an OrderPlaced event. A payment service receives the event and attempts to process the payment. The payment service fails because the message contains an invalid currency code.
Retrying the same message will not correct the invalid currency code. The consumer will continue to fail unless the message or its processing requirements are corrected.
After the configured number of attempts, the message can be moved to a Dead-Letter Queue. The normal payment queue can then continue processing other messages.
The dead-letter message remains available for investigation. Developers or support teams can examine the original payload, identify the failure, correct the underlying issue, and decide whether the message should be replayed.
A Dead-Letter Queue is not simply a place to discard failed messages. It is an important part of a reliable message-processing and recovery strategy.
Why Do Messages Move to a Dead-Letter Queue?
Messages can fail for different reasons. Understanding the failure type is important because not every error should be handled in the same way.
Invalid Message Data
A message may contain missing fields, an invalid identifier, an unsupported currency, or a value that does not satisfy business validation rules.
For example, a payment event might contain a negative payment amount. If the application does not support negative payment requests, the message cannot be processed normally.
Retrying the message without correcting the data will not help. Such messages should usually be treated as permanent failures and moved to a dead-letter destination or another controlled rejection workflow.
Repeated Database Failures
A consumer may fail because the database is temporarily unavailable, a connection cannot be established, or a database command times out.
These failures are often temporary. The application should first attempt a controlled retry.
If the database remains unavailable beyond the configured retry limit, the broker may eventually move the message to the Dead-Letter Queue.
However, a database outage can affect many messages at once. Moving every affected message immediately into a DLQ may create a large backlog that later needs to be replayed. Retry delays, circuit breakers, and broker delivery policies should therefore be designed together.
External Service Failures
A message consumer may depend on another service, such as a payment gateway, customer service, or inventory API.
If the external service is temporarily unavailable, retrying the message after a delay may allow processing to succeed.
If the service returns a permanent rejection, such as an unsupported operation or invalid account, repeated retries may be unnecessary.
The application should classify the failure based on the actual response and the external service's documented behavior.
Unsupported Message Types or Versions
A consumer may receive an event type or schema version that it does not understand.
For example, a newer producer may publish OrderArchived version 3 while an older consumer only supports version 1 and version 2.
The consumer should not silently acknowledge the message or repeatedly retry it without a plan. It should record the unsupported event information and route the message to a controlled failure-handling process.
Processing Timeouts
A message may take longer to process than the broker's configured visibility timeout or lock duration.
The broker may consider the message abandoned and make it available again. This can lead to repeated deliveries even when the original consumer is still working.
Long-running consumers should use appropriate message-lock renewal or visibility-timeout settings. They should also avoid performing unnecessarily slow operations while holding a message.
Understanding Retry and Dead-Letter Processing
Retries and dead-letter handling are related, but they serve different purposes.
A retry gives a consumer another opportunity to process a message. Dead-letter handling removes a repeatedly failing message from the normal processing flow so that it can be investigated separately.
A typical processing workflow looks like this:
<escape>```text
Message Published
|
v
Message Broker
|
v
Consumer Receives Message
|
v
Process Message
|
+---- Success ----> Acknowledge Message
|
+---- Failure
|
v
Is Failure Temporary?
|
+-----+-----+
| |
Yes No
| |
v v
Retry Dead-Letter
| |
v v
Retry Limit Investigation
|
+----+----+
| |
Attempts Attempts
Remaining Exhausted
| |
v v
Retry Dead-Letter
The important decision is whether the failure is temporary or permanent.
A temporary failure may succeed when the dependency becomes available again. A permanent failure usually requires a correction to the message, the application, or the business data.
A production application should avoid treating every exception as a temporary failure. For example, retrying a message containing invalid JSON will not make the JSON valid.
## Dead-Letter Queue vs. Retry Queue
A retry queue and a Dead-Letter Queue have different responsibilities.
| Feature | Retry Queue | Dead-Letter Queue |
|---|---|---|
| Purpose | Give a message another processing opportunity | Store messages that cannot be processed normally |
| Processing | Scheduled for another attempt | Requires investigation or a recovery workflow |
| Typical errors | Temporary database or network failures | Invalid payloads or exhausted retries |
| Expected outcome | Message returns to normal processing | Message remains isolated until handled |
| Ownership | Usually automated | Often requires operational oversight |
A retry queue can be used to delay a message before another processing attempt. A Dead-Letter Queue is generally used after the message has reached a configured failure condition.
Some brokers provide delayed delivery and dead-letter functionality directly. Others require applications to implement retry queues and message forwarding.
The correct design depends on the broker and the application's delivery requirements.
## Creating the ASP.NET Core Project
We will create a simple ASP.NET Core application that processes order messages and records failed messages for investigation.
The implementation will use:
- ASP.NET Core for the application.
- Entity Framework Core for database operations.
- SQL Server for persistent storage.
- A message-processing service for business operations.
- A dead-letter record for failed-message information.
- A consumer abstraction for integration with a message broker.
Create a Web API project:
```bash
dotnet new webapi -n DeadLetterQueueDemo
cd DeadLetterQueueDemo
Install the SQL Server provider:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Install the EF Core design package:
dotnet add package Microsoft.EntityFrameworkCore.Design
For this example, we will keep the business processing and dead-letter storage logic separate. The message broker integration will be represented through an abstraction because acknowledgment, retry, and dead-letter APIs differ between brokers.
Creating the Order Message Model
First, create the message model that the consumer will receive.
public sealed class OrderPlacedMessage
{
public Guid MessageId { get; init; }
public Guid OrderId { get; init; }
public decimal Amount { get; init; }
public string Currency { get; init; } = string.Empty;
public DateTime OccurredAtUtc { get; init; }
public string? CorrelationId { get; init; }
}
MessageId uniquely identifies the message. It should remain unchanged when the broker redelivers the same message.
OrderId identifies the business order associated with the event. Amount and Currency contain the payment-related information required by the consumer.
CorrelationId helps connect related operations across services. For example, if an order event passes through the order service, payment service, and notification service, the same correlation identifier can help trace the workflow in application logs.
A stable message identifier is especially important when a message is retried or replayed. If every retry creates a new MessageId, the consumer cannot reliably identify repeated delivery.
Creating the Dead-Letter Entity
The application needs a way to retain information about messages that cannot be processed successfully.
Create a DeadLetterMessage entity:
public sealed class DeadLetterMessage
{
public long Id { get; set; }
public Guid MessageId { get; set; }
public string MessageType { get; set; } = string.Empty;
public string Payload { get; set; } = string.Empty;
public string FailureReason { get; set; } = string.Empty;
public string FailureCategory { get; set; } = string.Empty;
public int DeliveryAttempts { get; set; }
public string? CorrelationId { get; set; }
public DateTime FirstFailedAtUtc { get; set; }
public DateTime DeadLetteredAtUtc { get; set; }
public bool IsResolved { get; set; }
public DateTime? ResolvedAtUtc { get; set; }
}
Each property provides information that can help during investigation.
MessageId identifies the original message. MessageType identifies the event type, while Payload stores the original message content.
FailureReason contains a readable explanation of the failure. FailureCategory classifies the problem, such as Validation, DependencyUnavailable, UnsupportedMessage, or ProcessingLimitExceeded.
DeliveryAttempts records how many attempts were made before the message reached the dead-letter workflow. CorrelationId connects the failure to the larger business operation.
FirstFailedAtUtc records when the application first encountered the failure. DeadLetteredAtUtc records when the message was moved to the dead-letter workflow.
IsResolved and ResolvedAtUtc help track whether the failure has been investigated and handled.
A production system may also include properties such as the original queue name, broker message identifier, consumer name, exception type, stack trace, and replay count.
Be careful when storing message payloads and exception details. They may contain personal information, payment data, access tokens, or other sensitive information. Apply suitable access controls, retention policies, and data-masking rules.
Creating the Order Entity
For the example, create a simple order entity:
public sealed class Order
{
public Guid Id { get; set; }
public decimal Amount { get; set; }
public string Currency { get; set; } = string.Empty;
public string Status { get; set; } = "Pending";
public DateTime UpdatedAtUtc { get; set; }
}
The order will be updated when a valid OrderPlaced message is processed.
The example uses a simple order status update to demonstrate message processing. In a real application, payment authorization, inventory reservation, and other business operations should be implemented through their own services and reliability mechanisms.
Configuring Entity Framework Core
Create an ApplicationDbContext class:
using Microsoft.EntityFrameworkCore;
public sealed class ApplicationDbContext : DbContext
{
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Order> Orders => Set<Order>();
public DbSet<DeadLetterMessage> DeadLetterMessages =>
Set<DeadLetterMessage>();
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Order>(entity =>
{
entity.HasKey(x => x.Id);
entity.Property(x => x.Currency)
.HasMaxLength(10)
.IsRequired();
entity.Property(x => x.Status)
.HasMaxLength(50)
.IsRequired();
});
modelBuilder.Entity<DeadLetterMessage>(entity =>
{
entity.HasKey(x => x.Id);
entity.HasIndex(x => x.MessageId);
entity.Property(x => x.MessageType)
.HasMaxLength(200)
.IsRequired();
entity.Property(x => x.FailureCategory)
.HasMaxLength(100)
.IsRequired();
entity.Property(x => x.FailureReason)
.HasMaxLength(2000)
.IsRequired();
});
}
}
The DeadLetterMessages table stores failed-message information. The index on MessageId helps the application find records for a particular message.
This example does not make MessageId unique because the same logical message may fail in multiple processing workflows or be recorded again after an explicit replay, depending on the operational design.
If your application requires exactly one dead-letter record per original message, use a unique constraint and update the existing record when another failure occurs. The correct choice depends on whether you want one consolidated record per message or a history of individual failure attempts.
Configuring the Database Connection
Add a connection string to appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=DeadLetterQueueDb;Trusted_Connection=True;TrustServerCertificate=True;"
}
}
Register the database context and services in Program.cs:
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ApplicationDbContext>(
options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString(
"DefaultConnection")));
builder.Services.AddScoped<OrderMessageProcessor>();
builder.Services.AddScoped<DeadLetterService>();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
Create and apply the database migration:
dotnet ef migrations add CreateDeadLetterTables
dotnet ef database update
The database now contains the Orders and DeadLetterMessages tables.
Classifying Message Processing Failures
Before implementing the consumer, it is useful to define how the application classifies failures.
A common mistake is to catch every exception and move the message directly to the Dead-Letter Queue. This can cause temporary failures to become permanent operational problems.
For example, a short database outage should not necessarily send every incoming message to the dead-letter destination. The application should allow a controlled retry when the error is likely to be temporary.
Create a simple failure category:
public enum MessageFailureCategory
{
Validation,
UnsupportedMessage,
DependencyUnavailable,
ProcessingLimitExceeded,
Unexpected
}
This classification gives the application a consistent way to describe failures.
Validation represents messages that contain invalid or incomplete business data. UnsupportedMessage represents event types or versions that the consumer cannot handle.
DependencyUnavailable represents temporary problems with a database or another service. ProcessingLimitExceeded represents messages that have exceeded the configured retry limit. Unexpected represents failures that do not fit the other categories.
Now create a custom exception for invalid messages:
public sealed class MessageValidationException : Exception
{
public MessageValidationException(string message)
: base(message)
{
}
}
A custom exception helps the application distinguish business validation failures from infrastructure failures.
You can create additional exception types for unsupported events or other permanent processing problems when the application requires more detailed classification.
Implementing the Order Message Processor
Create the OrderMessageProcessor class:
using Microsoft.EntityFrameworkCore;
public sealed class OrderMessageProcessor
{
private readonly ApplicationDbContext _dbContext;
public OrderMessageProcessor(
ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task ProcessAsync(
OrderPlacedMessage message,
CancellationToken cancellationToken)
{
ValidateMessage(message);
var order = await _dbContext.Orders
.FirstOrDefaultAsync(
x => x.Id == message.OrderId,
cancellationToken);
if (order is null)
{
throw new MessageValidationException(
$"Order {message.OrderId} was not found.");
}
order.Status = "Processing";
order.Amount = message.Amount;
order.Currency = message.Currency;
order.UpdatedAtUtc = DateTime.UtcNow;
await _dbContext.SaveChangesAsync(
cancellationToken);
}
private static void ValidateMessage(
OrderPlacedMessage message)
{
if (message.MessageId == Guid.Empty)
{
throw new MessageValidationException(
"MessageId is required.");
}
if (message.OrderId == Guid.Empty)
{
throw new MessageValidationException(
"OrderId is required.");
}
if (message.Amount <= 0)
{
throw new MessageValidationException(
"Order amount must be greater than zero.");
}
if (string.IsNullOrWhiteSpace(message.Currency))
{
throw new MessageValidationException(
"Currency is required.");
}
}
}
The processor validates the message before attempting to update the order.
This is important because invalid input should be rejected before it reaches the business operation. For example, an order with a zero or negative amount may violate the application's business rules.
The processor then retrieves the order and updates its status and payment-related information.
This is a simplified example. In a production application, you should also consider whether the order is in a state that permits the requested operation. For example, an already cancelled order should not automatically be moved to Processing just because another OrderPlaced event arrives.
Business-state validation should be part of the processing service rather than relying only on message structure validation.
Implementing the Dead-Letter Service
The DeadLetterService will save failed-message information in the database.
Create the service:
using System.Text.Json;
public sealed class DeadLetterService
{
private readonly ApplicationDbContext _dbContext;
private readonly ILogger<DeadLetterService> _logger;
public DeadLetterService(
ApplicationDbContext dbContext,
ILogger<DeadLetterService> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task StoreAsync(
OrderPlacedMessage message,
MessageFailureCategory category,
string reason,
int deliveryAttempts,
CancellationToken cancellationToken)
{
var payload = JsonSerializer.Serialize(message);
var deadLetter = new DeadLetterMessage
{
MessageId = message.MessageId,
MessageType = nameof(OrderPlacedMessage),
Payload = payload,
FailureReason = reason,
FailureCategory = category.ToString(),
DeliveryAttempts = deliveryAttempts,
CorrelationId = message.CorrelationId,
FirstFailedAtUtc = DateTime.UtcNow,
DeadLetteredAtUtc = DateTime.UtcNow,
IsResolved = false
};
_dbContext.DeadLetterMessages.Add(deadLetter);
await _dbContext.SaveChangesAsync(
cancellationToken);
_logger.LogWarning(
"Message {MessageId} moved to dead-letter storage. Category: {Category}",
message.MessageId,
category);
}
}
The service serializes the original message and stores it along with failure information.
Keeping the original payload is useful because developers may need to examine exactly what the consumer received. The failure category and reason help identify whether the problem came from invalid data, an unsupported event, or a processing limit.
The service also records the number of delivery attempts. This information helps determine whether the message failed immediately or only after several retries.
This example stores dead-letter information in SQL Server. A real broker may also provide its own Dead-Letter Queue. In that case, the broker's dead-letter destination should normally be the primary location for the original message, while the database can store an operational record for searching, reporting, and administration.
Do not assume that a database insert and a broker dead-letter operation are automatically part of one transaction. They are separate systems unless a specific transactional integration is available.
Implementing the Message Handling Workflow
The next step is to create a service that coordinates processing, retry decisions, and dead-letter storage.
Create a result model:
public sealed class MessageProcessingResult
{
public bool IsSuccessful { get; init; }
public bool IsDeadLettered { get; init; }
public string? FailureReason { get; init; }
}
Now create the message handler:
public sealed class OrderMessageHandler
{
private const int MaxAttempts = 3;
private readonly OrderMessageProcessor _processor;
private readonly DeadLetterService _deadLetterService;
private readonly ILogger<OrderMessageHandler> _logger;
public OrderMessageHandler(
OrderMessageProcessor processor,
DeadLetterService deadLetterService,
ILogger<OrderMessageHandler> logger)
{
_processor = processor;
_deadLetterService = deadLetterService;
_logger = logger;
}
public async Task<MessageProcessingResult> HandleAsync(
OrderPlacedMessage message,
int deliveryAttempts,
CancellationToken cancellationToken)
{
try
{
await _processor.ProcessAsync(
message,
cancellationToken);
return new MessageProcessingResult
{
IsSuccessful = true
};
}
catch (MessageValidationException ex)
{
await MoveToDeadLetterAsync(
message,
MessageFailureCategory.Validation,
ex.Message,
deliveryAttempts,
cancellationToken);
return new MessageProcessingResult
{
IsDeadLettered = true,
FailureReason = ex.Message
};
}
catch (Exception ex)
when (deliveryAttempts >= MaxAttempts)
{
_logger.LogError(
ex,
"Message {MessageId} failed after {Attempts} attempts.",
message.MessageId,
deliveryAttempts);
await MoveToDeadLetterAsync(
message,
MessageFailureCategory.ProcessingLimitExceeded,
ex.Message,
deliveryAttempts,
cancellationToken);
return new MessageProcessingResult
{
IsDeadLettered = true,
FailureReason = ex.Message
};
}
}
private Task MoveToDeadLetterAsync(
OrderPlacedMessage message,
MessageFailureCategory category,
string reason,
int deliveryAttempts,
CancellationToken cancellationToken)
{
return _deadLetterService.StoreAsync(
message,
category,
reason,
deliveryAttempts,
cancellationToken);
}
}
The handler coordinates the processing workflow.
If the message is processed successfully, the handler returns a successful result.
If the message contains invalid business data, the handler immediately moves it to dead-letter storage. Retrying invalid data would not normally solve the problem.
For other exceptions, the handler checks the delivery attempt count. When the configured limit is reached, it stores the message in the dead-letter workflow.
If a temporary error occurs before the retry limit is reached, the exception is allowed to propagate to the message consumer. The consumer can then use the broker's retry or negative-acknowledgment mechanism.
There is an important operational detail here: the handler must not treat every exception as a permanent failure. The example uses a simple retry-limit rule, but production systems should classify known transient and permanent errors more precisely.
For example, a database timeout may be transient, while a missing required field is permanent. A payment gateway response indicating that a payment method is invalid may also be permanent, while a temporary service-unavailable response may be retryable.
The classification should be based on the actual exception or response, not simply on the fact that an operation failed.
Connecting the Handler to a Message Broker
The message handler is independent of the broker. We can define an abstraction for the broker consumer:
public interface IOrderMessageConsumer
{
Task StartAsync(
Func<OrderPlacedMessage, int, CancellationToken, Task> handler,
CancellationToken cancellationToken);
}
The consumer implementation is responsible for:
Receiving messages from the broker.
Deserializing the message payload.
Providing the delivery attempt count.
Calling the message handler.
Acknowledging successful messages.
Scheduling retries for retryable failures.
Moving exhausted or permanently failed messages to the broker's DLQ when supported.
The important part is the acknowledgment sequence.
If the handler returns successfully with IsSuccessful set to true, the consumer can acknowledge the message.
If the handler returns successfully with IsDeadLettered set to true, the consumer can acknowledge the original delivery only after the dead-letter record has been stored successfully or the broker's dead-letter operation has completed.
If the handler throws an exception, the consumer should follow the configured retry behavior.
The broker-specific implementation must make these decisions explicitly. A generic interface cannot define the exact acknowledgment behavior for RabbitMQ, Azure Service Bus, or Kafka because their delivery and failure mechanisms differ.
For example, RabbitMQ consumers typically use acknowledgments and negative acknowledgments. Azure Service Bus supports message completion, abandonment, and dead-letter operations. Kafka consumers generally manage message offsets and require careful coordination between processing and offset commits.
Do not acknowledge a message before its required database or dead-letter operation has completed. Otherwise, a crash can result in message loss.
Configuring Retry Delays
Retrying a failed message immediately is not always a good idea.
Suppose a database becomes unavailable for 30 seconds. If every consumer retries every failed message immediately, the application may create a large number of repeated database requests while the database is still recovering.
A better approach is to introduce a delay between attempts.
One common strategy is exponential backoff. The delay increases after each failed attempt.
For example:
Attempt | Retry delay |
|---|
First retry | 2 seconds |
Second retry | 4 seconds |
Third retry | 8 seconds |
Fourth retry | 16 seconds |
The application can calculate a delay using the following method:
public static TimeSpan GetRetryDelay(
int attempt,
int initialDelaySeconds = 2,
int maximumDelaySeconds = 60)
{
var exponent = Math.Clamp(attempt - 1, 0, 10);
var delaySeconds = Math.Min(
initialDelaySeconds * Math.Pow(2, exponent),
maximumDelaySeconds);
return TimeSpan.FromSeconds(delaySeconds);
}
The method increases the delay as the attempt count increases and limits the maximum delay to avoid waiting indefinitely.
In production, consider adding random jitter to the delay. Without jitter, many consumers that fail at the same time may retry together, creating another burst of requests.
The retry policy should also respect broker-specific delivery limits and message-lock durations. If the broker supports scheduled redelivery, it is generally preferable to let the broker manage delayed delivery rather than keeping a consumer thread occupied while waiting.
Implementing a Dead-Letter Inspection API
A dead-letter workflow is more useful when authorized operators can inspect failed messages.
We can create a simple administrative API to retrieve unresolved dead-letter records.
Create a controller:
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
[ApiController]
[Route("api/admin/dead-letters")]
public sealed class DeadLetterController : ControllerBase
{
private readonly ApplicationDbContext _dbContext;
public DeadLetterController(
ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
[HttpGet]
public async Task<IActionResult> GetUnresolvedAsync(
CancellationToken cancellationToken)
{
var messages = await _dbContext.DeadLetterMessages
.AsNoTracking()
.Where(x => !x.IsResolved)
.OrderBy(x => x.DeadLetteredAtUtc)
.Select(x => new
{
x.Id,
x.MessageId,
x.MessageType,
x.FailureCategory,
x.FailureReason,
x.DeliveryAttempts,
x.DeadLetteredAtUtc,
x.CorrelationId
})
.ToListAsync(cancellationToken);
return Ok(messages);
}
}
The endpoint returns unresolved messages ordered by the time they entered dead-letter storage.
It intentionally does not return the complete payload. In many applications, message payloads contain business or personal information that should not be exposed through a general administrative listing.
A separate detail endpoint can return the payload to authorized operators when necessary.
This endpoint must be protected by authentication and role-based authorization. Dead-letter records may contain sensitive information, and replay operations can trigger real business actions.
For a production administrative API, also implement pagination, filtering by message type or failure category, date ranges, and audit logging.
Implementing Safe Message Replay
After investigating a dead-letter message, an operator may decide that it can be processed again.
For example, a message might have failed because a required database record was temporarily missing. Once the missing data is corrected, the original message may be valid for replay.
However, replaying a message is not simply a matter of copying its payload back into the original queue.
The application must consider whether the original business operation has already been completed.
Imagine that a consumer successfully updates the order in SQL Server but crashes before acknowledging the broker. The broker may redeliver the message, and the message could eventually reach the dead-letter destination because of repeated acknowledgment failures.
If an operator replays it without checking the business state, the application may repeat the operation.
This is why replay must preserve the original MessageId and use the same idempotency protections as normal message processing.
Create a method for marking a dead-letter record as resolved:
public sealed class DeadLetterResolutionService
{
private readonly ApplicationDbContext _dbContext;
public DeadLetterResolutionService(
ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<bool> MarkResolvedAsync(
long deadLetterId,
CancellationToken cancellationToken)
{
var message = await _dbContext.DeadLetterMessages
.FirstOrDefaultAsync(
x => x.Id == deadLetterId,
cancellationToken);
if (message is null || message.IsResolved)
{
return false;
}
message.IsResolved = true;
message.ResolvedAtUtc = DateTime.UtcNow;
await _dbContext.SaveChangesAsync(
cancellationToken);
return true;
}
}
This method updates the resolution status. It does not itself replay the message.
A separate replay service should retrieve the original payload, validate it, and publish it to the appropriate destination. The replay process should record who initiated the operation, when it happened, and whether the replay succeeded.
For sensitive business operations, require an explicit operator confirmation before replaying a message.
Also consider using a new replay operation identifier for tracking while preserving the original MessageId for deduplication. These identifiers serve different purposes: the original MessageId protects the business operation from duplicate execution, while the replay identifier helps track an operational recovery attempt.
If the original message failed because of invalid data, replaying the unchanged payload will not help. The data or processing logic must be corrected first.
Important Considerations When Using a Broker's Native Dead-Letter Queue
The database implementation above demonstrates how to retain failed-message information. In production, many applications should also use the broker's native dead-letter capabilities.
A broker-managed DLQ provides several benefits:
It retains the original broker message and its metadata.
It can automatically receive messages after configured delivery limits are reached.
It keeps failed messages separate from normal queue traffic.
It can support broker-specific inspection and replay workflows.
It reduces the need to implement all failure-routing behavior inside the application.
However, native dead-letter behavior differs between brokers.
For example, Azure Service Bus provides a dedicated dead-letter subqueue for supported queues and subscriptions. RabbitMQ commonly uses dead-letter exchanges and routing rules. Kafka does not provide a universal built-in DLQ mechanism in the same way; applications commonly publish failed records to a separate topic.
Therefore, configure the DLQ according to the broker being used.
Also, do not assume that storing a failure in SQL Server and moving the same message to a broker DLQ happen atomically. If the application stores the database record successfully but crashes before moving the broker message, the two systems may contain different information.
A reliable design should make the recovery operation repeatable and use the original MessageId to identify the same logical message.
Monitoring Dead-Letter Messages
A Dead-Letter Queue is useful only when failed messages are visible and someone or something can act on them.
A production application should monitor several important metrics.
Dead-Letter Message Count
Track how many messages enter the DLQ over time.
A sudden increase may indicate a deployment problem, an unsupported message contract, a database outage, or an external service failure.
Oldest Unresolved Message
The age of the oldest unresolved message helps identify whether failures are being investigated promptly.
A small number of unresolved messages may not be a serious problem if they are recent. However, messages that remain unresolved for several days may indicate that the recovery process is not working.
Failure Category
Group dead-letter messages by their failure category.
For example, a high number of Validation failures may indicate a producer problem. A high number of DependencyUnavailable failures may indicate infrastructure instability.
This classification makes it easier to identify the actual source of failures rather than examining every message individually.
Retry Attempts
Track how many messages fail once, twice, or repeatedly.
If most messages succeed after one retry, the issue may be a temporary dependency problem. If many messages reach the retry limit, the application may need a better failure-handling strategy.
Replay Success Rate
Track how many replay attempts result in successful processing.
A low replay success rate may indicate that operators are replaying messages before correcting the underlying problem.
These metrics can be connected to an application monitoring platform and used to create alerts for unexpected increases in dead-letter traffic.
Security and Data Retention Considerations
Dead-letter messages often contain the same information as the original application events. Depending on the application, this information may include customer details, order information, account identifiers, or other sensitive business data.
Do not treat the DLQ as an unrestricted debugging location.
Apply role-based access controls so that only authorized users can inspect message payloads and initiate replay operations.
Avoid storing passwords, access tokens, payment credentials, and unnecessary personal information in event payloads. If sensitive data must be included, apply suitable encryption and masking controls.
Set a retention period based on business and operational requirements. Keeping every failed message forever can increase storage costs and create unnecessary data exposure.
Before deleting old records, make sure they are no longer required for investigation, compliance, or recovery. Keep an audit trail of important administrative actions even when the original message payload is eventually removed.
Best Practices for Building a Reliable Dead-Letter Workflow
Classify Failures Before Deciding to Retry
Not every exception should be retried.
Validation errors and unsupported message types are generally permanent until the data or application is corrected. Network failures and temporary dependency outages may be retryable.
Use clear exception types and failure categories so that the consumer can make consistent decisions.
Configure a Limited Retry Policy
Avoid retrying messages forever.
Set a maximum number of attempts and introduce appropriate delays between retries. Use exponential backoff and jitter where suitable.
The retry policy should account for the broker's own delivery limits so that the application and broker do not create conflicting retry behavior.
Preserve the Original Message
Store enough information to investigate and recover the message.
At a minimum, retain its original identifier, event type, payload or secure payload reference, failure reason, delivery count, and relevant correlation information.
Do not modify the original message silently during replay.
Make Message Processing Idempotent
A message may have been processed successfully even if the broker did not receive its acknowledgment.
Use the Inbox Pattern, unique message identifiers, database transactions, or other idempotency mechanisms to prevent repeated business operations.
Dead-letter replay should follow the same protections as normal message processing.
Protect the Dead-Letter Workflow
Dead-letter inspection and replay endpoints should be restricted to authorized users.
Record administrative actions and make replay operations auditable. A replay can trigger real business operations, so it should not be available as an unrestricted public API.
Monitor and Alert on Dead-Letter Traffic
Track the number of failed messages, failure categories, retry counts, and unresolved message age.
Create alerts for unusual increases or messages that remain unresolved beyond the expected recovery period.
Test Failure and Recovery Scenarios
Test invalid messages, temporary database failures, repeated external service errors, consumer restarts, and exhausted retries.
Also test replay behavior and verify that replaying a previously processed message does not repeat its business operation.
A dead-letter workflow should be tested as a complete recovery process, not just as a mechanism for saving failed messages.
Common Mistakes to Avoid
Moving Every Failed Message Directly to the DLQ
Temporary failures should usually receive a controlled retry opportunity.
Moving every failed message immediately to the DLQ can create unnecessary operational work and prevent automatic recovery from short-lived problems.
Retrying Permanent Failures Indefinitely
Invalid payloads and unsupported event types will not normally become valid through repeated delivery.
Classify failures and move permanent failures to a controlled dead-letter workflow.
Acknowledging Before Saving the Failed Message
If the application acknowledges the original broker message before its dead-letter record is safely stored or its broker dead-letter operation completes, a crash can result in losing the message.
Complete the required failure-storage or dead-letter operation before acknowledging the original delivery.
Replaying Messages Without Checking Idempotency
A message may have completed its business operation before the consumer failed to acknowledge it.
Replaying it without checking the original MessageId can repeat business operations.
Preserve the original identifier and use the same deduplication mechanism during replay.
Storing Sensitive Information Without Protection
Dead-letter payloads may contain sensitive business data.
Apply access controls, secure storage, data masking, encryption where appropriate, and a clear retention policy.
Treating the DLQ as Permanent Storage
A Dead-Letter Queue is a recovery mechanism, not necessarily a permanent archive.
Messages should be investigated, resolved, replayed when appropriate, or removed according to a defined retention policy.
Conclusion
A Dead-Letter Queue is an important part of reliable message processing in ASP.NET Core applications. It provides a controlled location for messages that cannot be processed successfully through normal delivery and retry mechanisms.
A well-designed workflow distinguishes temporary failures from permanent failures, applies limited retries with suitable delays, and moves exhausted or invalid messages to a dead-letter destination.
The application should retain enough information to investigate failures and provide a secure way to resolve or replay messages. Replay must preserve the original message identity and use the same idempotency protections as normal processing.
For production systems, combine broker-native dead-letter capabilities with clear failure classification, monitoring, access controls, and a documented recovery process. Also remember that a database record and a broker DLQ operation are separate actions unless the infrastructure provides an appropriate transactional mechanism.
The goal is not simply to move failed messages out of the main queue. It is to make failures visible, prevent repeated processing from consuming resources, and provide a safe way to recover messages without creating duplicate business operations.
Join the conversation! Your thoughts help the community grow.