The Real Challenge in Event-Driven Systems Is Not Sending Messages
At first glance, event-driven architectures look quite simple. An important operation occurs in one service, the service produces an event, and other services consume that event.
Order Service
↓
OrderCreated
↓
Message Broker
↓
Inventory Service
Payment Service
Notification Service
On paper, this looks clean. In production, however, one important question quickly appears:
What happens if the database operation succeeds, but the application crashes before the event is published?
Even worse, what happens if the event is successfully published, but the application crashes before recording that the message was sent?
Reliable event-driven messaging therefore needs to solve two different problems:
- Events must not be lost.
- If the same event arrives multiple times, the same business effect must not happen multiple times.
Two commonly used patterns for solving these problems are Transactional Outbox and Idempotent Consumer.
1. The Real Problem: Dual Writes
Consider an e-commerce application that creates an order.
The application needs to perform two operations:
- Save the order to SQL Server.
- Publish an
OrderCreatedevent to the message broker.
The most obvious implementation may look like this:
var order = new Order
{
CustomerId = request.CustomerId,
TotalAmount = request.TotalAmount,
Status = "Created"
};
db.Orders.Add(order);
await db.SaveChangesAsync(cancellationToken);
await messageBus.PublishAsync(
new OrderCreatedEvent
{
OrderId = order.Id,
CustomerId = order.CustomerId,
TotalAmount = order.TotalAmount
},
cancellationToken);
Under normal conditions, this code works.
However, SQL Server and the message broker are two separate systems.
There is a very small but critical failure window between them:
Order saved to SQL Server
↓
SaveChanges succeeded
↓
APPLICATION CRASHED
↓
OrderCreated was never published
The result is an inconsistent distributed system:
- The order exists in the Orders table.
- The Inventory Service does not know about it.
- The Payment Service does not know about it.
- The Notification Service never sends a message to the customer.
From the database perspective, the operation succeeded. From the distributed-system perspective, the operation is incomplete.
This is known as the dual-write problem.
2. Does Reversing the Order Solve the Problem?
We might try publishing the event first and then writing to the database:
await messageBus.PublishAsync(
new OrderCreatedEvent(...),
cancellationToken);
db.Orders.Add(order);
await db.SaveChangesAsync(cancellationToken);
This does not solve the problem either.
Now the opposite failure scenario becomes possible:
OrderCreated published
↓
Consumer received the event
↓
Inventory was reserved
↓
SQL Server insert failed
The system has now reserved inventory for an order that does not actually exist.
Reversing the operation order does not eliminate the dual-write problem. It merely changes the type of inconsistency you can create.
3. Transactional Outbox Pattern
The core idea of the Outbox Pattern is simple:
The business data and the event that must eventually be published are stored in the same database transaction.
The event is not immediately sent to the message broker. Instead, it is first stored in an Outbox table.
API Request
↓
SQL Transaction
│
├── Orders
│
└── OutboxMessages
↓
COMMIT
↓
Outbox Worker
↓
Message Broker
If the transaction succeeds, both the order and the event record exist.
If the transaction fails, neither exists.
If the application crashes before publishing the event, the event is still safely stored in the Outbox table.
4. SQL Server Outbox Table
A production-oriented Outbox table may look like this:
CREATE TABLE OutboxMessages
(
Id UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,
AggregateType NVARCHAR(100) NOT NULL,
AggregateId NVARCHAR(100) NOT NULL,
EventType NVARCHAR(200) NOT NULL,
EventVersion INT NOT NULL DEFAULT 1,
Payload NVARCHAR(MAX) NOT NULL,
OccurredAt DATETIME2 NOT NULL,
PublishedAt DATETIME2 NULL,
AttemptCount INT NOT NULL DEFAULT 0,
NextAttemptAt DATETIME2 NULL,
LockId UNIQUEIDENTIFIER NULL,
LockedUntil DATETIME2 NULL,
LastError NVARCHAR(2000) NULL
);
A filtered index can help workers efficiently find unpublished messages:
CREATE INDEX IX_OutboxMessages_Pending
ON OutboxMessages
(
NextAttemptAt,
OccurredAt
)
WHERE PublishedAt IS NULL;
5. Outbox Entity
public sealed class OutboxMessage
{
public Guid Id { get; set; }
public string AggregateType { get; set; } = "";
public string AggregateId { get; set; } = "";
public string EventType { get; set; } = "";
public int EventVersion { get; set; } = 1;
public string Payload { get; set; } = "";
public DateTime OccurredAt { get; set; }
public DateTime? PublishedAt { get; set; }
public int AttemptCount { get; set; }
public DateTime? NextAttemptAt { get; set; }
public Guid? LockId { get; set; }
public DateTime? LockedUntil { get; set; }
public string? LastError { get; set; }
}
6. Save the Order and Event in the Same Transaction
Assume the Orders table uses an identity column.
We can first save the order, obtain its ID, create the Outbox record, and commit both operations inside the same SQL transaction.
public async Task<long> CreateOrderAsync(
CreateOrderRequest request,
CancellationToken cancellationToken)
{
await using var transaction =
await _db.Database.BeginTransactionAsync(
cancellationToken);
try
{
var order = new Order
{
CustomerId = request.CustomerId,
TotalAmount = request.TotalAmount,
Status = "Created",
CreatedAt = DateTime.UtcNow
};
_db.Orders.Add(order);
await _db.SaveChangesAsync(
cancellationToken);
var orderCreated = new OrderCreatedEvent
{
MessageId = Guid.NewGuid(),
OrderId = order.Id,
CustomerId = order.CustomerId,
TotalAmount = order.TotalAmount,
OccurredAt = DateTime.UtcNow
};
var outboxMessage = new OutboxMessage
{
Id = orderCreated.MessageId,
AggregateType = "Order",
AggregateId = order.Id.ToString(),
EventType = "OrderCreated",
EventVersion = 1,
Payload =
JsonSerializer.Serialize(orderCreated),
OccurredAt = orderCreated.OccurredAt
};
_db.OutboxMessages.Add(outboxMessage);
await _db.SaveChangesAsync(
cancellationToken);
await transaction.CommitAsync(
cancellationToken);
return order.Id;
}
catch
{
await transaction.RollbackAsync(
cancellationToken);
throw;
}
}
Now only two consistent outcomes are possible:
Order exists
+
Outbox message exists
or:
Order does not exist
+
Outbox message does not exist
The dangerous state where the order exists but the event information is lost has been removed.
7. Outbox Worker
Writing events into an Outbox table is only half of the solution.
A separate process must eventually publish those messages to the broker.
In an ASP.NET Core application, a simple implementation can use
BackgroundService.
public sealed class OutboxPublisher(
IServiceScopeFactory scopeFactory,
IMessageBus messageBus,
ILogger<OutboxPublisher> logger)
: BackgroundService
{
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using var scope =
scopeFactory.CreateScope();
var db =
scope.ServiceProvider
.GetRequiredService<ShopDbContext>();
var messages =
await db.OutboxMessages
.Where(x =>
x.PublishedAt == null &&
(x.NextAttemptAt == null ||
x.NextAttemptAt <= DateTime.UtcNow))
.OrderBy(x => x.OccurredAt)
.Take(50)
.ToListAsync(stoppingToken);
foreach (var message in messages)
{
try
{
await messageBus.PublishAsync(
message.EventType,
message.Payload,
message.Id,
stoppingToken);
message.PublishedAt =
DateTime.UtcNow;
message.LastError = null;
}
catch (Exception ex)
{
message.AttemptCount++;
message.LastError =
ex.Message;
message.NextAttemptAt =
DateTime.UtcNow.AddSeconds(
Math.Min(
300,
Math.Pow(
2,
message.AttemptCount)));
}
}
await db.SaveChangesAsync(
stoppingToken);
await Task.Delay(
TimeSpan.FromSeconds(2),
stoppingToken);
}
}
}
This demonstrates the basic Outbox publishing flow.
But there is still another critical failure window.
8. Outbox Does Not Prevent Duplicate Messages
Consider the following scenario:
Outbox Worker loaded the message
↓
Publish to broker succeeded
↓
OrderCreated is now in the broker
↓
APPLICATION CRASHED
↓
PublishedAt was never updated
When the application restarts, it checks the Outbox table.
Because PublishedAt is still NULL,
the same event is published again.
The broker may therefore receive:
OrderCreated
MessageId: ABC-123
OrderCreated
MessageId: ABC-123
This is not necessarily a bug.
Outbox-based systems usually aim for:
At-Least-Once Delivery
We prefer the possibility of duplicate messages over the possibility of lost messages.
This is why the second half of the architecture, the Idempotent Consumer, is so important.
9. The Real Failure: Processing the Same Event Twice
Assume Inventory Service receives this message:
{
"messageId": "8c36c6de-....",
"orderId": 15025,
"productId": 15,
"quantity": 2
}
If the consumer simply runs:
product.StockQuantity -= message.Quantity;
await db.SaveChangesAsync();
and the same event arrives twice:
First delivery:
Stock 10 → 8
Duplicate delivery:
Stock 8 → 6
Only two products were actually sold, but inventory was reduced by four.
In financial systems, duplicate processing can cause even more serious problems:
- The same invoice may be created twice.
- The customer may be charged twice.
- Loyalty points may be added twice.
- The same notification may be sent repeatedly.
10. Idempotent Consumer and Inbox Pattern
A consumer can store the IDs of messages it has already processed.
A simple Inbox table can be used:
CREATE TABLE InboxMessages
(
ConsumerName NVARCHAR(150) NOT NULL,
MessageId UNIQUEIDENTIFIER NOT NULL,
ProcessedAt DATETIME2 NOT NULL,
CONSTRAINT PK_InboxMessages
PRIMARY KEY
(
ConsumerName,
MessageId
)
);
The composite primary key prevents the same consumer from recording the same message twice.
11. Inbox and Business Logic Must Use the Same Transaction
The following code may initially look correct:
if (await IsProcessed(message.MessageId))
return;
await ProcessBusinessLogic(message);
await MarkAsProcessed(message.MessageId);
But another failure window exists:
Business operation completed
↓
Stock was reduced
↓
APPLICATION CRASHED
↓
MarkAsProcessed never executed
When the broker redelivers the message, the business operation executes again.
The correct approach is to write the Inbox record and the business state change inside the same transaction.
12. Idempotent Consumer Example
public async Task HandleAsync(
OrderCreatedEvent message,
CancellationToken cancellationToken)
{
const string consumerName =
"Inventory.OrderCreated";
await using var transaction =
await _db.Database.BeginTransactionAsync(
cancellationToken);
try
{
var inbox = new InboxMessage
{
ConsumerName = consumerName,
MessageId = message.MessageId,
ProcessedAt = DateTime.UtcNow
};
_db.InboxMessages.Add(inbox);
try
{
await _db.SaveChangesAsync(
cancellationToken);
}
catch (DbUpdateException ex)
when (IsDuplicateKey(ex))
{
await transaction.RollbackAsync(
cancellationToken);
// Message was already processed.
return;
}
var product =
await _db.Products
.SingleAsync(
x =>
x.Id == message.ProductId,
cancellationToken);
if (product.StockQuantity <
message.Quantity)
{
throw new InvalidOperationException(
"Insufficient stock.");
}
product.StockQuantity -=
message.Quantity;
await _db.SaveChangesAsync(
cancellationToken);
await transaction.CommitAsync(
cancellationToken);
}
catch
{
await transaction.RollbackAsync(
cancellationToken);
throw;
}
}
The important property of this design is:
Inbox record
+
Business state change
=
One transaction
If the business operation fails, the Inbox record is rolled back too.
The broker can safely redeliver the message later.
13. What If Two Consumer Instances Receive the Same Message?
Distributed systems often run multiple instances of the same consumer.
Message
↓
┌───────────────┐
│ Consumer #1 │
└───────────────┘
Message
↓
┌───────────────┐
│ Consumer #2 │
└───────────────┘
If both instances execute:
SELECT COUNT(*)
FROM InboxMessages
WHERE MessageId = ...
and both see zero rows, both may begin processing the same message.
This is why an application-level AnyAsync check is not enough.
The database UNIQUE or PRIMARY KEY constraint must be the final concurrency boundary.
14. Are Idempotency and Deduplication the Same Thing?
Not exactly.
Deduplication detects that the same message ID has already been processed.
Idempotency means that repeating the same logical operation does not incorrectly change system state again.
For example:
SET Order.Status = 'Paid'
may naturally behave more idempotently.
But:
Customer.Balance -= 1500
is not idempotent. Running it again subtracts the money again.
15. MessageId Must Remain Stable
Generating a new MessageId during a retry breaks deduplication.
Wrong:
First delivery:
MessageId = A
Retry:
MessageId = B
The consumer sees two different events.
Correct:
First delivery:
MessageId = A
Retry:
MessageId = A
Using the Outbox record ID as the broker message ID is therefore a very useful strategy.
16. Consumer Completed the Work but ACK Was Lost
Another very common messaging scenario looks like this:
Broker delivered message
↓
Consumer processed business logic
↓
Database COMMIT succeeded
↓
Consumer crashed
↓
Broker never received ACK
↓
Message was redelivered
If the consumer is not idempotent, the business action runs twice.
The Inbox Pattern is especially valuable in this scenario.
17. What If the Consumer Needs to Publish Another Event?
After Inventory Service processes the order, it may need to publish:
InventoryReserved
If the consumer directly publishes the new event, the same dual-write problem appears again.
The consumer service can therefore maintain its own Outbox:
OrderCreated
↓
Inventory Consumer
↓
SQL Transaction
│
├── Update stock
├── InboxMessages
└── OutboxMessages
↓
COMMIT
↓
InventoryReserved
This lets the reliability pattern continue across services.
18. Retry Must Not Continue Forever
If the message broker is temporarily unavailable, retrying is reasonable.
But permanent failures such as malformed payloads should not be retried forever.
Attempt 1
Attempt 2
Attempt 3
Attempt 4
...
Attempt 148,265
That is no longer resilience. It is the system enthusiastically wasting its own resources.
An exponential backoff strategy can be used:
Failure 1 → 2 seconds
Failure 2 → 4 seconds
Failure 3 → 8 seconds
Failure 4 → 16 seconds
Failure 5 → 32 seconds
After a configured number of failures, the message can:
- Be marked as Failed.
- Move to a Dead Letter Queue.
- Generate an operational alert.
19. Poison Messages
Some messages can never be processed successfully.
For example:
- The payload may be malformed.
- A required field may be missing.
- The event schema may be incompatible.
- The business data may no longer be valid.
Repeatedly returning these messages to the main queue can prevent healthy messages from being processed efficiently.
After a limited number of failed attempts, a poison message should usually be moved to a Dead Letter Queue.
20. Message Ordering
Assume an Order produces these events:
1. OrderCreated
2. PaymentCompleted
3. OrderCancelled
In a distributed architecture, you should not assume consumers always receive all messages globally in that order.
A sequence number can be added:
public sealed record OrderEvent
{
public Guid MessageId { get; init; }
public long OrderId { get; init; }
public long Sequence { get; init; }
public DateTime OccurredAt { get; init; }
}
For example:
OrderId: 15025
OrderCreated
Sequence = 1
PaymentCompleted
Sequence = 2
OrderCancelled
Sequence = 3
If the broker supports partition keys, sessions or ordering keys, events for the same aggregate can be routed consistently.
Trying to guarantee global ordering is often unnecessarily expensive. Aggregate-level ordering is usually more realistic and scalable.
21. Running Multiple Outbox Workers
If the application runs on multiple instances, each instance may have its own Outbox Worker.
Two workers may attempt to load the same message.
Consumer idempotency can protect business state from duplicate publication, but duplicate broker traffic is still wasteful.
Workers can therefore temporarily claim records.
Example SQL Server approach:
DECLARE @LockId UNIQUEIDENTIFIER = NEWID();
UPDATE TOP (50) OutboxMessages
SET
LockId = @LockId,
LockedUntil =
DATEADD(SECOND, 30, SYSUTCDATETIME())
OUTPUT inserted.*
WHERE Id IN
(
SELECT TOP (50) Id
FROM OutboxMessages WITH
(
UPDLOCK,
READPAST,
ROWLOCK
)
WHERE PublishedAt IS NULL
AND
(
LockedUntil IS NULL
OR LockedUntil < SYSUTCDATETIME()
)
AND
(
NextAttemptAt IS NULL
OR NextAttemptAt <= SYSUTCDATETIME()
)
ORDER BY OccurredAt
);
The worker should claim the records quickly and close the transaction.
The broker publish operation should not be performed while holding a long-running SQL transaction.
If the worker crashes after claiming the message,
another worker can retry it after LockedUntil expires.
22. Is Exactly-Once Really Possible?
The phrase exactly-once delivery appears frequently in messaging discussions.
However, guaranteeing one and only one end-to-end business execution across SQL Server, application processes and a separate message broker can be extremely difficult.
A more practical design is usually:
At-Least-Once Delivery
+
Stable MessageId
+
Idempotent Consumer
+
Database Constraints
=
Approximately Exactly-Once Business Effect
The message may arrive twice, but the business effect occurs only once.
23. Real Scenario: Creating an Order
Let's follow the complete process.
Step 1: The customer creates an order
POST /api/orders
Step 2: Order Service starts a transaction
BEGIN TRANSACTION
INSERT Orders
INSERT OutboxMessages
OrderCreated
COMMIT
Step 3: API response is returned
The message broker no longer needs to be available at the exact moment the API transaction completes.
Step 4: Outbox Worker publishes the event
Outbox
↓
OrderCreated
↓
Broker
Step 5: Inventory Consumer receives the event
BEGIN TRANSACTION
INSERT InboxMessages
UPDATE Products
SET Stock = Stock - Quantity
INSERT OutboxMessages
InventoryReserved
COMMIT
Step 6: InventoryReserved is published
Inventory Outbox
↓
InventoryReserved
↓
Broker
↓
Order Service
Payment Service
Each service remains responsible only for its own local database transaction.
Instead of using a distributed transaction across services, the system achieves consistency through events and eventual consistency.
24. How Eventual Consistency Appears to Users
In event-driven systems, all services do not necessarily reach the same state in the same millisecond.
Immediately after an order is created:
Order Status:
Created
A short time later:
InventoryReserved
and later:
PaymentCompleted
The UI and API design should support these transitional states.
Useful order states may include:
PendingInventoryPendingPaymentCompletedFailed
This makes the asynchronous workflow explicit instead of pretending every operation completes instantly.
25. Event Schema Versioning
Producers and consumers may not always be deployed at the same time.
Today's event may look like:
{
"orderId": 15025,
"customerId": 42
}
and later evolve into:
{
"orderId": 15025,
"customerId": 42,
"currency": "TRY"
}
Backward-compatible changes should be preferred whenever possible.
Event metadata can include a version:
EventType : OrderCreated
EventVersion : 2
When breaking changes are unavoidable, a new event version or a new event type may be a better design.
26. CorrelationId and CausationId
One incoming HTTP request may trigger dozens of events across multiple services.
In production troubleshooting, MessageId alone is often not enough.
Event metadata may include:
{
"messageId": "...",
"correlationId": "...",
"causationId": "...",
"eventType": "InventoryReserved",
"occurredAt": "..."
}
MessageId identifies the current message.
CorrelationId connects all messages belonging to the same business flow.
CausationId identifies the previous message or command that caused the current event.
HTTP Request
CorrelationId = X
↓
OrderCreated
CorrelationId = X
↓
InventoryReserved
CorrelationId = X
↓
PaymentCompleted
CorrelationId = X
27. Without Monitoring, an Outbox Can Fail Silently
The Outbox Pattern reduces message loss, but without monitoring another problem appears.
The broker may have been unavailable for two hours, while the API continues accepting new orders.
The Outbox table can grow:
10 messages
100 messages
5,000 messages
150,000 messages
Useful metrics include:
- Pending Outbox Message Count
- Oldest Pending Message Age
- Publish Failure Count
- Average Publish Latency
- Dead Letter Count
- Inbox Duplicate Count
Oldest Pending Message Age is especially useful.
A large Outbox can be normal in a high-throughput system. But if the oldest unpublished message is two hours old, something is clearly wrong.
28. The Outbox Table Must Not Grow Forever
If successfully published messages are never removed, the table can eventually grow to millions or hundreds of millions of rows.
A retention strategy should be defined.
For example:
DELETE TOP (5000)
FROM OutboxMessages
WHERE PublishedAt <
DATEADD(DAY, -7, SYSUTCDATETIME());
Cleanup can be performed in small batches to reduce locking and transaction pressure.
If audit retention is required, older messages can be archived to another table or storage system.
29. Do Not Put Everything Into an Event Payload
Event messages may be logged, stored by brokers or consumed by multiple systems.
Sensitive information should therefore be minimized.
Events should generally avoid carrying:
- Credit card numbers
- Passwords
- Access tokens
- Unnecessary personal information
An event contract should contain the minimum information required to represent the business event.
30. Common Mistakes
Mistake 1: Publish Immediately After SaveChanges
SaveChanges()
Publish()
There is still a crash window.
Mistake 2: Using Outbox Without Idempotent Consumers
Duplicate events can execute business logic multiple times.
Mistake 3: Generating a New MessageId During Retry
Consumers can no longer identify duplicate delivery.
Mistake 4: Separating Inbox Write and Business Update
A crash between them can cause duplicate business execution.
Mistake 5: Infinite Retry
Poison messages can consume resources forever.
Mistake 6: Holding a SQL Transaction While Publishing to the Broker
Long transactions increase locking and reduce concurrency.
Mistake 7: Assuming Global Ordering
Multiple partitions, workers and consumer instances can change delivery order.
31. Real Failure Scenarios That Should Be Tested
Happy-path tests are not enough for an Outbox-based system.
| Test | Expected Result |
|---|---|
| Terminate the application after Order commit | Outbox event is published after restart |
| Crash after broker publish but before PublishedAt update | Duplicate publish may occur, consumer does not repeat business effect |
| Send the same MessageId twice | Business effect occurs once |
| Two consumers receive the same duplicate concurrently | Unique constraint allows only one successful Inbox record |
| Broker unavailable for 10 minutes | Outbox accumulates and drains safely after recovery |
| Send malformed payload | Limited retries, then Dead Letter Queue |
| Outbox Worker crashes while publishing | Another worker can recover the message after lock expiration |
32. Recommended Architecture
┌──────────────────┐
│ REST API │
└────────┬─────────┘
│
▼
┌──────────────────┐
│ SQL Transaction │
│ │
│ Business Data │
│ Outbox Message │
└────────┬─────────┘
│
COMMIT
│
▼
┌──────────────────┐
│ Outbox Publisher │
└────────┬─────────┘
│
▼
┌──────────────────┐
│ Message Broker │
└────────┬─────────┘
│
▼
┌──────────────────┐
│ Consumer │
│ │
│ Inbox Check │
│ Business Update │
│ New Outbox Event │
└──────────────────┘
33. Conclusion
Reliable event-driven messaging is not simply about using a message broker such as RabbitMQ, Kafka or Azure Service Bus.
The real challenge is deciding what happens when operations across different systems fail at different moments.
The Transactional Outbox Pattern greatly reduces the risk of event loss by storing business state and the event record inside the same local database transaction.
But Outbox alone is not enough.
If an event is successfully published and the producer crashes before recording that fact, the same event may be published again.
This means the consumer side should use:
- Stable MessageId values
- Inbox or deduplication records
- Database uniqueness constraints
- The same transaction for Inbox and business updates
A practical summary looks like this:
Business Data
+
Transactional Outbox
+
At-Least-Once Delivery
+
Stable MessageId
+
Idempotent Consumer
+
Inbox Transaction
+
Retry / Dead Letter
+
Monitoring
=
Reliable Event-Driven Messaging
When designing an event-driven system, it is not enough to ask:
“How will I send the message?”
The more important questions are:
“What happens if the application crashes after the database commit?”
“What happens if the same message arrives twice?”
“What happens if the consumer commits its database transaction but crashes before acknowledging the message?”
A system with tested answers to those questions is much closer to being a genuinely reliable event-driven architecture in production.
```
0 Comments