
Exactly-once processing in distributed systems
One of the reasons we use message brokers in distributed systems is that services don't have to be available at the same time to communicate with each other. A service can send a message while its recipient is offline, and the broker can keep it in a queue until a consumer is available. If a consumer loses its connection while processing a message, the broker can deliver that message again.
This works well for recovering from temporary failures, but it puts some responsibility on the application receiving the message. A consumer may have already committed its work to a database by the time it loses its connection to the broker.
Consider an online shop where order processing and inventory management are handled by separate services. When a customer places an order for a lamp, the order service sends a ReserveStock command to the inventory service. Inventory receives the command, creates a reservation in its database, reduces the available stock by one, and acknowledges the message.
If the connection drops just after the database transaction commits, RabbitMQ never receives the acknowledgement. It eventually delivers ReserveStock again. Unless the inventory service recognizes that it has already processed the reservation, we'll end up reserving two lamps for a customer who ordered one.
We want to keep the ability to redeliver messages and recover from failures without reserving the same stock twice.
The problem with acknowledgements#
In 2015, Tyler Treat published an essay titled You Cannot Have Exactly-Once Delivery. It describes a problem that comes up whenever two systems communicate over an unreliable network: if a sender doesn't receive an acknowledgement, it cannot tell whether the message was lost or whether the receiver processed it and the acknowledgement was lost.
The sender can retry, at the risk of repeating an operation that already succeeded, or give up, at the risk of leaving the operation incomplete.
In our inventory service, we have some control over which of these failures we need to deal with. We can acknowledge the message before or after committing the database transaction.
If we acknowledge it first and the inventory service crashes before committing the reservation, RabbitMQ considers the delivery complete. The reservation is lost. This is the trade-off we accept with an at-most-once consumption strategy.
If we commit the reservation first, a crash before the acknowledgement leaves us with a successful database operation that RabbitMQ may ask us to perform again.
- stock (durable)
- 10
- reservations
- 0
- queue
- msg-101 ready
- worker
- running
RabbitMQ distinguishes between publisher confirms and consumer acknowledgements. Publisher confirms cover communication between the publisher and RabbitMQ, whereas consumer acknowledgements cover communication between RabbitMQ and the consumer.
Both sides can encounter the same uncertainty. A publisher that loses a confirm may publish a message that RabbitMQ has already accepted. When a consumer's channel closes, RabbitMQ requeues deliveries that haven't been acknowledged.
Publisher confirms also have a limitation that's worth knowing about: RabbitMQ can confirm a message even if it couldn't route that message to a queue. When publishing commands that must reach a destination, enable mandatory publishing and handle returned messages alongside publisher confirms.
The RabbitMQ Reliability Guide and the documentation on consumer acknowledgements and publisher confirms explain these mechanisms in more detail.
Where exactly-once processing is possible#
If you've worked with Kafka, you've probably come across its exactly-once processing guarantees.
Kafka can commit a consumer's input offsets and the records produced during processing in a single transaction. For an application that reads from one topic, transforms the records, and writes to another topic, Kafka owns both sides of that transaction.
If processing fails and the transaction aborts, the input offsets aren't advanced. Consumers configured with read_committed won't see the aborted output, and processing can be retried.
The guarantee becomes more complicated once we introduce another system. If our Kafka consumer also updates inventory in PostgreSQL or charges a customer through a payment API, neither of those operations is automatically covered by the Kafka transaction.
Kafka's documentation on message delivery semantics discusses this distinction.
For our inventory service, we can express the guarantee in terms of the reservation itself. Receiving the same reservation request several times should result in at most one committed reservation.
This is commonly referred to as effectively-once processing. The handler may execute more than once, and several attempts may fail before a transaction eventually commits. A message that expires or ends up in a dead-letter queue might never produce a reservation at all.
Whether we eventually complete the reservation depends on our retry policy, the availability of the services involved, and whether the operation can succeed in the first place.
Getting the reservation command to inventory#
Before we deal with duplicate deliveries in the inventory service, there's a failure we need to account for in the order service.
When a customer checks out, the order service has two things to do. It needs to create the order in its database and send the ReserveStock command.
Saving the order and then publishing the command leaves a window in which the order service can crash. The order has been committed, but inventory hasn't received anything. Publishing first is equally problematic because inventory could reserve stock for an order that subsequently fails to commit.
Since the order is stored in PostgreSQL, we can use the same database transaction to store the outgoing command. A separate worker reads those stored messages and publishes them to RabbitMQ after the transaction has committed.
This is the transactional outbox pattern.
Mocha comes with a PostgreSQL implementation of the outbox. Inside a message consumer, UseTransaction() manages the database transaction, and UsePostgresOutbox() stores eligible outgoing messages.
Checkout itself will probably be initiated through a web endpoint rather than a message consumer. In that case, we need to open the transaction explicitly and use the same scoped DbContext that Mocha uses for the outbox. Otherwise, saving the order and storing the outgoing command could still result in separate commits. The docs cover the transaction requirements in detail.
Once the order and outbox entry have committed, the outbox worker can dispatch the command. Mocha deletes the outbox row after dispatch returns successfully.
There is another failure window here. RabbitMQ might accept the command, and the outbox worker might stop before committing the deletion of the outbox row. When the worker starts again, it finds the row and dispatches the command again, using the same message ID.
We can now recover from a crash in the order service without forgetting to publish the reservation command. Duplicate publication remains possible. The reliability of the handoff to RabbitMQ also depends on the transport's confirmation behavior and the broker's routing and persistence settings.
The docs describe how the outbox processor works.
Handling repeated deliveries in the inventory service#
The inventory service needs somewhere to record the messages it has processed.
Gregor Hohpe and Bobby Woolf describe this approach in their 2003 book Enterprise Integration Patterns as one implementation of the Idempotent Receiver.
We can keep a table of processed message IDs and check it before invoking a handler. This table is commonly called an inbox.
The difficulty is keeping the inbox and the business operation consistent. If we record a message as processed before committing the reservation, a failure could leave an inbox entry for work that never happened. If we record it afterward, a failure between the two writes could allow another reservation.
Since inventory already uses PostgreSQL, we can put both writes in the same transaction.
Mocha has a transactional inbox for this. Assuming InventoryDbContext is configured, the messaging tables have been migrated, and the RabbitMQ connection and routes are in place, the inventory service can register its message bus as follows:
builder.Services
.AddMessageBus()
.AddRequestHandler<ReserveStockHandler>()
.AddEntityFramework<InventoryDbContext>(p =>
{
p.UsePostgresOutbox();
p.UseTransaction();
p.UsePostgresInbox();
})
.AddRabbitMQ();Here, ReserveStockHandler implements IEventRequestHandler<ReserveStock>.
The registration order of the transaction and inbox middleware is important. We want the transaction to be open when the inbox attempts to claim the message.
For each message it receives, Mocha inserts an inbox claim for the combination of MessageId and ConsumerType. PostgreSQL enforces uniqueness on that pair, so concurrent deliveries cannot both successfully claim it.
Once the claim succeeds, the handler can create the reservation and update the available stock.
Inventory also needs to inform the order service that the reservation succeeded. It does this by publishing a StockReserved event. Unlike the original ReserveStock command, which is directed at inventory, the event describes something that has happened and can be consumed by other interested services.
With the outbox enabled, the inbox claim, reservation, stock update, and outgoing event all participate in the same PostgreSQL transaction, provided they use the same scoped context.
If the inventory worker crashes before committing, PostgreSQL rolls back the transaction, including the inbox claim. Another delivery can then attempt the reservation.
If the worker crashes after committing but before acknowledging the message, the reservation and inbox entry survive. When RabbitMQ redelivers the command, Mocha finds the existing claim and skips the handler.
- inventory stock
- 10
- reservations
- 0
- msg-101 in queue
- 0
- handler skipped
- 0
The inbox has a few limits to keep in mind.
The claim is scoped to the consumer type, so different consumers can process the same message independently. Messages without an ID bypass deduplication, and inbox entries are removed after the configured retention period. If the claim itself fails, for example because of a transient database error, Mocha runs the handler anyway rather than drop the message.
The docs explain how to configure the inbox, and the inbox middleware shows how claims are made.
When the same reservation arrives in a different message#
So far, the duplicate commands in our workflow have shared a message ID. This is usually what happens when RabbitMQ redelivers a message or when the outbox dispatches a stored message again.
Suppose checkout submits another command for the same order line. Perhaps an earlier attempt timed out, or an operator is trying to recover an order that appears to be stuck.
The new command has a different message ID, even though it asks inventory to perform the same reservation.
The inbox sees two unrelated messages.
We need an identifier that belongs to the reservation and survives the creation of new messages. Let's call it ReservationId. The order service generates this ID when initiating the reservation and reuses it whenever that reservation is resubmitted.
Consider these three deliveries:
| Message ID | Reservation ID | Inventory action |
|---|---|---|
msg-101 | reservation-42 | Create the reservation |
msg-101 | reservation-42 | Duplicate delivery |
msg-208 | reservation-42 | Duplicate reservation request |
The inbox can recognize the second delivery. The third requires inventory to understand the identity of the business operation.
We can enforce this directly in PostgreSQL by adding a unique constraint to the reservation ID. When handling the command, attempt to insert a reservation:
INSERT INTO reservations (
reservation_id,
order_line_id,
quantity
)
VALUES (
@reservation_id,
@order_line_id,
@quantity
)
ON CONFLICT (reservation_id) DO NOTHING
RETURNING reservation_id;If the statement returns a row, we've created a new reservation. The handler can decrement the available stock and record the StockReserved event in the outbox.
If it returns nothing, a reservation with that ID already exists. Read the existing record and compare it with the incoming command. If the order line and quantity match, the handler can reuse the recorded outcome. If they differ, we have a conflicting request that should be rejected.
The reservation insert, stock update, and outgoing event must still commit together.
This approach also handles concurrent requests with different message IDs. PostgreSQL's unique constraint prevents both requests from creating the same reservation.
At this point, we could choose to implement the handler without an inbox. If every relevant effect is conditional on successfully inserting the reservation, executing the handler again won't create another reservation, change the stock again, or record another event.
An inbox is still useful when we want to avoid executing the handler unnecessarily, but the business constraint protects the reservation beyond the lifetime of an inbox entry.
Choosing the right business key is important here. An order ID alone would be insufficient if each line of an order has its own reservation. A correlation ID might connect every message belonging to an order, but each individual operation needs an identity appropriate to its purpose.
See the Idempotent Consumer pattern and the PostgreSQL INSERT documentation.
Taking the order through payment#
With inventory reserved, the order service can move on to payment.
If the customer can be charged successfully, the order proceeds. If payment fails, we need to release the reserved stock. These steps happen across multiple services and messages, so the order service needs to remember which steps have completed and what it is waiting for.
This is a good use case for a saga.
Mocha's saga state machines allow us to persist the state of an order workflow between messages. With PostgreSQL persistence, the saga can commit a state transition and an outgoing command together, provided the saga store and outbox share the same scoped DbContext.
For example, when the saga receives StockReserved, it can move the order into an awaiting-payment state and record an outgoing payment command in the same transaction.
The billing service, however, has to communicate with an external payment provider. The provider cannot participate in our PostgreSQL transaction.
Consider what happens when the billing service sends a payment request and times out waiting for the response.
There are two possible outcomes. The request may have failed before the provider created a charge, or the provider may have charged the customer without the response reaching our billing service.
If we immediately tell the saga that payment failed and release the inventory, we could leave a customer with a successful charge and an order for which we no longer have stock reserved.
The order should remain in an awaiting-payment state until billing can determine the outcome.
Payment providers often offer their own idempotency mechanisms. Stripe's API v1, for example, supports idempotency keys on POST requests.
Before making the first request, the billing service should persist an identifier for the payment operation. If the service crashes or the request times out, it can retrieve the same identifier and retry with the same idempotency key and request parameters.
This works while Stripe retains the key. If enough time has passed that Stripe may have removed it, the billing service needs to reconcile the payment with the provider before attempting another charge.
- order saga
- AwaitingPayment
- inventory
- reserved
- charges at provider
- 0
- billing knows
- nothing yet
Not every payment provider offers idempotency keys or a reliable way to retrieve the outcome of an uncertain request. When neither is available, an unresolved payment may need manual review.
If payment is confirmed to have failed, the saga can send a command to release the reservation. The release needs its own operation identity and must be safe to repeat independently of the original reservation.
We also need to enforce valid state transitions. Making reservation and release operations idempotent doesn't prevent an older message from arriving after a newer one.
The docs cover sagas and their persistence in PostgreSQL. Stripe documents its keys in idempotent requests.
Testing the failures we expect to recover from#
A useful first integration test doesn't require stopping any services.
Seed the inventory database with ten lamps, execute a reservation for one lamp, and deliver the same message again. There should be one reservation in the database and nine lamps available. The repeated delivery should not record another StockReserved event.
Run the same test with a different message ID and the original ReservationId. This exercises the business-level protection independently of the inbox.
When asserting outgoing messages, distinguish between recording a new event in the outbox and dispatching an existing one again. The latter is an expected part of outbox recovery.
Once these tests pass, introduce failures at the transaction boundaries.
| Failure or test scenario | Expected outcome |
|---|---|
| Order service stops after committing the order | The pending reservation command survives and can be dispatched after recovery. |
| Outbox worker stops after RabbitMQ accepts the command | Repeated publication does not create another reservation. |
| Inventory worker stops before committing | The inbox claim and business changes roll back. A later delivery can complete the reservation. |
| Inventory worker stops after committing but before acknowledging | Redelivery does not decrement stock again. |
| Concurrent requests use different message IDs but the same reservation ID | Only one reservation is committed. |
| A reservation ID is reused with a different quantity | The conflicting request is rejected. |
| The payment provider creates a charge but the response is lost | Billing recovers the existing payment outcome without creating a second charge. |
I'd also test what happens when an operator replays a reservation after its original inbox entry has been removed. If replays are part of how we recover failed workflows in production, we need to support them beyond the broker's normal redelivery window.
Set the inbox retention accordingly, and account separately for how long business operation IDs are retained and how long external providers retain their idempotency keys.
In production, pay particular attention to the age of pending outbox entries, repeated dispatch failures, inbox claim failures, and messages accumulating in dead-letter queues. These are useful signals when an order has stopped progressing through the workflow.
To set up the outbox and inbox with PostgreSQL, see the transactional outbox in the docs.
