Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 05 · Distributed Systems & ConsensusChapter 27 of 33
26.
Phase 05Read time ~23 minDifficulty advanced

Distributed Transactions

In this chapter
  • 01Chapter Overview
  • 02Why Distributed Transactions Are Difficult
  • 03Local Transaction vs Distributed Transaction
  • 04Local Transaction
  • 05Distributed Transaction
  • 06The Atomicity Problem
  • 07ACID in Distributed Systems
  • 08The Unknown Outcome Problem
  • 09Distributed Transaction Strategies
  • 10Two-Phase Commit (2PC)
  • 11Phase 1 — Prepare
  • 12Phase 2 — Commit
  • 13What If One Participant Says No?
  • 142PC State Machine
  • 15Why 2PC Is Attractive
  • 16The Major Problem with 2PC
  • 17Coordinator Failure
  • 182PC and Network Partitions
  • 19Performance Cost of 2PC
  • 20Resource Locking
  • 21Three-Phase Commit
  • 22Why Sagas Became Important
  • 23Saga Example
  • 24Rollback vs Compensation
  • 25Database rollback
  • 26Saga compensation
  • 27Saga Example in Detail
  • 28Saga Choreography
  • 29Saga Choreography Failure
  • 30Saga Orchestration
  • 31Choreography vs Orchestration
  • 32Saga State Machine
  • 33Durable Workflow State
  • 34Transactional Outbox
  • 35Outbox Solution
  • 36Outbox Publisher
  • 37Why Outbox Helps
  • 38Outbox Is Not Exactly-Once Delivery
  • 39Idempotency
  • 40Idempotent Saga Steps
  • 41Exactly-Once Is Difficult
  • 42Deduplication
  • 43Saga Failure Scenario
  • 44Compensation Is Not Always Possible
  • 45Distributed Locking
  • 46Lease-Based Locks
  • 47The Fencing Token Problem
  • 48When to Use 2PC
  • 49When to Use Saga
  • 502PC vs Saga
  • 51Example: Payment Workflow
  • 52Example Architecture
  • 53Failure Recovery
  • 54Retry Strategy
  • 55Retry + Idempotency
  • 56Timeouts and Unknown Results
  • 57Reconciliation
  • 58Long-Running Transactions
  • 59Human-in-the-Loop Workflows
  • 60Distributed Transaction Design Rules
  • 61Rule 1
  • 62Rule 2
  • 63Rule 3
  • 64Rule 4
  • 65Rule 5
  • 66Rule 6
  • 67Rule 7
  • 68Rule 8
  • 69Rule 9
  • 70Rule 10
  • 71Common Misconception #1
  • 72Wrong
  • 73Correct
  • 74Common Misconception #2
  • 75Wrong
  • 76Common Misconception #3
  • 77Wrong
  • 78Common Misconception #4
  • 79Wrong
  • 80Common Misconception #5
  • 81Wrong
  • 82Interview Question: What Is 2PC?
  • 83Answer
  • 84Interview Question: Why Is 2PC Slow?
  • 85Interview Question: What Is a Saga?
  • 86Answer
  • 87Interview Question: Choreography vs Orchestration
  • 88Choreography
  • 89Orchestration
  • 90Interview Question: Why Is Idempotency Important?
  • 91Interview Question: What Is Transactional Outbox?
  • 92Interview Question: Exactly Once?
  • 93Mini Project
  • 94Design a Distributed E-Commerce Checkout
  • 95State
  • 96Failure states
  • 97Compensation
  • 98Reliability
  • 99Advanced Challenge
  • 100Production Checklist
  • 101Final Mental Model
  • 102Summary
  • 103Next Chapter
  • 104Chapter 26 — Distributed Coordination
