Mastering the Transactional Outbox Pattern
Solving the "Dual Write" problem to ensure 100% message delivery.
"In a distributed system, you cannot assume the network is reliable. The Outbox Pattern is your insurance policy against partial failures and inconsistent states."
1 The Problem: The Myth of Total Reliability
When building .NET APIs, we often update a database and immediately publish an event to a Message Broker (like RabbitMQ or Azure Service Bus). This is known as the Dual Write Problem.
1. Your DB update succeeds. ✅
2. The Message Broker is down or the network blips. ❌
3. Your event is lost forever. Your system is now in an inconsistent state (The "Ghost Change").
2 The Solution: Atomic Transactions
The Outbox pattern solves this by using a single local transaction. Instead of sending the message to the broker immediately, you save it in a special Outbox Table within the same database as your business entity.
- Atomicity: Both the "Business Entity" and the "Outbox Message" are saved together. If one fails, the whole transaction rolls back.
- Background Publishing: A separate background worker (using BackgroundService or Quartz.NET) polls the table and pushes messages to the broker.
3 Handling Failure Points
Modern systems face multiple points of failure. The Outbox pattern provides resilience against:
- Process Crashes: Resource limits or programming errors won't lose data stored in the DB.
- Network Blips: DNS issues or ISP failures only delay the message; they don't delete it.
- Infrastructure Maintenance: During OS updates or hardware failures, the Outbox table keeps your messages safe until the node is back online.
4 Guaranteed Delivery: "At Least Once"
The Outbox pattern guarantees that a message will be sent at least once. Because the background worker only deletes or marks a message as "sent" after receiving a confirmation from the broker, no message is ever lost.
Since we guarantee "At Least Once" delivery, the consumer of your message must be Idempotent. It should be able to process the same message twice without causing side effects.
Comentarios
Publicar un comentario