0
0
Microservicessystem_design~3 mins

Why Saga pattern for distributed transactions in Microservices? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your system could fix itself automatically when things go wrong across many services?

The Scenario

Imagine you run a small online store where orders need to update inventory, charge payments, and arrange shipping. You try to do all these steps manually, one after another, across different systems.

What if the payment succeeds but the inventory update fails? You have to fix it by hand, which is slow and confusing.

The Problem

Doing these steps manually means you must constantly check each system's status and fix errors yourself.

This is slow, error-prone, and can cause inconsistent data, like charging a customer without shipping their order.

The Solution

The Saga pattern breaks the big transaction into smaller steps, each with a way to undo itself if something goes wrong later.

This way, the system can automatically keep everything in sync, even if some parts fail.

Before vs After
Before
try {
  updateInventory();
  chargePayment();
  arrangeShipping();
} catch (error) {
  // manual fixes needed
}
After
startSaga()
  .then(updateInventory)
  .then(chargePayment)
  .then(arrangeShipping)
  .catch(undoPreviousSteps);
What It Enables

It enables reliable, automatic coordination of multiple services to keep data consistent without manual intervention.

Real Life Example

When booking a flight, hotel, and car rental from different companies, the Saga pattern ensures that if the hotel booking fails, the flight and car rental bookings are canceled automatically.

Key Takeaways

Manual multi-step processes are slow and error-prone.

Saga pattern splits transactions into steps with compensations.

This keeps distributed systems consistent and reliable.