In this chapter (104 sections)
01Chapter Overview02Why Distributed Transactions Are Difficult03Local Transaction vs Distributed Transaction04Local Transaction05Distributed Transaction06The Atomicity Problem07ACID in Distributed Systems08The Unknown Outcome Problem09Distributed Transaction Strategies10Two-Phase Commit (2PC)11Phase 1 — Prepare12Phase 2 — Commit13What If One Participant Says No?142PC State Machine15Why 2PC Is Attractive16The Major Problem with 2PC17Coordinator Failure182PC and Network Partitions19Performance Cost of 2PC20Resource Locking21Three-Phase Commit22Why Sagas Became Important23Saga Example24Rollback vs Compensation25Database rollback26Saga compensation27Saga Example in Detail28Saga Choreography29Saga Choreography Failure30Saga Orchestration31Choreography vs Orchestration32Saga State Machine33Durable Workflow State34Transactional Outbox35Outbox Solution36Outbox Publisher37Why Outbox Helps38Outbox Is Not Exactly-Once Delivery39Idempotency40Idempotent Saga Steps41Exactly-Once Is Difficult42Deduplication43Saga Failure Scenario44Compensation Is Not Always Possible45Distributed Locking46Lease-Based Locks47The Fencing Token Problem48When to Use 2PC49When to Use Saga502PC vs Saga51Example: Payment Workflow52Example Architecture53Failure Recovery54Retry Strategy55Retry + Idempotency56Timeouts and Unknown Results57Reconciliation58Long-Running Transactions59Human-in-the-Loop Workflows60Distributed Transaction Design Rules61Rule 162Rule 263Rule 364Rule 465Rule 566Rule 667Rule 768Rule 869Rule 970Rule 1071Common Misconception #172Wrong73Correct74Common Misconception #275Wrong76Common Misconception #377Wrong78Common Misconception #479Wrong80Common Misconception #581Wrong82Interview Question: What Is 2PC?83Answer84Interview Question: Why Is 2PC Slow?85Interview Question: What Is a Saga?86Answer87Interview Question: Choreography vs Orchestration88Choreography89Orchestration90Interview Question: Why Is Idempotency Important?91Interview Question: What Is Transactional Outbox?92Interview Question: Exactly Once?93Mini Project94Design a Distributed E-Commerce Checkout95State96Failure states97Compensation98Reliability99Advanced Challenge100Production Checklist101Final Mental Model102Summary103Next Chapter104Chapter 26 — Distributed Coordination

1. Chapter Overview#

In a traditional application, a transaction is often simple:

BEGIN
  update table A
  update table B
COMMIT

A single database can provide ACID guarantees across those operations.

But modern systems often look like this:

Order Service
     │
     ├────► Order DB
     │
     ├────► Payment Service
     │
     ├────► Inventory Service
     │
     └────► Notification Service

Now one business operation spans:

  • multiple services
  • multiple databases
  • multiple machines
  • multiple network calls

This creates the problem of the distributed transaction.

The central question becomes:

How do we keep a multi-step business operation correct when the steps can fail independently?


2. Why Distributed Transactions Are Difficult#

Consider an e-commerce checkout:

1. Create order
2. Reserve inventory
3. Charge payment
4. Create shipment
5. Send confirmation

Suppose:

Order created       ✓
Inventory reserved  ✓
Payment charged     ✓
Shipment creation   ✗

What should happen?

We now need to decide:

  • Should payment be refunded?
  • Should inventory be released?
  • Should the order be cancelled?
  • Should shipment retry?
  • Who coordinates the workflow?
  • What happens if the network fails while coordinating?

This is the core difficulty.


3. Local Transaction vs Distributed Transaction#

Local Transaction#

Everything happens inside one database:

Application
    │
    ▼
Database
 ┌─────────────┐
 │ BEGIN       │
 │ UPDATE A    │
 │ UPDATE B    │
 │ COMMIT      │
 └─────────────┘

The database manages atomicity.

Distributed Transaction#

The operation spans multiple resources:

Service A ──► DB A
    │
    ├───────► Service B ──► DB B
    │
    └───────► Service C ──► DB C

Now there is no single local transaction manager that automatically controls every resource.


4. The Atomicity Problem#

Suppose:

Payment = ₹1,000
Inventory = 1 item

Workflow:

Reserve item
     ↓
Charge payment

If payment succeeds but inventory reservation fails:

Payment → SUCCESS
Inventory → FAILURE

We have an inconsistent business state.

The system needs a recovery strategy.


5. ACID in Distributed Systems#

Traditional ACID means:

  • Atomicity
  • Consistency
  • Isolation
  • Durability

Distributed systems make these guarantees harder because operations can fail independently.

For example:

Service A → SUCCESS
Network  → FAILURE
Service B → UNKNOWN

