Distributed consistency and saga
What you will learn
A saga coordinates local transactions across services. If a later step cannot complete, a compensating operation can reverse the business effect of an earlier step. Compensation is another operation that can fail, not a global database rollback.
- Model successful, compensated and pending saga outcomes.
- Explain orchestration versus choreography and eventual consistency.
- Preserve idempotency during compensation and reconciliation.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Standalone Java 21 models; the companion Spring Cloud configuration is source-reviewed, not executed.
Coordinate two local mock services
public class Main { enum Billing { APPROVED, DECLINED, UNKNOWN } interface BillingPort { Billing authorize(); } static class Stock { int free=5; void reserve(){free-=2;} void release(){free+=2;} } static String place(Stock s,BillingPort billing) { s.reserve(); return switch(billing.authorize()) { case APPROVED -> "CONFIRMED"; case DECLINED -> { s.release(); yield "COMPENSATED"; } case UNKNOWN -> "PENDING"; }; } public static void main(String[] args) { for (Billing reply : Billing.values()) { Stock inventory=new Stock(); System.out.println(place(inventory, () -> reply)+":"+inventory.free); } }}Expected output:
CONFIRMED:3COMPENSATED:5PENDING:3Inventory and billing are local mock participants. An unknown billing result keeps the reservation pending; the next action is reconciliation, not blind compensation.
Saga and local atomicity
Each participant commits its own local transaction. A coordinator may reserve inventory, request billing authorization, and confirm the order. A definite billing rejection permits releasing the reservation. A lost billing response instead requires reconciliation by operation ID; do not release stock while an authorization may have succeeded. Compensation may mean refunding or releasing, not erasing history. A cancellation can be impossible after a shipment, requiring a different business process.
Coordination and delivery
Orchestration centralizes workflow decisions in a coordinator. Choreography uses events and local reactions, reducing direct coordination but making global progress harder to see. Persist workflow state and outbox messages atomically; an outbox relay can deliver duplicates, so consumers need idempotent effects. At-least-once delivery with a durable unique event ID and atomic consumer effect can yield one business effect in a specified scope, not universal exactly-once delivery.
Eventual consistency and recovery
A read model may lag while events are in flight; expose pending state and last known version. Use semantic locks, reservations, version checks or explicit conflict handling to protect invariants. Persist failed compensation as retryable work, bound retries, and escalate unresolved state to operators. Trace IDs correlate logs; workflow IDs identify durable saga state. The following model keeps everything in memory and deliberately cannot survive a crash.
Ignore a duplicate release
public class Main { static class Stock { int free=3; final java.util.Map<String,Integer> holds=new java.util.HashMap<>(java.util.Map.of("R1",2)); synchronized void release(String id) { Integer n=holds.remove(id); if(n!=null) free+=n; } } public static void main(String[] args) { var s=new Stock(); s.release("R1"); s.release("R1"); System.out.println(s.free); }}Expected output:
5Removing the known reservation makes repeated release harmless in this local model. Durable participants require an atomic transaction and audit history.
Reject a stale read-model snapshot
public class Main { record View(long version,int free) {} static View update(View current,View incoming) { return incoming.version()>current.version() ? incoming : current; } public static void main(String[] args) { var v=new View(2, 7); System.out.println(update(v,new View(1,9))); System.out.println(update(v,new View(3,5))); }}Expected output:
View[version=2, free=7]View[version=3, free=5]Versioned full snapshots can ignore older versions. Delta events need ordered application or gap recovery; do not apply this rule blindly to deltas.
Common mistakes
Do not equate compensation with a database rollback, release a reservation on an ambiguous result, or rely on an in-memory deduplication set for durable delivery.
Practice
Model compensation that fails once and succeeds on a later explicit retry. Print COMPENSATION_PENDING then COMPENSATED. Do not hide the first failure or retry endlessly.
Expected output:
COMPENSATION_PENDINGCOMPENSATEDCompare with the manual review criteria.
Further reading: Saga · Idempotency. Independent editorial review remains pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Distributed consistency and saga — knowledge check
Distributed systems and resilience reasoning.
What is a saga?
Billing timed out. What should happen to a held reservation?
Why must release be idempotent?
What must be durable in a real saga?
When can stale snapshots be ignored?