0
0
Microservicessystem_design~3 mins

Why Two-phase commit (and why to avoid it) in Microservices? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your system freezes waiting for one slow part to say yes or no?

The Scenario

Imagine you run a small shop with two cash registers. When a customer buys something, both registers must record the sale. You try to coordinate by calling each register to confirm the sale before finalizing it.

The Problem

This manual coordination is slow and confusing. If one register confirms but the other doesn't, you don't know what to do. Sometimes sales get lost or recorded twice, causing mistakes and unhappy customers.

The Solution

Two-phase commit is like a strict manager who first asks all registers if they are ready to record the sale, then tells them all to finalize it together. This keeps data consistent but can slow everything down and cause delays if one register is slow or broken.

Before vs After
Before
call register1 to save sale
call register2 to save sale
if both success then confirm else rollback
After
start transaction
prepare register1
prepare register2
if all prepared then commit else abort
What It Enables

It ensures all parts agree on a change or none do, keeping data perfectly in sync across systems.

Real Life Example

In a bank, transferring money between accounts in different systems needs two-phase commit to avoid losing or creating money by mistake.

Key Takeaways

Manual coordination causes delays and errors.

Two-phase commit guarantees consistency but can slow systems and cause blocking.

Understanding its limits helps design better, faster systems.