The coordinator may not know whether Service B completed the operation.

This is one of the most difficult distributed transaction scenarios.


6. The Unknown Outcome Problem#

Imagine:

Client
  │
  ▼
Payment Service
  │
  ▼
Charge ₹1,000
  │
  ▼
Payment succeeds
  │
  X
  │
Response lost

The client receives:

TIMEOUT

But what actually happened?

Possibilities:

A. Payment never happened
B. Payment succeeded
C. Payment is still processing

A blind retry could cause:

Charge 1 → SUCCESS
Charge 2 → SUCCESS

Therefore distributed systems need:

  • idempotency
  • transaction state
  • reconciliation
  • durable workflow state

7. Distributed Transaction Strategies#

There are several major approaches:

Distributed Transactions
        │
        ├── Two-Phase Commit
        │
        ├── Three-Phase Commit
        │
        ├── Saga
        │
        ├── Transactional Outbox
        │
        ├── Idempotent workflows
        │
        └── Application-specific compensation

These approaches solve different problems.


8. Two-Phase Commit (2PC)#

Two-Phase Commit is a distributed transaction protocol.

It uses:

  • a coordinator
  • participants

Example:

             Coordinator
             /    |    \
            /     |     \
           ▼      ▼      ▼
         DB A   DB B   DB C

The coordinator manages the transaction.


9. Phase 1 — Prepare#

The coordinator asks every participant:

"Can you commit?"

Example:

Coordinator
    │
    ├──► DB A: PREPARE
    │
    ├──► DB B: PREPARE
    │
    └──► DB C: PREPARE

Each participant checks whether it can safely commit.

If successful:

DB A → READY
DB B → READY
DB C → READY

The participants persist enough state to commit later.


10. Phase 2 — Commit#

If every participant says:

READY

the coordinator sends:

COMMIT

to all participants.

Coordinator
    │
    ├──► DB A: COMMIT
    ├──► DB B: COMMIT
    └──► DB C: COMMIT

The transaction completes.


11. What If One Participant Says No?#

Suppose:

DB A → READY
DB B → READY
DB C → FAIL

The coordinator cannot safely commit the whole transaction.

It sends:

ABORT

to participants.

Coordinator
    │
    ├──► DB A: ABORT
    ├──► DB B: ABORT
    └──► DB C: ABORT

The transaction is rolled back.


12. 2PC State Machine#

A simplified model:

              START
                │
                ▼
             PREPARE
                │
       ┌────────┴────────┐
       │                 │
     ALL YES           ANY NO
       │                 │
       ▼                 ▼
     COMMIT             ABORT
       │                 │
       ▼                 ▼
     DONE               DONE

This is the basic idea behind two-phase commit.


13. Why 2PC Is Attractive#

2PC can provide a strong atomicity guarantee across participating resources.

For example:

DB A
DB B
DB C

can be coordinated so that the transaction either:

all commit

or:

all abort

This is useful for certain workloads that genuinely require distributed atomicity.


14. The Major Problem with 2PC#

2PC can block.

Suppose:

Coordinator
    │
    ├── A → READY
    ├── B → READY
    └── C → READY

The coordinator has decided to commit but crashes before participants receive the final decision.

Participants may be left in a prepared state:

DB A → waiting
DB B → waiting
DB C → waiting

They cannot safely make an independent decision without violating atomicity.

This is a major weakness.


15. Coordinator Failure#

Consider:

Participants:
A
B
C
 
Coordinator:
X

If the coordinator fails at the wrong point:

A → PREPARED
B → PREPARED
C → PREPARED

Participants may need to wait for recovery or a mechanism that can recover the transaction decision.

This is one reason 2PC introduces coordination overhead and failure-handling complexity.


16. 2PC and Network Partitions#

Suppose:

Coordinator
     X
Participants

The coordinator cannot communicate with some participants.

A participant may know:

"I prepared."

but not know:

"Did the global transaction commit?"

The protocol therefore has to prioritize atomicity over simply allowing participants to independently continue.


17. Performance Cost of 2PC#

2PC can add:

  • multiple network round trips
  • durable logging
  • locks or reserved resources
  • coordinator overhead
  • blocking
  • recovery complexity

This becomes especially expensive across regions.

Example:

India
   │
   │ WAN
   ▼
