Video in progress
When a business rule spans several aggregates or services (for example, stock in the warehouse and an order), how do you enforce the invariant?
First I question the rule itself: does it really have to be consistent instantly, or is eventual consistency with compensation enough? Usually a saga: each step is a local transaction in its own aggregate, with a compensating action on failure.
📖 Answer
"An order is accepted only if there's stock" is a requirement that spans two aggregates (Order, Stock) and often two services. The options:
1. Redraw the boundary. If the rule is truly strict and the load is small, both pieces of data may belong in one aggregate. But that's rarely right: the aggregate gets too big.
- Reservation (a saga).
Orderis created in thePENDINGstate and anOrderPlacedevent is emitted.- The warehouse service reserves the stock (
StockReserved) or rejects it (StockRejected). OrderbecomesCONFIRMEDorREJECTEDaccordingly.- If the payment fails, compensation:
ReleaseStock.
Orchestration (a central saga class drives the steps) is clearer in a complex flow; choreography (services react to events on their own) gives lower coupling in a simple flow, but becomes hard to follow at 5+ steps.
- Talk to the business. Many "strict" rules aren't really strict. Sometimes allowing a small amount of overselling and then apologizing to the customer with a coupon is cheaper than 2PC. Put this question to the business directly.
The technical requirements:
- every step is idempotent (an event can arrive again);
- events go through an outbox, otherwise the DB write happens and the message never goes out;
- the saga state is stored and there's a timeout: what happens if no reply comes;
- compensation can fail too: a "dead" state and an alert for manual intervention.
2PC/XA is usually not chosen: support is limited across brokers and modern DBs, and if the coordinator goes down, resources stay stuck in locks.
Sign up to mark studied questions and save your progress.