How are Distributed Transactions handled in Microservices? (Saga Pattern)

Why Distributed Transactions Are a Problem?

How are Distributed Transactions handled in Microservices? (Saga Pattern)
How are Distributed Transactions handled in Microservices? (Saga Pattern)

In microservices:

  • Each service has its own database

  • Traditional 2PC (XA transactions) don’t scale well

  • High latency & tight coupling

πŸ‘‰ So we use Saga Pattern.


πŸ”Ή What is Saga Pattern?

A Saga is a sequence of local transactions, where:

  • Each service performs its transaction

  • If one fails β†’ compensating actions undo previous steps


πŸ”Ή Types of Saga

1️⃣ Choreography-based Saga

  • No central controller

  • Services react to events

πŸ“Œ Example:

OrderCreated β†’ PaymentProcessed β†’ InventoryUpdated

2️⃣ Orchestration-based Saga

  • Central orchestrator controls flow

  • Services respond to commands

πŸ“Œ Example:

Order Orchestrator β†’ Payment β†’ Inventory β†’ Shipping

πŸ”Ή Example Flow (E-commerce)

  1. Order Service β†’ create order

  2. Payment Service β†’ deduct money

  3. Inventory Service β†’ reduce stock

❌ If inventory fails:

  • Payment Service β†’ refund

  • Order Service β†’ cancel order


πŸ”Ή Eventual Consistency

  • Data is not consistent immediately

  • Becomes consistent over time


πŸ”Ή Saga vs 2PC

Aspect Saga 2PC
Coupling Loose Tight
Performance High Slow
Scalability Excellent Poor
Failure Handling Compensating Blocking

πŸ”Ή Implementation Tools

  • Kafka / RabbitMQ

  • Spring State Machine

  • Temporal

  • Camunda


πŸ”Ή Real-World Use Case

πŸ’³ Payment success
πŸ“¦ Inventory failure
↩ Refund triggered automatically


⭐ Interview One-Liner

β€œSaga handles distributed transactions by breaking them into local transactions with compensating actions.”


πŸ”Ή Follow-Up Questions Interviewers Ask

  • Saga vs Eventual Consistency?

  • How do you handle duplicate events?

  • How do you ensure idempotency?

Leave a Reply