Europe
   │
   │ WAN
   ▼
US

Cross-region coordination can significantly increase latency.


18. Resource Locking#

Some distributed transaction implementations hold resources while a transaction is prepared.

Conceptually:

Transaction starts
      ↓
Resources reserved
      ↓
Wait for global decision
      ↓
Commit / abort
      ↓
Release resources

If the coordinator is unavailable for a long time:

Resources remain occupied

This can reduce throughput.


19. Three-Phase Commit#

Three-Phase Commit (3PC) extends the basic idea of 2PC.

A simplified conceptual flow is:

1. CanCommit?
2. PreCommit
3. DoCommit

Compared with 2PC, 3PC introduces an additional intermediate phase intended to reduce certain blocking situations under assumptions about failures and timing.

However:

3PC does not magically make distributed transactions easy or eliminate all failure problems.

It also introduces additional communication and protocol complexity.


20. Why Sagas Became Important#

Modern microservices frequently avoid global ACID transactions.

Instead, they use a Saga.

A Saga breaks one business transaction into a sequence of local transactions.

Example:

Create Order
     ↓
Reserve Inventory
     ↓
Charge Payment
     ↓
Create Shipment

Each service commits its own local transaction.

If a later step fails, the system executes compensating actions.


21. Saga Example#

Suppose:

Step 1:
Create order ✓
 
Step 2:
Reserve inventory ✓
 
Step 3:
Charge payment ✓
 
Step 4:
Create shipment ✗

The system may compensate:

Refund payment
      ↓
Release inventory
      ↓
Cancel order

This is not a database rollback.

It is a business-level compensation.


22. Rollback vs Compensation#

This distinction is critical.

Database rollback#

Transaction
   ↓
ROLLBACK
   ↓
Database returns to previous state

Saga compensation#

Payment charged
      ↓
Refund payment

The refund is a new business operation.

It is not literally undoing the original database transaction.


23. Saga Example in Detail#

Consider:

Order Service
     ↓
Create Order
     ↓
Inventory Service
     ↓
Reserve Item
     ↓
Payment Service
     ↓
Charge Customer
     ↓
Shipping Service
     ↓
Create Shipment

Compensating actions:

Create Order
    ↓
Cancel Order
 
Reserve Item
    ↓
Release Item
 
Charge Payment
    ↓
Refund Payment
 
Create Shipment
    ↓
Cancel Shipment

Each step needs a clearly defined compensation where applicable.


24. Saga Choreography#

In choreography, services react to events.

Example:

Order Service
    │
    ▼
OrderCreated
    │
    ▼
Inventory Service
    │
    ▼
InventoryReserved
    │
    ▼
Payment Service
    │
    ▼
PaymentCompleted

There is no central orchestrator.

Each service knows how to react to events.


25. Saga Choreography Failure#

Choreography can become difficult when there are many services.

Example:

Order
 ↓
Inventory
 ↓
Payment
 ↓
Shipping
 ↓
Notification
 ↓
Analytics

With many event relationships, it can become difficult to understand:

  • who triggers what
  • where compensation happens
  • which service owns a decision
  • how the overall workflow completes

This can create a "distributed spaghetti" problem.


26. Saga Orchestration#

In orchestration, a central workflow component coordinates the Saga.

              Saga Orchestrator
              /       |       \
             /        |        \
            ▼         ▼         ▼
         Order    Inventory   Payment

The orchestrator says:

1. Create order
2. Reserve inventory
3. Charge payment
4. Create shipment

If payment fails:

Orchestrator
     ↓
Release inventory
     ↓
Cancel order

27. Choreography vs Orchestration#

Aspect Choreography Orchestration
Central coordinator No Yes
Communication Events Commands/workflow
Coupling Distributed Central workflow
Visibility Can become difficult Usually easier
Large workflows Can become complex Often easier to manage
Failure handling Distributed Centralized workflow logic
Risk Event spaghetti Orchestrator complexity

Neither is universally better.

The workflow shape and organizational requirements matter.


28. Saga State Machine#

A Saga can be modeled explicitly:

START
  │
  ▼
ORDER_CREATED
  │
  ▼
INVENTORY_RESERVED
  │
  ▼
PAYMENT_COMPLETED
  │
  ▼
