Video in progress
What anomalies does the lack of isolation in a saga cause, and how do you reduce them?
Saga steps commit separately, so other operations see intermediate states: a reservation that isn't confirmed yet, a payment that will be cancelled later. You reduce this with a semantic lock (PENDING states), rechecking, and ordering the steps correctly.
📖 Answer
In a local transaction, even at READ COMMITTED, others don't see half-finished data. In a saga, every step is a separate commit. Examples:
- Dirty read. The warehouse reserved stock and the quantity hit 0. Another customer sees "sold out". Then the payment fails and the reservation is cancelled, meaning the product actually was available.
- Lost update. Saga A compensated and restored the quantity to the old value, while in the meantime saga B had also changed the quantity, so B's change is lost.
Ways to reduce it:
Semantic lock. The record is created in the PENDING state, and other operations take that state into account. For example, cancelling or editing a PENDING order is forbidden.
Commutative updates. Change the quantity not by "setting it to a value" but by "adding a delta": qty = qty - 2, and on compensation qty = qty + 2. Then order stops mattering and there's no lost update.
-- bad: SET qty = 5 (restoring the old value)
UPDATE stock SET reserved = reserved - 2 WHERE sku = ? AND reserved >= 2;
Re-reading. Before the pivot step, recheck the important conditions: has the price changed, is the limit still sufficient.
Step order. If the steps most likely to be cancelled come first, there are fewer intermediate states that affect others.
If you know this in an interview, you show that you don't hold the wrong idea that "a saga is a distributed ACID": a saga gives (eventual) atomicity but not isolation.
Sign up to mark studied questions and save your progress.