← Writing

Legacy modernization, part 2: Add an outbox to the order transaction

On this page

An order is saved, but the notification worker never hears about it. The reverse can happen too: the customer gets an order receipt even though saving the order failed. A failure between the database write and the send can cause either outcome when the two operations run separately.

To reduce that risk while continuing to accept orders, save the order change and the event to publish in the same database transaction. A separate worker reads and delivers committed events. This is a transactional outbox. In this fictional store, we’ll verify the path before enabling customer notifications or updating production statistics. Transactional outbox pattern from AWS

1. Find the paths that change orders

Adding an outbox only to the customer order API leaves admin cancellations, payment provider callbacks, and scheduled jobs untouched. If they update the order table directly, the order changes without an event.

First, find where the system records order acceptance, payment confirmation, and completed cancellation. Include batch jobs, database triggers, and manual recovery scripts. Route the paths in the pilot through shared order mutation logic. Address any remaining direct writes before relying on events for the affected paths.

Event names should describe what has already happened. OrderCancellationRequested and OrderCancelled, for example, describe different facts. If cancellation in this store requires refund confirmation, recording OrderCancelled when the request arrives can trigger a completion notice too soon.

2. Save the order change and event together

The pseudocode below shows the implementation sequence. Increment a per-order publication sequence for each order change that emits an event. Leave the sequence unchanged for changes such as private notes that emit no event.

Lock the order or check its version, validate the transition, and write the order and outbox together. A failure rolls both back.

Lock the order or check its version, validate the transition, and write the order and outbox together. A failure rolls both back.

beginTransaction()
    order = lockOrderOrCheckVersion(orderId)
    requireAllowedTransition(order.status, requestedStatus)
    order.status = requestedStatus
    order.publicationSequence += 1
    save(order)
    outbox.insert(eventFor(order, order.publicationSequence))
commitTransaction()

Record event_id, order_id, the per-order publication sequence, event type, schema version, and time of occurrence in the outbox. Put separate unique constraints on event_id and the pair (order ID, publication sequence). Include only the business data needed for delivery. Avoid copying entire shipping addresses or contact details from the order.

If saving the order or the outbox fails, both roll back. The worker reads only committed records. If the application stops just after the commit, the event to publish is still there. The delivery worker’s state does not determine whether the customer’s order was accepted.

3. Plan for duplicates and out-of-order delivery

The worker claims the records it will deliver and sends the messages. It marks an event published only after the broker acknowledges it. For batch sends, check the outcome of each event. After a restart, retry unfinished records with their original event_id.

If the worker stops right after the broker accepts an event, the outbox record still lacks a completion mark. Retrying can deliver that event again. The verification consumer saves the processing record for the event_id and the effect in its own database in the same transaction. It acknowledges the message after committing so it can recognize a processed event on redelivery. An external email or SMS send cannot be committed in that database transaction. The next part will cover a separate send log and reconciliation.

Consumers that require ordering check the per-order publication sequence. If the last applied number is 4 and 6 arrives first, hold 6 and check whether 5 is late or missing. This check assumes a verification consumer receiving all order events. A consumer subscribed to a subset of event types can expect gaps and needs its own ordering contract.

4. Reconcile before enabling notifications and statistics

In the first deployment, write outbox records and let only the verification consumer receive events. It records what it receives without messaging customers or updating production metrics. Compare the state transitions eligible for publication in existing order history with outbox and receipt records. Overall counts can hide a missing event for one order offset by a duplicate for another. Reconcile by order and transition.

Scenario to reproduce Expected result
Outbox write fails The order change rolls back and there is no event to deliver.
Worker stops just after order commit The order and outbox record remain. The event is delivered after the worker resumes.
Worker stops just after broker acceptance The same ID can be redelivered. The verification effect is applied once.
Sequence 6 arrives before 5 Hold 6, verify 5, and apply them in order.
A batch job changes state outside the publishing logic The missing event shows up when order history is compared against the outbox.
Broker is temporarily unavailable Unpublished records remain and the backlog shrinks after recovery.

Operations runbook

Situation Action Checks before resuming
Unpublished events are piling up The on-call engineer checks the count, age of the oldest pending record, and recent send errors. After the worker or broker recovers, retry a limited batch with the original IDs. Older events are processed first, the backlog shrinks, and database load is within the acceptable range.
Order history has a transition with no event Stop expansion. The order owner identifies the write path. Repair missing events only when records can establish the original transition. The scope and repairs can be explained, and the reproduction test passes for the affected write path.
Duplicate effects or sequence gaps appear Pause application by that consumer and record the order ID, event ID, and last applied sequence. Compare the outbox with receipt history to narrow the replay scope. Resume consumption after verifying that duplicate effects are prevented and the gaps are resolved.
The outbox change affects order writes Stop expanding the release. Roll back to the previous order path and record the time and order scope in which outbox recording stops. Pause the verification consumer as well. Order creation and cancellation have recovered. Reconcile the recording gap and determine its impact on downstream consumers.

Completion requires more than sending a single event. You should be able to account for every eligible transition in order history and confirm that resending the same event after an interruption applies its verification effect only once. With that evidence, the next part can reconcile the existing send queue and hand notification delivery over to the new worker one channel at a time.

Previous — Modernizing a legacy monolith, part 1: Move the order list first

Next — Modernizing a legacy monolith, part 3: Move order notifications without sending duplicates

Discussion

View on GitHub ↗