SHIPMENT_CREATED
  │
  ▼
COMPLETED

Failure:

PAYMENT_FAILED
      │
      ▼
RELEASE_INVENTORY
      │
      ▼
CANCEL_ORDER
      │
      ▼
FAILED

Explicit state makes recovery easier.


29. Durable Workflow State#

Do not keep critical Saga state only in memory.

Bad:

Orchestrator RAM
     ↓
workflow state

If the orchestrator crashes:

state lost

Better:

Orchestrator
     │
     ▼
Durable Workflow DB

Example state:

order_id = 123
state = PAYMENT_COMPLETED
inventory = RESERVED
payment = SUCCESS
shipment = PENDING

The workflow can resume after a crash.


30. Transactional Outbox#

Another important pattern is the Transactional Outbox.

Problem:

Service
  │
  ├── write database
  │
  └── publish event

What if:

DB write → SUCCESS
Event publish → FAILURE

Now the database contains the new state but other services never receive the event.


31. Outbox Solution#

Store the business change and outgoing event in the same local database transaction.

BEGIN
 
UPDATE orders
 
INSERT INTO outbox_events
 
COMMIT

Now both are committed atomically.

Example:

Orders table
----------------
order_id | status
123      | CREATED
 
Outbox table
-----------------------------
id | event
1  | OrderCreated

32. Outbox Publisher#

A separate publisher reads the outbox:

Database
   │
   ▼
Outbox Table
   │
   ▼
Publisher
   │
   ▼
Message Broker
   │
   ▼
Consumers

If publishing fails:

Retry

The event remains durable.


33. Why Outbox Helps#

Without Outbox:

DB update ✓
Event publish ✗

With Outbox:

DB update ✓
Outbox insert ✓
        ↓
Publisher retries
        ↓
Event eventually published

This provides reliable handoff between local database state and asynchronous messaging.


34. Outbox Is Not Exactly-Once Delivery#

A publisher might do:

Publish event
     ↓
Broker accepts
     ↓
Publisher crashes

The publisher may not know whether the broker accepted the message.

It may retry:

Event → delivered twice

Therefore consumers should be idempotent.

This leads to an important principle:

At-least-once delivery + idempotent processing is often more practical than trying to build perfect exactly-once behavior across the entire system.


35. Idempotency#

An operation is idempotent when repeating it produces the same intended final effect.

Example:

PUT /orders/123/status
status = CONFIRMED

Repeated execution can still result in:

CONFIRMED

For payment APIs, use an idempotency key:

idempotency_key = abc123

First request:

abc123 → process

Retry:

abc123 → return existing result

36. Idempotent Saga Steps#

Every Saga step should ideally be safe to retry.

Example:

ReserveInventory(order_id=123)

If called twice:

First → reservation created
Second → existing reservation returned

Not:

Reserve 1 item
Reserve another item

unless that is explicitly intended.


37. Exactly-Once Is Difficult#

A common interview statement is:

"We need exactly-once processing."

Be careful.

Across distributed systems, exactly-once end-to-end behavior is difficult because:

  • requests can be duplicated
  • responses can be lost
  • processes can crash
  • messages can be retried
  • acknowledgements can be lost

A practical design often uses:

At-least-once delivery
        +
Idempotent consumers
        +
Deduplication
        +
Durable state

to achieve an effectively-once business outcome.


38. Deduplication#

Consumers can maintain processed IDs:

processed_events
 
event_id
---------
abc
def
ghi

When event abc arrives again:

if abc already processed:
    skip business operation
else:
    process
    record abc

The deduplication record itself must be stored safely.


39. Saga Failure Scenario#

Suppose:

Order created ✓
Inventory reserved ✓
Payment charged ✓
Shipping failed ✗

Compensation:

Refund payment
     ↓
Release inventory
     ↓
Cancel order

Now suppose refund itself fails:

Refund ✗

The system must retry the compensation.

This demonstrates:

Compensation is itself a distributed operation that can fail.

Therefore Saga design requires durable state, retries, idempotency, and monitoring.


40. Compensation Is Not Always Possible#

Some actions cannot be perfectly undone.

For example:

Email sent

You cannot truly "unsend" an email in the general case.

Instead:

Email sent
     ↓
Send correction email

Similarly:

Physical shipment dispatched

