Introduction
Message-based communication is widely used in modern applications to connect different services. Instead of making every operation through a direct HTTP request, an application can publish messages to a message broker such as RabbitMQ, Azure Service Bus, or Kafka. Other services subscribe to these messages and process them independently.
This approach improves scalability and reduces direct dependencies between services. However, message-based communication introduces an important challenge: the same message can be delivered more than once.
For example, imagine an order service that publishes an OrderPlaced event. A payment service receives the event, processes the payment, and updates the order status. After completing the database transaction, the payment service crashes before acknowledging the message to the broker. When the service restarts, the broker may deliver the same message again.
If the payment service processes the message without checking whether it has already been handled, it might attempt to charge the customer twice.
This is where the Inbox Pattern becomes useful.
The Inbox Pattern provides a reliable way to identify previously received messages and prevent the same message from being processed repeatedly. It is particularly useful in distributed systems where message brokers provide at-least-once delivery rather than guaranteed exactly-once processing.
In this article, we will implement the Inbox Pattern in an ASP.NET Core application using Entity Framework Core and SQL Server. We will also understand how to handle duplicate messages, manage database transactions, deal with failures, and make message processing more reliable in production environments.
What Is the Inbox Pattern?
The Inbox Pattern is a message-processing technique in which a receiving application stores the unique identifier of every message it processes.
Before applying the business operation associated with a message, the application checks whether that message has already been recorded in its inbox table. If the message has already been processed, the application skips the business operation. If it is a new message, the application records it and processes the associated business logic.
For example, consider an application that receives payment requests from an order service. Each payment request contains a unique MessageId.
When the payment service receives the message for the first time, it stores the MessageId in its database and processes the payment-related business operation. If the same message arrives again, the service finds the existing MessageId and recognizes that the message has already been handled.
The most important part of this approach is that the inbox record and the related business changes must be committed in the same database transaction.
Without this transaction boundary, the application could record a message as processed without completing its business operation, or complete the business operation without recording the message. Both situations can cause data inconsistencies.
The Inbox Pattern does not stop a broker from delivering duplicate messages. Instead, it makes the receiving application capable of recognizing and safely ignoring duplicates.
Why Do Duplicate Messages Occur?
Most message brokers are designed to provide reliable message delivery. To avoid losing messages, they commonly use acknowledgment mechanisms.
A consumer receives a message, processes it, and sends an acknowledgment to the broker. The broker removes the message from the pending queue after receiving the acknowledgment.
However, there is a small but important gap between completing the business operation and acknowledging the message.
Consider the following sequence:
The broker delivers a message to the consumer.
The consumer processes the message.
The consumer saves the changes in the database.
The application crashes before acknowledging the message.
The broker does not receive the acknowledgment.
The broker delivers the same message again.
From the broker's perspective, the message was not successfully acknowledged. It cannot safely assume that the consumer completed the operation, so it delivers the message again.
This behavior protects against message loss, but it also means consumers must be prepared to receive duplicates.
Other situations can also result in repeated delivery:
A network connection fails while the consumer is acknowledging a message.
A consumer restarts while a message is still being processed.
A message-processing operation exceeds the broker's visibility timeout or acknowledgment deadline.
Multiple consumers compete to process messages.
A message is manually replayed during troubleshooting or recovery.
These situations are normal possibilities in distributed systems. Instead of assuming that every message will arrive only once, applications should be designed to handle repeated delivery safely.
Inbox Pattern vs. Outbox Pattern
The Inbox and Outbox Patterns solve related but different problems.
The Outbox Pattern protects outgoing messages. It ensures that an application can save its business data and the event that needs to be published within the same database transaction.
The Inbox Pattern protects incoming message processing. It ensures that a consumer can identify messages that have already been processed and avoid repeating the associated database operation.
Consider an order and payment workflow.
When a customer places an order, the order service saves the order and an OrderPlaced event in its database transaction. This is the responsibility of the Outbox Pattern.
The payment service receives the OrderPlaced event. It records the message identifier and processes the payment-related database changes in one transaction. This is the responsibility of the Inbox Pattern.
Pattern | Main responsibility | Where it is used |
|---|
Outbox Pattern | Reliably publish outgoing messages | Message-producing service |
Inbox Pattern | Deduplicate incoming messages | Message-consuming service |
Idempotent operation | Make repeated operations safe | Business logic and external integrations |
These patterns can be used together. In fact, using an Outbox Pattern in a producer and an Inbox Pattern in a consumer creates a stronger foundation for reliable communication between services.
Understanding the Inbox Processing Flow
Before writing code, it is important to understand the complete processing flow.
Suppose a payment service receives an OrderPlaced event. The event contains a unique MessageId that remains unchanged whenever the broker redelivers the message.
The consumer follows these steps:
Receive the message from the broker.
Read its unique MessageId.
Begin a database transaction.
Insert the MessageId into the Inbox table.
If the identifier already exists, treat the message as a duplicate and skip the business operation.
If the identifier is new, execute the business operation.
Commit the inbox record and business changes together.
Acknowledge the message to the broker only after the transaction commits successfully.
The transaction is the most important part of this process.
Imagine that the application inserts the inbox record and then crashes before updating the payment information. If both operations are inside the same database transaction, the database rolls back the uncommitted changes. When the broker redelivers the message, the consumer can safely process it again.
Similarly, if the database transaction commits successfully but the application crashes before acknowledging the broker, the broker may redeliver the message. This time, the Inbox table contains the MessageId, so the consumer skips the business operation and acknowledges the duplicate.
This is how the Inbox Pattern handles the most common failure scenarios.
Creating the ASP.NET Core Project
We will create a simple ASP.NET Core application that receives order events and processes them using an inbox table.
The implementation uses:
ASP.NET Core for the application.
Entity Framework Core for database operations.
SQL Server for persistent storage.
A message consumer abstraction for receiving messages.
A database transaction for atomic message processing.
You can create the project using the following command:
dotnet new webapi -n InboxPatternDemo
cd InboxPatternDemo
Install the Entity Framework Core SQL Server provider:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
For migrations, install the EF Core design package:
dotnet add package Microsoft.EntityFrameworkCore.Design
The project will contain the following main components:
Each component has a specific responsibility. Keeping these responsibilities separate makes the implementation easier to test and maintain.
Creating the Message Model
Every incoming message should have a unique identifier. The identifier is the key used by the Inbox Pattern to recognize duplicate deliveries.
Create an OrderPlacedMessage class:
public sealed class OrderPlacedMessage
{
public Guid MessageId { get; init; }
public Guid OrderId { get; init; }
public decimal Amount { get; init; }
public DateTime OccurredAtUtc { get; init; }
public string? CorrelationId { get; init; }
}
The MessageId identifies a particular message, while OrderId identifies the business entity associated with that message.
These two identifiers serve different purposes. An order can generate several different events during its lifetime, and each event should have its own MessageId. Therefore, using OrderId as the deduplication key would be incorrect because it could cause legitimate later events for the same order to be rejected.
The OccurredAtUtc property records when the event happened. The CorrelationId helps connect related operations across multiple services when investigating a distributed workflow.
The MessageId must remain unchanged when a message is retried or redelivered. If the producer generates a new identifier every time it republishes the same logical event, the consumer will treat each delivery as a new message.
Creating the Inbox Entity
The Inbox table stores information about incoming messages that have been successfully processed.
Create an InboxMessage entity:
public sealed class InboxMessage
{
public long Id { get; set; }
public Guid MessageId { get; set; }
public string MessageType { get; set; } = string.Empty;
public DateTime ReceivedAtUtc { get; set; }
public DateTime ProcessedAtUtc { get; set; }
}
The Id property is the database-generated primary key. MessageId stores the unique identifier received from the message broker.
MessageType identifies the type of event that was processed. This can be useful when an application consumes several event types and needs to investigate processing behavior.
ReceivedAtUtc records when the application received the message, while ProcessedAtUtc records when the processing transaction completed.
For a simple transactional Inbox implementation, the record should be inserted and committed together with the business changes. This means a committed inbox record represents successfully completed database processing, not merely a message that was received.
If you need to track messages that are currently being processed, or messages that failed, you can introduce additional status fields and a separate processing workflow. That is a more advanced design and should not be confused with the basic transactional Inbox Pattern.
Creating the Order Entity
For this example, the payment service will update an order's payment status after receiving an OrderPlaced event.
Create an Order entity:
public sealed class Order
{
public Guid Id { get; set; }
public decimal Amount { get; set; }
public string PaymentStatus { get; set; } = "Pending";
public DateTime UpdatedAtUtc { get; set; }
}
In a real application, payment processing would usually involve a dedicated payment record or payment service. Here, we are using a simple order entity to demonstrate how inbox deduplication works with business data.
The important requirement is that the business change must be committed in the same database transaction as the inbox record.
Configuring Entity Framework Core
Next, create the ApplicationDbContext class.
using Microsoft.EntityFrameworkCore;
public sealed class ApplicationDbContext : DbContext
{
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<InboxMessage> InboxMessages =>
Set<InboxMessage>();
public DbSet<Order> Orders =>
Set<Order>();
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<InboxMessage>(entity =>
{
entity.HasKey(x => x.Id);
entity.HasIndex(x => x.MessageId)
.IsUnique();
entity.Property(x => x.MessageType)
.HasMaxLength(200)
.IsRequired();
});
modelBuilder.Entity<Order>(entity =>
{
entity.HasKey(x => x.Id);
entity.Property(x => x.PaymentStatus)
.HasMaxLength(50)
.IsRequired();
});
}
}
The most important configuration is the unique index on MessageId.
This index prevents the database from storing two inbox records with the same message identifier. It also protects the application against concurrent processing.
For example, suppose two consumer instances receive the same message at almost the same time. Both instances might initially believe that the message has not been processed. If the application relies only on checking the database before inserting a record, both instances could pass that check.
A unique database constraint prevents both inserts from succeeding. Only one transaction can successfully insert that MessageId. The other transaction receives a unique-constraint violation and must treat the message as a duplicate.
This is why a unique database index is essential. An application-level check alone is not sufficient to guarantee deduplication under concurrent processing.
Configuring the Database Connection
Add the database connection string to appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=InboxPatternDb;Trusted_Connection=True;TrustServerCertificate=True;"
}
}
For production applications, store credentials in a secure configuration provider rather than committing passwords or sensitive connection details to source control.
Register the database context 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<MessageProcessingService>();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
The AddDbContext registration makes ApplicationDbContext available through dependency injection. EF Core creates a context for each dependency-injection scope, which is suitable for a message-processing operation that performs a database transaction.
Create and apply the database migration:
dotnet ef migrations add CreateInboxTables
dotnet ef database update
After the migration is applied, the database will contain the Orders and InboxMessages tables. The InboxMessages table will also have a unique index on MessageId.
Implementing the Message Processing Service
Now we can implement the central part of the Inbox Pattern.
Create a MessageProcessingService class:
using Microsoft.EntityFrameworkCore;
public sealed class MessageProcessingService
{
private readonly ApplicationDbContext _dbContext;
private readonly ILogger<MessageProcessingService> _logger;
public MessageProcessingService(
ApplicationDbContext dbContext,
ILogger<MessageProcessingService> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task<bool> ProcessOrderPlacedAsync(
OrderPlacedMessage message,
CancellationToken cancellationToken)
{
await using var transaction =
await _dbContext.Database.BeginTransactionAsync(
cancellationToken);
try
{
var inboxMessage = new InboxMessage
{
MessageId = message.MessageId,
MessageType = nameof(OrderPlacedMessage),
ReceivedAtUtc = DateTime.UtcNow,
ProcessedAtUtc = DateTime.UtcNow
};
_dbContext.InboxMessages.Add(inboxMessage);
await _dbContext.SaveChangesAsync(
cancellationToken);
var order = await _dbContext.Orders
.FirstOrDefaultAsync(
x => x.Id == message.OrderId,
cancellationToken);
if (order is null)
{
throw new InvalidOperationException(
$"Order {message.OrderId} was not found.");
}
order.PaymentStatus = "Processing";
order.UpdatedAtUtc = DateTime.UtcNow;
await _dbContext.SaveChangesAsync(
cancellationToken);
await transaction.CommitAsync(
cancellationToken);
_logger.LogInformation(
"Message {MessageId} processed successfully.",
message.MessageId);
return true;
}
catch (DbUpdateException ex)
when (IsUniqueConstraintViolation(ex))
{
await transaction.RollbackAsync(
cancellationToken);
_logger.LogInformation(
"Duplicate message {MessageId} detected.",
message.MessageId);
return false;
}
catch
{
await transaction.RollbackAsync(
cancellationToken);
throw;
}
}
private static bool IsUniqueConstraintViolation(
DbUpdateException exception)
{
return exception.InnerException is
Microsoft.Data.SqlClient.SqlException sqlException
&& (sqlException.Number == 2601
|| sqlException.Number == 2627);
}
}
This implementation uses an explicit database transaction to make inbox insertion and business processing atomic.
The first operation inserts the MessageId into the InboxMessages table. EF Core sends the insert to SQL Server when SaveChangesAsync is called. However, because the transaction has not been committed, the change is not yet permanently committed.
The service then retrieves the corresponding order and updates its payment status. If the order is missing or another processing error occurs, the transaction is rolled back. This also removes the uncommitted inbox record.
When both operations succeed, CommitAsync permanently saves the inbox record and the business change together.
The unique-constraint exception is handled separately. SQL Server error numbers 2601 and 2627 represent unique-index and primary-key violations. In this example, the unique MessageId index is the expected source of that exception.
The IsUniqueConstraintViolation method is intentionally specific to SQL Server. If you change the database provider, the exception-handling logic must be adapted to that provider.
The method returns true when a new message is processed and false when the message is identified as a duplicate. The message consumer can use this result for logging and monitoring, but both outcomes can be acknowledged to the broker once the database confirms that the message is already handled or has just been handled successfully.
One important production consideration is that not every DbUpdateException is a duplicate. The application should only treat the specific unique constraint violation on the MessageId index as a duplicate. Other database errors must be allowed to propagate so that the broker can retry the message or move it through the configured failure-handling process.
For a larger application, it is often better to use a dedicated repository or database-specific error-handling component to identify the exact constraint that failed.
Connecting the Processing Service to a Message Consumer
The processing service is responsible for database operations, but a real application also needs a message consumer that receives messages from a broker.
Different brokers provide different APIs, so we can define a simple abstraction that keeps the business processing logic independent of a particular messaging technology.
public interface IMessageConsumer
{
Task StartAsync(
Func<OrderPlacedMessage, CancellationToken, Task> handler,
CancellationToken cancellationToken);
}
The message consumer implementation is responsible for receiving messages, deserializing them, and invoking the supplied handler.
A simplified consumer integration could look like this:
public sealed class OrderMessageHandler
{
private readonly MessageProcessingService _processingService;
public OrderMessageHandler(
MessageProcessingService processingService)
{
_processingService = processingService;
}
public async Task HandleAsync(
OrderPlacedMessage message,
CancellationToken cancellationToken)
{
await _processingService.ProcessOrderPlacedAsync(
message,
cancellationToken);
}
}
The actual broker adapter should acknowledge the message only after HandleAsync completes successfully.
This ordering is important. If the consumer acknowledges a message before the database transaction commits, a database failure could result in the broker removing a message whose business operation was never saved.
The correct sequence is:
Receive the message.
Invoke the message handler.
Commit the inbox and business changes.
Acknowledge the message.
If the handler throws an exception, the consumer should not acknowledge the message as successfully processed. The broker can then redeliver it according to its retry and visibility settings.
If the handler identifies a duplicate, it can return successfully because the original processing transaction has already committed. The consumer can acknowledge that delivery without repeating the business operation.
The exact acknowledgment API depends on the broker. For example, RabbitMQ uses delivery acknowledgments, while Azure Service Bus uses message completion. The abstraction should preserve the same processing order regardless of the broker being used.
Understanding What Happens During Application Failures
The main value of the Inbox Pattern becomes clearer when we examine different failure scenarios.
Scenario 1: The Application Crashes Before the Transaction Commits
Suppose the consumer receives a new message and inserts its MessageId into the Inbox table. It then starts updating the order but crashes before committing the transaction.
Because the transaction was not committed, SQL Server rolls back the uncommitted changes when the connection is terminated.
The broker does not receive a successful acknowledgment, so it can deliver the message again. Since the inbox record was also rolled back, the consumer can insert the MessageId and process the business operation normally.
This prevents the application from incorrectly treating an incomplete operation as completed.
Scenario 2: The Application Crashes After the Transaction Commits
Now suppose the consumer successfully inserts the inbox record, updates the order, and commits the transaction. Immediately afterward, the application crashes before acknowledging the broker.
The broker may deliver the same message again because it never received the acknowledgment.
When the consumer receives it, the unique MessageId constraint prevents another inbox record from being inserted. The consumer recognizes the duplicate and skips the business operation.
It can then acknowledge the message.
This is one of the most important situations handled by the Inbox Pattern. The business operation is not repeated even though the broker delivers the message again.
Scenario 3: The Database Is Temporarily Unavailable
Suppose the consumer receives a message, but SQL Server is temporarily unavailable.
The application cannot safely determine whether the message was processed or whether the inbox record exists. It should not acknowledge the message as successfully processed.
Instead, it should allow the processing attempt to fail and use the broker's retry mechanism or a controlled retry policy.
When the database becomes available, the broker can deliver the message again.
The consumer then checks the inbox through the unique insert operation and processes the message if it has not already been committed.
Scenario 4: Two Consumers Receive the Same Message
In a distributed application, multiple consumer instances may run simultaneously. Two instances might receive the same message because of redelivery, visibility timeouts, or broker-specific delivery behavior.
Both consumers may attempt to insert the same MessageId.
The unique index ensures that only one transaction can successfully insert the record. The other consumer receives a unique-constraint violation.
This prevents both instances from independently committing the same database operation.
However, the consumer should still use sensible broker settings, processing timeouts, and concurrency controls. The unique constraint is the final protection against duplicate inbox entries, not a replacement for responsible message-consumer configuration.
Important Considerations for External API Calls
The Inbox Pattern protects database operations that participate in the same transaction as the inbox record. It does not automatically protect operations performed outside that database.
For example, suppose the payment consumer does the following:
Inserts the MessageId into the Inbox table.
Calls an external payment gateway.
Updates the order in SQL Server.
Commits the database transaction.
If the payment gateway successfully charges the customer but the database transaction fails, the inbox record is rolled back. When the broker redelivers the message, the consumer may call the payment gateway again.
This can result in a duplicate charge.
The reason is that a SQL Server transaction cannot automatically roll back an operation performed by an external payment provider.
For external operations, use additional reliability mechanisms.
One option is to pass a stable idempotency key to the external API, if the provider supports it. The same logical payment operation must use the same key across retries so the provider can recognize repeated requests.
Another option is to use a separate workflow with an Outbox Pattern. The consumer can atomically record the incoming message and create an outgoing command in its database. A background worker then sends that command to the external system. The external operation still needs appropriate idempotency or reconciliation support.
The important distinction is that the Inbox Pattern protects the database transaction it controls. It does not provide global exactly-once execution across databases, payment gateways, email providers, and other independent systems.
Handling Failed and Poison Messages
Not every message-processing failure is temporary.
A temporary failure might occur because of a database timeout, a short network interruption, or an unavailable downstream dependency. Retrying such a message after a delay may allow it to succeed.
A permanent failure might occur because the message contains invalid data, references an unsupported event version, or violates a business rule that cannot be resolved through retrying.
Repeatedly retrying a permanently invalid message wastes resources and can block other messages, depending on the broker and queue configuration.
A production message-processing system should distinguish between transient and permanent failures.
For transient failures, use a limited retry policy with increasing delays. For example, the application might retry after a short delay and gradually increase the delay between attempts.
For permanent failures, send the message to a dead-letter queue or another controlled failure-handling destination. The dead-letter process should retain enough information to identify the original message, understand why processing failed, and support safe investigation or replay.
Do not insert a successful Inbox record for a message that has permanently failed before its business operation has completed. Otherwise, a later replay could be incorrectly rejected as a duplicate.
If you need to retain failed-message details, use a separate failure record or a more advanced inbox state model. Keep the meaning of successfully processed records clear.
Managing Inbox Data Retention
The Inbox table grows as the application processes more messages. If the service handles thousands or millions of events, retaining every record forever can increase storage requirements and affect database maintenance.
However, deleting inbox records too early creates a risk.
Imagine that the service deletes a MessageId after one day, but the broker or an operator replays the original message after two days. The consumer no longer has a record of the previous processing operation and may execute the business logic again.
For this reason, the retention period should be based on the maximum realistic message-redelivery and replay window.
Consider the following factors:
How long the broker can retain or redeliver a message.
Whether operators can replay messages from historical storage.
Whether messages can be restored from backups.
How long the business needs to protect against duplicate operations.
Whether the same MessageId can be replayed across different environments or workflows.
For high-volume applications, you can create a scheduled cleanup job that deletes old inbox records in controlled batches.
The cleanup process should avoid deleting records that are still within the required deduplication window. It should also be monitored so that a large cleanup operation does not create unnecessary database load.
Best Practices for Implementing the Inbox Pattern
Always Use a Stable Message Identifier
The producer should assign a unique MessageId when the event is created. The identifier must remain the same across retries and redeliveries.
Do not generate a new identifier every time a message is published again. Doing so defeats the purpose of the Inbox Pattern because the consumer will see every delivery as a different message.
Enforce Uniqueness in the Database
Always create a unique index or constraint on the MessageId column.
Checking whether a message exists before inserting it is useful for application logic, but it is not enough to handle concurrent consumers safely. The database constraint must be the final authority.
Commit the Inbox Record and Business Changes Together
The inbox record and the business data changes should participate in the same transaction.
If they are saved separately, the application can enter an inconsistent state in which the inbox says that a message was processed even though its business operation was not completed.
Acknowledge Messages Only After Successful Processing
The broker should receive an acknowledgment only after the database transaction has committed.
If the application acknowledges first and commits afterward, a failure between those operations can result in message loss.
Keep Business Logic Independent of Broker APIs
Avoid placing broker-specific acknowledgment logic inside business services.
Use a separate consumer adapter to handle message delivery and acknowledgment. Keep the processing service focused on inbox checks and business operations.
This separation makes it easier to change the message broker, test business logic independently, and support different event types.
Make External Operations Idempotent
The Inbox Pattern cannot roll back an external API call. Use stable idempotency keys, an Outbox Pattern, reconciliation, or a suitable workflow for external side effects.
Monitor Duplicate Deliveries and Processing Failures
Track how many messages are processed successfully, how many are identified as duplicates, and how many fail.
A sudden increase in duplicate deliveries may indicate consumer restarts, acknowledgment problems, visibility-timeout issues, or unstable network connections.
Monitoring helps identify these problems before they affect the reliability of the application.
Common Mistakes to Avoid
Using OrderId Instead of MessageId
An order can generate multiple events, such as OrderPlaced, OrderConfirmed, and OrderCancelled. If OrderId is used as the inbox key, processing one event might prevent another valid event for the same order from being processed.
Use a unique MessageId for each event.
Checking for Duplicates Without a Unique Constraint
A common implementation checks the Inbox table first and inserts a record only when no matching MessageId is found.
This creates a race condition when multiple consumers perform the check simultaneously. Both may see that the message is missing and attempt to process it.
Use a unique database constraint and handle the specific duplicate-key exception.
Saving the Inbox Record Before Business Processing Without a Transaction
If the inbox record is committed first and the application crashes before updating the business data, the next delivery may be ignored even though the operation never completed.
The inbox record and business changes must be part of the same transaction.
Acknowledging the Message Too Early
Acknowledging a message before committing the database transaction can cause message loss if the transaction later fails.
Always commit first and acknowledge afterward.
Assuming Inbox Provides Exactly-Once Processing
The Inbox Pattern provides deduplication for the database operation protected by its transaction. It does not guarantee exactly-once execution across independent services or external systems.
Use additional idempotency and reliability mechanisms wherever operations cross transaction boundaries.
Deleting Inbox Records Too Soon
Removing inbox records before the maximum replay window expires can allow previously processed messages to execute again.
Set retention rules according to broker behavior and business requirements.
Testing the Inbox Pattern
Testing should cover more than the successful processing of a single message. The main purpose of the Inbox Pattern is to handle failures and repeated delivery, so those situations must be tested explicitly.
Start by sending a new message with a unique MessageId. Verify that an inbox record is created and the associated business data is updated.
Next, send the same message again. Verify that the application identifies it as a duplicate and does not repeat the business operation.
Test transaction rollback by causing an exception after the inbox record has been inserted but before the business changes are committed. Verify that neither the inbox record nor the business update remains in the database.
Also test the situation where the database transaction commits but the broker acknowledgment fails. Deliver the same message again and verify that the second delivery is treated as a duplicate.
For concurrency testing, send the same message to multiple consumer instances at nearly the same time. Confirm that the unique constraint prevents multiple committed inbox records and that the business operation is not duplicated.
Use a real relational database provider for these tests. EF Core's in-memory provider does not reproduce SQL Server's unique constraints, transaction behavior, or provider-specific exceptions accurately. SQLite can be useful for some integration tests, but SQL Server integration tests are important when production uses SQL Server.
For production-level testing, also simulate database outages, broker redeliveries, consumer restarts, and dead-letter scenarios.
Advantages and Limitations of the Inbox Pattern
The Inbox Pattern offers several advantages:
It protects database operations against duplicate message delivery.
It supports reliable processing when consumers restart unexpectedly.
It reduces the risk of repeating business changes.
It works well with message brokers that provide at-least-once delivery.
It can be combined with the Outbox Pattern to improve reliability across services.
It provides a persistent record that can help with troubleshooting and auditing.
However, it also introduces some additional responsibilities.
The application needs an inbox table, unique database constraints, transaction management, and retention policies. Every consumer must follow the correct processing and acknowledgment sequence. High-volume systems also need to manage inbox storage and database write performance.
The pattern does not automatically protect external API calls, file operations, or other side effects that cannot participate in the same database transaction.
For most distributed business applications, these tradeoffs are worthwhile because preventing duplicate business operations is usually more important than avoiding a small amount of additional database work.
Conclusion
The Inbox Pattern is an important technique for building reliable message consumers in ASP.NET Core applications. It helps applications handle duplicate message delivery without repeating the same database business operation.
The key to a correct implementation is using a stable MessageId, enforcing uniqueness at the database level, and committing the inbox record together with the associated business changes in one transaction.
The consumer should acknowledge the message only after the transaction has committed. If the application crashes before the commit, the operation can be retried. If it crashes after the commit but before acknowledgment, the inbox record allows the next delivery to be recognized as a duplicate.
The pattern does not provide global exactly-once execution, especially when external services are involved. For those scenarios, combine inbox processing with idempotent APIs, the Outbox Pattern, and appropriate retry and reconciliation strategies.
When implemented correctly, the Inbox Pattern provides a practical foundation for reliable event-driven applications and helps prevent duplicate processing from creating inconsistent business data.
Join the conversation! Your thoughts help the community grow.