Introduction
Message brokers help applications communicate without requiring services to call each other directly. An order service can publish events, a payment service can process payment requests, and a notification service can send updates to customers. Each service works independently and communicates through messages.
However, distributed messaging introduces a challenge that developers must consider: messages do not always arrive in the same order in which they were published.
Consider an order workflow in which an order service publishes three events:
OrderCreated
OrderConfirmed
OrderCancelled
The expected sequence is that the receiving service processes OrderCreated first, followed by OrderConfirmed and OrderCancelled.
But a message broker or consumer may deliver OrderConfirmed before OrderCreated. If the receiving service processes events immediately without checking their order, it might attempt to confirm an order that does not exist yet.
A similar problem can occur when two events update the same customer account, inventory item, payment record, or other business entity. Processing an older event after a newer event can overwrite the latest data with outdated information.
This problem is known as out-of-order message processing.
In this article, we will understand why messages arrive out of order, how this affects ASP.NET Core applications, and how to handle it using event sequence numbers, aggregate versions, database transactions, and controlled retry strategies. We will also explore practical implementation patterns and production considerations for reliable event processing.
What Is Out-of-Order Message Processing?
Out-of-order message processing occurs when a consumer receives or processes messages in a different order from the order in which the producer created them.
For example, suppose an inventory service publishes the following events for product ID 101:
Event | Available quantity | Sequence |
|---|
InventoryUpdated | 50 | 1 |
InventoryReserved | 40 | 2 |
InventoryReleased | 45 | 3 |
The receiving service expects to process these events in sequence.
However, because of network delays, parallel processing, retries, or consumer restarts, it might receive them in this order:
Arrival order | Event | Available quantity | Sequence |
|---|
1 | InventoryUpdated | 50 | 1 |
2 | InventoryReleased | 45 | 3 |
3 | InventoryReserved | 40 | 2 |
If the consumer simply updates the inventory quantity whenever an event arrives, it first stores 50, then 45, and finally 40.
The final value is 40, even though the latest event represents a quantity of 45.
This is a data consistency problem. The consumer has processed every message, but the resulting data is incorrect because it processed the events in the wrong order.
It is important to understand that message arrival order and message processing order are two different things. Even if a broker delivers messages in order, multiple consumers or parallel processing can cause the actual business operations to complete in a different order.
Why Do Messages Arrive Out of Order?
There are several reasons why a distributed application may receive messages in an unexpected sequence.
Parallel Message Processing
Many applications process messages concurrently to improve throughput. Instead of waiting for one message to finish before processing the next, the consumer allows multiple messages to run simultaneously.
Suppose a service receives two events for the same order. The first event requires a database query and takes 500 milliseconds, while the second event requires only 100 milliseconds.
If both events are processed concurrently, the second event may finish first. Even though the first event arrived earlier, its business operation completes later.
This is particularly important when multiple events update the same database record. Parallel processing can produce incorrect results if the application assumes that arrival order automatically guarantees completion order.
Message Retries
Message brokers commonly retry messages when consumers fail to process them.
Imagine that a consumer receives an OrderCreated event but encounters a temporary database error. The broker schedules the message for retry.
Meanwhile, the next event, OrderConfirmed, may be delivered successfully to another consumer instance.
The confirmation event can therefore be processed before the original creation event succeeds.
Retries improve reliability, but they can change the order in which messages are processed. Applications should not assume that a retried message will always be completed before later messages.
Multiple Consumer Instances
Production applications often run multiple instances of the same consumer to handle increased message traffic.
For example, an application may have three consumer instances processing messages from the same queue. One instance might receive an event and experience a slow database operation, while another instance processes a later event quickly.
This can result in different completion times.
Scaling consumers horizontally improves throughput, but it also means the application must consider ordering at the business entity level.
Multiple Message Broker Partitions or Queues
Some message brokers distribute messages across multiple queues or partitions to improve scalability.
Messages related to the same business entity may end up in different partitions if the producer does not use a consistent partitioning key.
For example, two events for the same order might be published to different partitions. Consumers can process those partitions independently, so there is no automatic ordering guarantee between them.
When ordering matters, the producer and broker must be configured to keep related messages within an ordering boundary, such as a partition or session associated with the same business identifier.
Network Delays and Consumer Restarts
Distributed applications depend on networks, databases, brokers, and other services. A temporary network interruption or consumer restart can delay one message while later messages continue to move through the system.
The original message may eventually be redelivered after the later message has already been processed.
These situations are normal in distributed systems. Reliable applications should use explicit ordering information instead of relying only on message delivery behavior.
Why Message Ordering Matters in Business Applications
Not every application requires strict message ordering.
For example, an application that sends independent promotional emails may not care whether one email event is processed before another. Each event can be handled independently.
However, ordering becomes important when events represent changes to the same business entity.
Consider these examples:
An order must be created before it can be confirmed.
A payment must be authorized before it can be captured.
Inventory must be reserved before a reservation can be released.
An account must be opened before a balance adjustment can be applied.
A customer profile must be created before another service updates its address.
In these situations, processing events in the wrong order can cause invalid state transitions, missing records, or incorrect calculations.
The first step is to identify which events require ordering. Applying strict ordering to every message can reduce throughput and introduce unnecessary complexity.
A practical approach is to preserve ordering only for events that belong to the same business entity or workflow.
Understanding Event Sequence Numbers
One of the most reliable ways to identify out-of-order messages is to include a sequence number in every event.
A sequence number represents the logical position of an event within a particular business entity's event stream.
For example, an order service might publish the following events:
public sealed class OrderEvent
{
public Guid MessageId { get; init; }
public Guid OrderId { get; init; }
public long SequenceNumber { get; init; }
public string EventType { get; init; } = string.Empty;
public DateTime OccurredAtUtc { get; init; }
}
The MessageId uniquely identifies the message and is useful for duplicate detection. The OrderId identifies the business entity. The SequenceNumber identifies the event's position within that order's event sequence.
These values have different purposes and should not be treated as interchangeable.
For example, an OrderCreated event might have sequence number 1, OrderConfirmed might have sequence number 2, and OrderCancelled might have sequence number 3.
The consumer can compare the incoming sequence number with the last successfully processed sequence number for that order.
If the incoming sequence number is the next expected value, the consumer can process it.
If it is lower than or equal to the last processed value, it may be a duplicate or an old event.
If it is greater than the next expected value, one or more earlier events may be missing.
This approach gives the consumer a way to make processing decisions based on business sequence rather than arrival time.
Creating the ASP.NET Core Project
We will implement a simple order event consumer using ASP.NET Core, Entity Framework Core, and SQL Server.
Create a Web API project:
dotnet new webapi -n OrderedMessageDemo
cd OrderedMessageDemo
Install the SQL Server provider:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Install the EF Core design package for migrations:
dotnet add package Microsoft.EntityFrameworkCore.Design
The example will use two main database entities:
The second table provides duplicate detection. This is useful because message ordering and duplicate delivery are separate problems. A message can arrive in the correct order but still be delivered more than once.
Creating the Database Entities
Create the OrderState entity:
public sealed class OrderState
{
public Guid OrderId { get; set; }
public string Status { get; set; } = "Created";
public long LastProcessedSequence { get; set; }
public DateTime UpdatedAtUtc { get; set; }
}
The LastProcessedSequence property stores the sequence number of the most recent event successfully applied to the order.
For example, if the consumer has processed events 1, 2, and 3, this property contains 3. When event 4 arrives, it is the next expected event.
Now create the ProcessedOrderEvent entity:
public sealed class ProcessedOrderEvent
{
public long Id { get; set; }
public Guid MessageId { get; set; }
public Guid OrderId { get; set; }
public long SequenceNumber { get; set; }
public DateTime ProcessedAtUtc { get; set; }
}
This table records successfully processed event identifiers. The MessageId helps prevent the same message from being applied more than once.
The SequenceNumber provides an additional record of the event's position in the order's history.
In a production application, you may also store the event type, correlation ID, and other metadata that helps with auditing and troubleshooting.
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<OrderState> Orders => Set<OrderState>();
public DbSet<ProcessedOrderEvent> ProcessedEvents =>
Set<ProcessedOrderEvent>();
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<OrderState>(entity =>
{
entity.HasKey(x => x.OrderId);
entity.Property(x => x.Status)
.HasMaxLength(50)
.IsRequired();
});
modelBuilder.Entity<ProcessedOrderEvent>(entity =>
{
entity.HasKey(x => x.Id);
entity.HasIndex(x => x.MessageId)
.IsUnique();
entity.HasIndex(x => new
{
x.OrderId,
x.SequenceNumber
})
.IsUnique();
});
}
}
The unique index on MessageId prevents the same message from being recorded twice.
The second unique index prevents two different messages from being recorded with the same sequence number for the same order.
This is useful when the producer guarantees that each order has one event per sequence number. If the application intentionally supports multiple events at the same sequence position, the event identity and ordering model must be adjusted accordingly.
The database constraints are important because application-level checks alone cannot protect against concurrent consumers. Two consumers might both read the same state and attempt to insert an event simultaneously.
The database must enforce the uniqueness rules even when multiple application instances are running.
Configuring the Database Connection
Add a connection string to appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=OrderedMessageDb;Trusted_Connection=True;TrustServerCertificate=True;"
}
}
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<OrderEventProcessor>();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
Create the database migration:
dotnet ef migrations add CreateOrderEventTables
dotnet ef database update
The database now contains the order state and processed event tables, including the unique indexes required for duplicate detection.
Implementing the Order Event Processor
The processor must compare the incoming event's sequence number with the last processed sequence number.
There are three important cases:
The incoming sequence number is exactly the next expected number. The event can be processed.
The incoming sequence number is less than or equal to the last processed number. The event is old or duplicated.
The incoming sequence number is greater than the next expected number. One or more earlier events are missing.
Create the OrderEventProcessor class:
using Microsoft.EntityFrameworkCore;
public sealed class OrderEventProcessor
{
private readonly ApplicationDbContext _dbContext;
private readonly ILogger<OrderEventProcessor> _logger;
public OrderEventProcessor(
ApplicationDbContext dbContext,
ILogger<OrderEventProcessor> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task ProcessAsync(
OrderEvent message,
CancellationToken cancellationToken)
{
await using var transaction =
await _dbContext.Database.BeginTransactionAsync(
cancellationToken);
try
{
var order = await _dbContext.Orders
.FirstOrDefaultAsync(
x => x.OrderId == message.OrderId,
cancellationToken);
if (order is null)
{
throw new InvalidOperationException(
$"Order {message.OrderId} was not found.");
}
var existingEvent =
await _dbContext.ProcessedEvents
.AnyAsync(
x => x.MessageId == message.MessageId,
cancellationToken);
if (existingEvent)
{
await transaction.RollbackAsync(
cancellationToken);
_logger.LogInformation(
"Duplicate event {MessageId} received.",
message.MessageId);
return;
}
var expectedSequence =
order.LastProcessedSequence + 1;
if (message.SequenceNumber < expectedSequence)
{
await transaction.RollbackAsync(
cancellationToken);
_logger.LogWarning(
"Old event {MessageId} received for order {OrderId}.",
message.MessageId,
message.OrderId);
return;
}
if (message.SequenceNumber > expectedSequence)
{
await transaction.RollbackAsync(
cancellationToken);
throw new MissingSequenceException(
message.OrderId,
expectedSequence,
message.SequenceNumber);
}
ApplyEvent(order, message);
order.LastProcessedSequence =
message.SequenceNumber;
order.UpdatedAtUtc = DateTime.UtcNow;
_dbContext.ProcessedEvents.Add(
new ProcessedOrderEvent
{
MessageId = message.MessageId,
OrderId = message.OrderId,
SequenceNumber = message.SequenceNumber,
ProcessedAtUtc = DateTime.UtcNow
});
await _dbContext.SaveChangesAsync(
cancellationToken);
await transaction.CommitAsync(
cancellationToken);
_logger.LogInformation(
"Event {MessageId} processed for order {OrderId}.",
message.MessageId,
message.OrderId);
}
catch
{
await transaction.RollbackAsync(
cancellationToken);
throw;
}
}
private static void ApplyEvent(
OrderState order,
OrderEvent message)
{
switch (message.EventType)
{
case "OrderCreated":
order.Status = "Created";
break;
case "OrderConfirmed":
order.Status = "Confirmed";
break;
case "OrderCancelled":
order.Status = "Cancelled";
break;
default:
throw new InvalidOperationException(
$"Unsupported event type: {message.EventType}");
}
}
}
The processor begins by opening a database transaction. It then retrieves the current order state and checks whether the message has already been processed.
If the MessageId already exists, the processor identifies the delivery as a duplicate and returns without repeating the business operation.
Next, it calculates the expected sequence number by adding one to LastProcessedSequence.
If the incoming sequence number is lower than the expected number, the event is older than the next event required by the current state. The processor skips it. This situation should still be logged or monitored because it can indicate a delayed message or a replay.
If the incoming sequence number is higher than expected, the processor knows that an earlier event is missing. It throws a MissingSequenceException rather than applying the event immediately.
Only when the incoming sequence number matches the expected value does the processor update the order state.
The business update, sequence number update, and processed event record are saved within the same transaction. This is important because the application must not advance the sequence number without also applying the associated business operation.
If the database transaction fails, all changes are rolled back. The event can then be retried according to the broker's delivery policy.
Creating a Missing Sequence Exception
The processor needs a specific exception to indicate that an event arrived before an earlier event.
Create the following class:
public sealed class MissingSequenceException : Exception
{
public Guid OrderId { get; }
public long ExpectedSequence { get; }
public long ReceivedSequence { get; }
public MissingSequenceException(
Guid orderId,
long expectedSequence,
long receivedSequence)
: base(
$"Order {orderId} expected sequence " +
$"{expectedSequence}, but received {receivedSequence}.")
{
OrderId = orderId;
ExpectedSequence = expectedSequence;
ReceivedSequence = receivedSequence;
}
}
This exception contains the order identifier, the expected sequence number, and the sequence number that was actually received.
The message consumer can use this information to decide how to handle the missing event.
For example, if the processor expects sequence 2 but receives sequence 3, the consumer knows that sequence 2 must be delivered or recovered before sequence 3 can be safely applied.
A dedicated exception is more useful than a generic exception because it allows the application to distinguish an ordering problem from a database outage, invalid message, or programming error.
Handling Missing Events
Detecting an out-of-order event is only the first part of the solution. The application must also decide what to do with it.
There are several approaches, and the correct choice depends on the business requirements and message broker.
Retry the Message Later
The simplest approach is to avoid acknowledging the message and allow the broker to redeliver it later.
For example, suppose the consumer receives sequence 3 while sequence 2 has not yet been processed. The consumer can temporarily fail the processing attempt and allow the broker's retry mechanism to deliver sequence 3 again.
During that time, sequence 2 may arrive and be processed successfully. When sequence 3 is delivered again, the consumer can now process it.
This approach is easy to implement, but it depends on the broker's retry behavior. Some brokers may repeatedly deliver the same message and delay other messages in the same queue. Others may move the message to a dead-letter queue after a configured number of attempts.
Use delayed retries when missing events are expected to arrive shortly and the broker supports a suitable retry mechanism.
Store Events Until Earlier Events Arrive
Another approach is to temporarily store out-of-order events in a pending event table.
For example, if sequence 3 arrives while sequence 2 is missing, the consumer stores sequence 3 without applying its business changes.
When sequence 2 arrives, the application processes it and then checks whether sequence 3 is available in the pending table.
This approach is useful when events may arrive with significant delays and repeatedly sending the same message through the broker would create unnecessary traffic.
A pending event entity could look like this:
public sealed class PendingOrderEvent
{
public long Id { get; set; }
public Guid MessageId { get; set; }
public Guid OrderId { get; set; }
public long SequenceNumber { get; set; }
public string Payload { get; set; } = string.Empty;
public DateTime ReceivedAtUtc { get; set; }
}
The Payload property stores the event data so that the application can deserialize and process it later.
The pending event table should have a unique constraint on the appropriate combination of order identifier and sequence number, assuming the producer guarantees one event per sequence position.
The consumer should not mark a pending event as successfully processed in the normal processed-event table. It has only stored the event; the business operation has not yet been applied.
A separate status or pending-event record makes this distinction clear.
When the missing event arrives, the application can process consecutive pending events in sequence. For example, after processing sequence 2, it can look for sequence 3, then sequence 4, and continue until the next expected event is unavailable.
The processing and removal of pending records should also be transactional. Otherwise, the application could delete a pending event without successfully applying its business changes.
This approach offers more control, but it requires additional storage, cleanup, monitoring, and recovery logic.
Use Broker-Level Ordering
Some message brokers support ordering through partitions, sessions, or similar mechanisms.
For example, a broker may allow messages with the same partition key to be routed to the same partition. If the producer uses OrderId as the partition key, events for the same order can be kept within the same ordering boundary.
This can reduce the possibility of out-of-order delivery for related messages.
However, broker-level ordering does not automatically guarantee that application processing completes in order. If the consumer receives messages sequentially but starts processing them concurrently, a later event can still finish first.
To preserve ordering, the consumer must also avoid parallel processing of messages within the same ordering group.
Broker-level ordering and application-level sequence validation work best together. The broker helps preserve delivery order, while the application verifies that business state transitions are valid.
Preventing Concurrent Updates With Database Concurrency Control
Sequence validation introduces another important problem: two consumers may process different events for the same order at the same time.
Suppose the current sequence number is 4. Two consumer instances receive events 5 and 6.
Both instances read LastProcessedSequence as 4. The first instance sees event 5 as valid. The second instance also sees that event 6 is greater than the next expected sequence and rejects it.
That situation is safe if the second instance performs its validation after reading the updated state. But concurrent transactions can create race conditions if both instances read and update the same record before either transaction commits.
Database concurrency control is needed to prevent this.
One option is to use optimistic concurrency with a concurrency token. EF Core can detect when another transaction has modified the record since it was read.
For example, add a RowVersion property to the OrderState entity:
public sealed class OrderState
{
public Guid OrderId { get; set; }
public string Status { get; set; } = "Created";
public long LastProcessedSequence { get; set; }
public DateTime UpdatedAtUtc { get; set; }
public byte[] RowVersion { get; set; } = [];
}
Configure it in ApplicationDbContext:
modelBuilder.Entity<OrderState>()
.Property(x => x.RowVersion)
.IsRowVersion();
SQL Server maintains the rowversion value whenever the row is updated.
When EF Core saves changes, it includes the original rowversion value in the update condition. If another transaction has already modified the record, the update affects no rows and EF Core throws a DbUpdateConcurrencyException.
The application can then roll back the transaction and retry the processing operation after loading the latest order state.
This ensures that two consumers cannot silently overwrite each other's changes based on outdated data.
However, optimistic concurrency does not automatically solve every ordering problem. The application must still validate the sequence number after reloading the latest state. A concurrency exception should trigger a controlled retry, not unconditional application of the event.
Another option is to lock the relevant order row while processing the event. This can be useful when the application requires strict serialization for each order, but locking can reduce throughput if transactions are long-running.
Choose the approach according to the expected message volume and the amount of contention on individual business entities.
Handling Message Ordering With Multiple Consumers
When an application runs multiple consumer instances, ordering must be considered at the level of the business entity.
For example, an application may process events for thousands of different orders simultaneously. There is no need to process every event in the entire application sequentially.
Instead, the application can process events for different orders concurrently while ensuring that events for the same order are processed in sequence.
This is commonly called per-entity ordering.
Consider the following events:
Order ID | Sequence | Event |
|---|
Order A | 1 | Created |
Order A | 2 | Confirmed |
Order A | 3 | Cancelled |
Order B | 1 | Created |
Order B | 2 | Confirmed |
The application can process Order A and Order B at the same time. However, it should not process Order A sequence 3 before sequence 2.
A partition key based on OrderId can help group related messages. Another approach is to use a keyed processing mechanism that ensures only one active processing operation exists for a particular order at a time.
Regardless of the implementation, database sequence validation should remain in place. It protects the application against unexpected delivery patterns, retries, and concurrency conditions.
Handling Event Versioning
Sequence numbers help preserve event order, but event contracts can also change over time.
For example, an older version of OrderConfirmed may contain only an OrderId, while a newer version may include confirmation details and customer information.
If a consumer receives an event with an unsupported schema version, it should not simply ignore the event and advance the sequence number.
Doing so could create a gap in the business history.
Include an event version in the message contract:
public sealed class OrderEvent
{
public Guid MessageId { get; init; }
public Guid OrderId { get; init; }
public long SequenceNumber { get; init; }
public int EventVersion { get; init; }
public string EventType { get; init; } = string.Empty;
public DateTime OccurredAtUtc { get; init; }
}
The consumer can use EventVersion to select the correct deserialization and processing logic.
If an event version is not supported, the application should route it to a controlled failure-handling process, such as a dead-letter queue, rather than silently advancing the sequence.
For long-running systems, event contracts should be designed to support backward compatibility where possible. Adding optional fields is generally easier to manage than changing the meaning or type of existing fields.
Important Considerations for Sequence Number Generation
The reliability of sequence-based processing depends on how sequence numbers are created.
A sequence number should be generated by a trusted producer that owns the business entity or its event stream.
For example, the order service should assign sequence numbers to events associated with an order. The payment service should not independently generate sequence numbers for those same events because it does not own the order's event history.
Sequence numbers must also be assigned consistently when multiple application instances can update the same entity.
A simple approach is to increment a version field in the database within the same transaction that saves the business change and creates the outgoing event.
For example, an order service can update its aggregate version from 4 to 5 and create an event with sequence number 5 in the same database transaction.
If the application uses the Outbox Pattern, the event and the updated aggregate version can be saved together. This prevents the producer from publishing an event with a sequence number that does not correspond to a committed business change.
Avoid using timestamps as a replacement for sequence numbers. Timestamps can have limited precision, clock differences, and concurrent event-generation problems. A timestamp tells you approximately when something happened, but it does not always establish an unambiguous order between events.
Best Practices for Production Applications
Use Ordering Only Where the Business Requires It
Strict ordering across an entire application can reduce throughput and make scaling difficult.
Identify which events affect the same business entity and preserve ordering only within those groups. Independent operations should be allowed to run concurrently.
Include Sequence Numbers in Event Contracts
A sequence number gives consumers a reliable way to identify missing, repeated, and out-of-order events.
Make sure the producer generates the number consistently and that it remains associated with the same business entity throughout the event lifecycle.
Keep Message Deduplication and Ordering Separate
A unique MessageId identifies duplicate delivery. A sequence number identifies the logical position of an event.
Both are important, but they solve different problems.
An event can have a new MessageId and still arrive out of order. Similarly, the same MessageId can be delivered multiple times even when its sequence number is correct.
Use both mechanisms when the business workflow requires them.
Use Database Transactions for Business Updates
The business update, processed-message record, and sequence number change should be committed together.
This prevents the application from recording an event as processed while leaving the business state unchanged.
Handle Missing Events Explicitly
Do not silently skip an event when a sequence gap is detected.
Choose a clear strategy: retry the message, store it as pending, or recover the missing event through a controlled workflow.
The correct choice depends on the broker, message volume, and business requirements.
Add Monitoring for Sequence Gaps
Record the expected and received sequence numbers whenever an ordering problem occurs.
Monitor the number of events waiting for missing predecessors, the age of pending events, retry counts, and dead-letter messages.
These metrics help identify problems in producers, brokers, and consumers before they become serious data consistency issues.
Test Concurrent Processing
Test multiple consumer instances processing events for the same business entity.
Also test delayed events, duplicate deliveries, missing sequence numbers, consumer restarts, database failures, and concurrency conflicts.
Testing only the normal event sequence does not provide enough confidence for a production message-processing system.
Common Mistakes to Avoid
Assuming Broker Delivery Order Guarantees Processing Order
A broker may preserve delivery order under certain configurations, but parallel consumers and asynchronous business operations can still change completion order.
Use broker ordering features where appropriate and validate the business sequence inside the consumer.
Using Timestamps as the Only Ordering Mechanism
Timestamps may not uniquely identify the order of concurrent events. Different services can also have slightly different system clocks.
Use sequence numbers generated by the service that owns the business entity.
Processing an Event When a Sequence Gap Exists
If the consumer expects sequence 2 but receives sequence 3, applying sequence 3 immediately may create an invalid business state.
Detect the gap and use a retry or pending-event strategy.
Advancing the Sequence Number Before Applying the Business Change
If the application saves the new sequence number but fails before applying the business operation, later messages may be accepted even though the earlier event was never successfully handled.
Save the business changes, processed-event record, and sequence number in one transaction.
Allowing Multiple Consumers to Update the Same Entity Without Concurrency Control
Two consumers can read the same previous state and attempt to update it simultaneously.
Use optimistic concurrency, database locking, or per-entity processing controls to prevent conflicting updates.
Treating Every Older Event as Harmless
An event with an old sequence number may be a duplicate, a delayed message, or a conflicting event with an unexpected identifier.
Use MessageId-based deduplication and sequence validation together. Log unexpected combinations so that they can be investigated.
Conclusion
Out-of-order message processing is a common challenge in distributed applications. Messages can arrive or finish processing in an unexpected order because of parallel consumers, retries, network delays, multiple broker partitions, and application restarts.
For business workflows where event order matters, relying only on the order in which messages arrive is not sufficient.
A reliable ASP.NET Core consumer should use stable message identifiers for duplicate detection and sequence numbers for ordering validation. It should compare each incoming event with the last successfully processed sequence number and reject or defer events when an earlier event is missing.
Database transactions ensure that business changes, processed-event records, and sequence updates remain consistent. Concurrency control protects the application when multiple consumer instances attempt to update the same business entity.
For production applications, combine application-level sequence validation with appropriate broker ordering features, controlled retries, pending-event storage where necessary, event versioning, and monitoring.
The goal is not to force every message in the system to run sequentially. It is to preserve the correct order for related business operations while allowing independent events to be processed concurrently. This approach helps build scalable, reliable, and consistent event-driven applications with ASP.NET Core.
Join the conversation! Your thoughts help the community grow.