may require:

Return process

rather than a database rollback.

This is why business workflows must be designed around real-world reversibility.


41. Distributed Locking#

Sometimes a system needs exclusive access to a resource.

Example:

Only one worker should process:
order_id = 123

A distributed lock may be used:

Worker A
   │
   ▼
Lock(order:123)
   │
   ▼
Process

But distributed locks have their own failure problems.


42. Lease-Based Locks#

A lease is a lock with an expiration time.

Example:

Lock acquired
TTL = 30 seconds

If the worker crashes:

30 seconds
     ↓
lease expires
     ↓
another worker can proceed

This prevents a permanently held lock.


43. The Fencing Token Problem#

Suppose:

Worker A gets lock
token = 10

A pauses due to a long garbage collection or network issue.

The lease expires.

Worker B gets:

token = 11

Worker A wakes up and continues.

Now both workers appear active.

A fencing token allows downstream storage to reject stale workers:

Worker A → token 10 → reject
Worker B → token 11 → accept

This is an important advanced distributed-systems pattern.


44. When to Use 2PC#

2PC can make sense when:

  • participants support the protocol
  • true atomic commit is required
  • transaction scope is controlled
  • performance is acceptable
  • operational complexity is understood

Examples may include certain tightly controlled transactional systems.

But it is usually not the first choice for loosely coupled internet-scale microservices.


45. When to Use Saga#

Saga is often appropriate when:

  • business workflow spans services
  • local transactions are preferred
  • temporary intermediate states are acceptable
  • compensating actions are possible
  • asynchronous processing is acceptable
  • high availability matters

Example:

Order
 ↓
Inventory
 ↓
Payment
 ↓
Shipping

46. 2PC vs Saga#

Property 2PC Saga
Atomic global commit Yes, by protocol No global rollback
Transactions Distributed transaction Local transactions
Compensation Usually not primary mechanism Core mechanism
Blocking Possible Workflow-based
Availability Can suffer Often better
Latency Coordination-heavy Can be asynchronous
Failure handling Protocol-driven Business-driven
Microservices fit Limited Common
Complexity Infrastructure/protocol Workflow/business logic

The choice depends on requirements.


47. Example: Payment Workflow#

Consider:

Checkout
   │
   ▼
Order Service
   │
   ▼
Payment Service
   │
   ▼
Inventory Service
   │
   ▼
Shipping Service

A robust workflow might use:

Local DB transactions
        +
Outbox
        +
Message broker
        +
Saga orchestration
        +
Idempotency
        +
Compensation

This avoids trying to turn every service into one giant distributed database transaction.


48. Example Architecture#

                  API
                   │
                   ▼
             Order Service
              │        │
              │        └────► Order DB
              │
              └────► Outbox
                       │
                       ▼
                   Message Bus
                  /     |      \
                 /      |       \
                ▼       ▼        ▼
         Inventory   Payment   Shipping
            │           │          │
           DB          DB         DB

Each service owns its database.

Events coordinate the workflow.


49. Failure Recovery#

Suppose:

Payment succeeded

but:

Order service crashed

After restart:

Read durable workflow state
        ↓
Detect payment success
        ↓
Continue workflow

This is why workflow state must be durable.


50. Retry Strategy#

Retries should use:

Exponential backoff
+
Jitter
+
Maximum attempts
+
Dead-letter handling

Example:

1 sec
2 sec
4 sec
8 sec
16 sec

with random jitter.

Do not retry forever without limits.


51. Retry + Idempotency#

Bad:

Payment request
   ↓
timeout
   ↓
retry
   ↓
charge again

Better:

Payment request
idempotency_key = payment_123
 
timeout
   ↓
retry with same key
   ↓
existing result

This is one of the most important production patterns for distributed workflows.


52. Timeouts and Unknown Results#

Suppose:

Service A → Service B

A waits:

10 seconds

then gets:

timeout

A must not automatically assume:

B definitely failed

The operation may have succeeded but the response may have been lost.

Therefore use:

  • idempotency
  • status APIs
  • durable transaction records
  • reconciliation
  • asynchronous completion events

53. Reconciliation#

A reconciliation process periodically checks for inconsistent workflow states.

Example:

Order:
PAID
 
Payment:
SUCCESS
 
Inventory:
RESERVED
 
Shipping:
MISSING

Reconciliation identifies:

Shipping should be created

and retries the missing step.

This is extremely useful for long-running business workflows.


54. Long-Running Transactions#

Some workflows may last:

seconds
minutes
hours
days

Examples:

  • loan processing
  • insurance claims
  • order fulfillment
  • travel booking
  • human approval workflows

A database transaction cannot remain open for hours.

Instead use:

Durable workflow state
+
events
+
timeouts
+
compensation
+
retries

55. Human-in-the-Loop Workflows#

Consider:

Order
 ↓
Fraud review
 ↓
Human approval
 ↓
Payment
 ↓
Shipping

This can take hours.

A Saga-style workflow can persist:

state = WAITING_FOR_REVIEW

When the reviewer approves:

state = APPROVED

The workflow continues.


56. Distributed Transaction Design Rules#

Rule 1#

Keep local transactions short.

Rule 2#

Avoid distributed transactions unless truly necessary.

Rule 3#

Make every retryable operation idempotent.

Rule 4#

Persist workflow state.

Rule 5#

Use durable events.

Rule 6#

Design compensating actions explicitly.

Rule 7#

Assume responses can be lost.

Rule 8#

Assume messages can be duplicated.

Rule 9#

Monitor stuck workflows.

Rule 10#

Build reconciliation for long-running systems.


57. Common Misconception #1#

Wrong#

Saga is just a distributed rollback.

Correct#

A Saga is a sequence of local transactions coordinated into a business workflow.

Compensation is a new business action, not a magical rollback.


58. Common Misconception #2#

Wrong#

Outbox guarantees exactly-once delivery.

No.

Outbox provides reliable persistence of the event alongside the local transaction.

Publishing may still result in duplicate delivery.

Consumers should be idempotent.


59. Common Misconception #3#

Wrong#

Retry means the previous request failed.

Not necessarily.

A timeout means the caller does not know the outcome.

The operation may have succeeded.


60. Common Misconception #4#

Wrong#

2PC completely eliminates failures.

No.

2PC coordinates atomic commit but introduces blocking, coordination, latency, and recovery complexity.


61. Common Misconception #5#

Wrong#

Compensation always restores the exact previous state.

Not necessarily.

Some actions cannot be perfectly reversed.

Compensation should be defined at the business level.


62. Interview Question: What Is 2PC?#

Answer#

Two-Phase Commit is a distributed transaction protocol involving a coordinator and participants. In the prepare phase, participants indicate whether they can commit. If all participants are prepared, the coordinator sends commit; otherwise it sends abort. The protocol can provide atomic commit but can introduce blocking and coordination overhead.


63. Interview Question: Why Is 2PC Slow?#

Possible reasons include:

  • multiple network round trips
  • durable prepare/commit logging
  • coordination
  • resource retention
  • cross-region latency
  • failure recovery

64. Interview Question: What Is a Saga?#

Answer#

A Saga breaks a distributed business transaction into a sequence of local transactions. If a later step fails, compensating actions are executed for earlier completed steps.


65. Interview Question: Choreography vs Orchestration#

Choreography#

Services react to events independently.

Orchestration#

A central workflow component directs the steps.

Use the model that keeps workflow ownership, failure handling, and operational visibility understandable.


66. Interview Question: Why Is Idempotency Important?#

Because distributed systems can retry operations after timeouts or duplicate messages.

Without idempotency:

Retry
 ↓
Duplicate side effect

With idempotency:

Retry
 ↓
Same logical result

67. Interview Question: What Is Transactional Outbox?#

Transactional Outbox stores the business state change and the outgoing event in the same local database transaction.

A separate publisher later sends the event to the broker.

This prevents the classic:

DB commit succeeded
event publish failed

inconsistency window.


68. Interview Question: Exactly Once?#

A strong answer:

End-to-end exactly-once behavior is difficult in distributed systems because requests, messages, acknowledgements, and processes can fail independently. A practical design often uses at-least-once delivery, idempotent processing, deduplication, durable state, and reconciliation to achieve an effectively-once business outcome.


69. Mini Project#

Design a Distributed E-Commerce Checkout#

Requirements:

  • Create order
  • Reserve inventory
  • Process payment
  • Create shipment
  • Send confirmation
  • Support retries
  • Survive service crashes
  • Prevent duplicate payment
  • Recover from partial failures

Design:

                    Checkout API
                         │
                         ▼
                  Order Service
                    │       │
                    │       └── Order DB
                    │
                    ▼
                 Outbox
                    │
                    ▼
               Message Bus
              /      |      \
             ▼       ▼       ▼
       Inventory   Payment  Shipping
          │           │        │
          DB          DB       DB

Define:

State#

ORDER_CREATED
INVENTORY_RESERVED
PAYMENT_COMPLETED
SHIPMENT_CREATED
COMPLETED

Failure states#

INVENTORY_FAILED
PAYMENT_FAILED
SHIPPING_FAILED
COMPENSATING
CANCELLED

Compensation#

Payment → Refund
Inventory → Release
Order → Cancel

Reliability#

Outbox
Idempotency
Retries
DLQ
Reconciliation
Durable workflow state

70. Advanced Challenge#

Suppose this happens:

Order created ✓
Inventory reserved ✓
Payment request sent ✓
Payment timed out ?

You do not know whether payment succeeded.

Design the system so that a retry does not double-charge the customer.

A strong solution should include:

Payment ID / Idempotency Key
        ↓
Payment Service
        ↓
Durable payment record
        ↓
Status lookup
        ↓
Retry safely

This is a classic distributed-systems interview problem.


71. Production Checklist#

Before deploying a distributed workflow, verify:

  • Every business step has durable state.
  • Every retryable operation has an idempotency strategy.
  • Duplicate events are handled.
  • Timeouts do not automatically imply failure.
  • Compensation is explicitly defined.
  • Compensation itself is retryable.
  • Outbox is used where appropriate.
  • Consumers are idempotent.
  • Dead-letter handling exists.
  • Stuck workflows can be detected.
  • Reconciliation exists.
  • Workflow state survives process crashes.
  • Metrics expose workflow failures.
  • Alerts exist for abnormal workflow duration.
  • Cross-region failure scenarios are tested.

72. Final Mental Model#

Think about distributed transactions like this:

                Business Transaction
                       │
          ┌────────────┴────────────┐
          │                         │
   Global ACID approach       Local transactions
          │                         │
         2PC                      Saga
          │                         │
   Coordination-heavy        Compensation-based

Around either approach, production systems usually need:

Idempotency
+
Retries
+
Durable state
+
Outbox/events
+
Timeouts
+
Reconciliation
+
Observability

The key lesson:

Distributed transaction design is not only about committing data. It is about defining correct behavior when any step, machine, message, or network call can fail independently.


73. Summary#

You learned:

  • What distributed transactions are
  • Why distributed transactions are difficult
  • Local vs distributed transactions
  • Atomicity across services
  • Unknown outcomes
  • Two-Phase Commit
  • Prepare phase
  • Commit phase
  • Abort phase
  • 2PC blocking
  • Coordinator failure
  • Network partitions
  • Performance costs
  • Three-Phase Commit
  • Sagas
  • Compensation
  • Saga choreography
  • Saga orchestration
  • Durable workflow state
  • Transactional Outbox
  • At-least-once delivery
  • Idempotency
  • Deduplication
  • Exactly-once misconceptions
  • Distributed locks
  • Leases
  • Fencing tokens
  • Reconciliation
  • Long-running workflows
  • Human-in-the-loop workflows
  • 2PC vs Saga
  • Real-world payment/order architecture
  • Distributed transaction interview questions

74. Next Chapter#

Chapter 26 — Distributed Coordination#

Next we will go deeper into how distributed systems coordinate multiple nodes.

We will cover:

  • Why coordination is difficult
  • Leader election
  • Distributed locks
  • Leases
  • Heartbeats
  • Failure detection
  • Split brain
  • Fencing tokens
  • Consensus intuition
  • Raft
  • Paxos concepts
  • Quorum-based coordination
  • ZooKeeper-style coordination
  • Coordination services
  • Membership
  • Service discovery
  • Distributed configuration
  • Clock problems
  • Logical clocks
  • Production failure scenarios
  • Interview questions
  • Coordination design exercise

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 24 — Consistency ModelsNext ChapterChapter 26 — Distributed Coordination
PrevNext