SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • The Problem with Distributed Transactions
  • Two-Phase Commit (2PC)
  • Three-Phase Commit (3PC)
  • SAGA Pattern
  • Try-Confirm-Cancel (TCC)
  • Compensating Transactions
  • Outbox Pattern
  • Exactly-Once Processing
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Distributed Transactions

The Problem with Distributed Transactions

Why 'all or nothing' across several databases or services is so hard to get.

โฑ 12 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A distributed transaction is one job that must change data in more than one database or service, and must either happen fully or not at all.

  • Inside one database, a transaction is easy: the database has one log and one lock manager, and it can undo everything.
  • Across several machines there is no single judge. Each one commits on its own, and a commit cannot be taken back by someone else.
  • Messages can be lost or late, and machines can crash at the worst moment, so we often cannot tell what happened.
  • The answers are either a commit protocol (like 2PC, slow and can block) or no global transaction at all (like SAGA, fast but you repair mistakes yourself).

02Concept: What is it?

In a single database, the ACID promises are kept for you. If you change two tables in one transaction and the power fails halfway, the database uses its log to undo the half-finished work. Either both changes exist or neither does.

Now think about an online order. The Payment service has its own database. The Inventory service has another. The Shipping service has a third. One order must charge the card, reserve the item and create a shipping label. These are three separate commits on three separate machines. If the second one fails after the first has succeeded, the customer has paid for something that was not reserved.

We want atomicity across machines: all three changes happen, or none. That is much harder than it sounds, because of two facts about distributed systems: any message can be lost or delayed, and any machine can crash at any moment. When no answer arrives, the sender cannot tell whether the other side did the work, did not do it, or is just slow.

One order, three databases
๐Ÿ›’OrderBuy button
โ†’โ†“1
๐Ÿ’ณPayment DBcharged โœ“
โ†’โ†“2
๐Ÿ“ฆInventory DBerror โœ—
โ‡ขโ‡ฃ3
๐ŸššShipping DBnever ran
Each database commits alone. There is no shared log that could undo all three together.
๐Ÿง The core problem
A single commit is a point in time. With several databases there is a gap between the first commit and the last, and a failure inside that gap leaves the system half done.

03Real-Life Example

๐ŸตBooking a Trip with Three Phone Calls
You are planning a trip and must book a flight, a hotel and a car. You call the airline and they confirm. You call the hotel and they confirm. You call the car company and they say: no cars left. Now you must call the airline and the hotel back to cancel. But the airline charges a cancellation fee, and the hotel line is busy. For an hour, you hold a trip that is half booked. Worse, if the car company's line goes silent, you do not even know if the car was booked or not.
Booking the trip
Distributed transaction
Airline, hotel and car company
Three services, each with its own database
Each booking confirmed on a call
A local commit in one database
Cancelling after you already confirmed
Undoing a committed change (a compensation)
A cancellation fee
A side effect that cannot be fully undone
A silent phone line
A timeout: you do not know if the work was done
Asking everyone first: can you hold this for me?
The prepare phase of two-phase commit
A travel agent who coordinates the calls
The transaction coordinator

04Why Do We Need It?

๐Ÿ’ฐMoney must be right
A payment taken without an order, or an order without a payment, costs real money and trust.
๐ŸงฉData is split up
Microservices, sharding and separate systems each own their data, so one business action often touches several.
๐ŸงนNo manual clean-up
Without a plan, people repair half-done orders by hand, which is slow and error-prone.
๐Ÿ”Retries are common
Networks fail, so callers retry. Retries on top of half-done work can double-charge or double-ship.
๐Ÿง Clear thinking
Knowing why this is hard helps you pick the right tool, instead of hoping that it works.
๐ŸŽคA favourite question
Interviewers love it: 'How do you keep two services in sync?' is almost always this problem.
When one job spans many databases, a failure in the middle leaves a mess, and no machine can see the whole picture to fix it alone.

05Where Do We Use It?

๐Ÿ›’Checkout
Payment, stock and shipping live in different services.
๐ŸฆBank transfers
Take money from one account and add it to another, maybe in two different banks.
๐ŸงฎSharded databases
One transaction touches rows that live on two different shards.
โœˆ๏ธTravel booking
Flights, hotels and cars come from different companies.
๐Ÿ””Save, then notify
Update a row and also send a message to a queue. Two systems, one intent.
โ˜๏ธCloud workflows
Steps across several managed services, such as create a user, a bucket and a billing account.

06Types / Parts / How It Works

Why it breaks: three kinds of trouble

TroubleWhat happensExample
Partial failureSome steps worked, others did notPayment charged, inventory failed
Unknown outcomeNo reply, so you cannot tell if it workedTimeout after sending 'reserve the item'
Crash between stepsThe coordinator or a service dies in the gapApp server dies after step 1 of 3
Concurrent usersOthers see or change the half-done dataAnother order buys the last item while yours is waiting
Duplicate requestsA retry repeats work that already happenedThe customer is charged twice

Four ways to deal with it

Choose your approach
Avoid it
๐Ÿ—„๏ธOne databasekeep related data together
Strong: commit protocol
๐Ÿค2PC / 3PCall or nothing, can block
Eventual: undo steps
โ†ฉ๏ธSAGAcompensate on failure
Eventual: reliable events
๐Ÿ“ฌOutbox + idempotencyretry until it works
The further right, the weaker the promise but the easier it scales.
ApproachPromiseCost
Keep the data in one databaseFull ACID, the simplestHard to do when services must own their data
Two-Phase Commit (2PC)All commit or all abortSlow, locks held, blocks if the coordinator dies
SAGAEach step is local, failures are undone by new stepsOthers can see half-done states, and you must write the undo code
Outbox + retries + idempotencyA change and its message are never separatedAt-least-once delivery, so receivers must handle duplicates
VisualizerThree separate commits vs all-or-nothingPick a step that fails and how it fails. With three separate commits, see how the data ends up half done. Switch to all-or-nothing and compare the messages and lock time.
How are the three changes made?
What goes wrong?
How does it fail?
One order = three changes in three different databases (step 1, 2, 3)
๐Ÿ’ณ1. Paymentcharge $50
Committed โœ“
โ†’โ†“
๐Ÿ“ฆ2. Inventoryreserve 1 item
Refused โœ—
โ†’โ†“
๐Ÿšš3. Shippingcreate a label
Never ran
Data consistent?
NO
half done
Customer charged
$50
Stock reserved
No
Label created
No
Messages
4
requests and replies
Row locked for
5 ms
Total time
50 ms
Payment already committed on their own database, and no database can undo another one's commit. The order is now half done: the customer paid for something that was never reserved. Someone must find and repair this by hand or with extra code.

A simplified model (no random numbers): each service does about 5 ms of local work. The all-or-nothing mode is two-phase commit, covered in the next topic. Real systems add logs, retries and timeouts on top of this.

07How to Use It / Steps / Implementation

How to think about it in a design

  1. 1
    First, ask if you need it
    Can the related data live in one database or one service? The best distributed transaction is the one you avoid.
  2. 2
    Find the real requirement
    Must the data be correct at the same instant (money moving), or is 'correct in a few seconds' fine (an email, a counter)?
  3. 3
    Choose a pattern
    Need all-or-nothing at once across a few databases that support it: use 2PC. Need to scale across services: use a SAGA. Need to save data and publish an event safely: use the Outbox pattern.
  4. 4
    Make every step idempotent
    Every call must be safe to repeat, because retries are the normal way to handle an unknown outcome. Use an idempotency key.
  5. 5
    Plan the 'undo' for each step
    For each action, write what the compensation is: a refund, a stock release, a label cancel. Some actions (an email sent) cannot be undone, so put them last.
  6. 6
    Put timeouts everywhere
    A call with no timeout can hang for ever and hold locks. Choose how long to wait and what to do after.
  7. 7
    Make it visible
    Log each step with an order id. Add an alert for transactions stuck in a half-done state, and a way for people to repair them.
๐Ÿ’กOrder the risky step first
Do the step that is most likely to fail, or the one that is hardest to undo, early or late on purpose. Charging a card is easy to refund but an email is not, so send the email last.
โš ๏ธDo not just call three services in a row
The code charge(); reserve(); ship(); looks fine and works on a good day. It has no plan for the day that reserve() fails or times out.

08Key Terms to Know

TermMeaning in easy words
Distributed transactionOne unit of work that changes data in more than one database or service
AtomicityAll of the changes happen, or none of them do
Partial failureSome parts of the system failed while others kept working
CoordinatorThe one process that drives a commit protocol and decides the outcome
ParticipantA database or service that takes part in the transaction
Commit / abortMake the changes permanent, or throw them away
CompensationA new action that reverses the effect of an earlier committed action (a refund)
TimeoutA limit on how long to wait for a reply. It does not tell you what happened
IdempotencyDoing the same request many times has the same effect as doing it once
BlockingParticipants must wait, holding locks, until a crashed process returns
Eventual consistencyThe data may disagree for a short time but will agree later

09Pros, Cons and Trade-offs

โœ… Pros
  • Naming the problem helps you choose a fitting tool
  • All-or-nothing protocols give a strong correctness promise
  • Compensation patterns scale across many services
  • Keeping data together avoids the whole problem
โš ๏ธ Cons
  • A failure in the middle can leave the data half done
  • Strong protocols are slow and can block
  • Weak patterns need extra code for undo and duplicates
  • Timeouts hide what really happened
  • More moving parts means more ways to fail

Trade-offs

ChoiceWe gainWe lose
Strong consistency (2PC)Never a half-done state visibleSpeed, availability and scale
Eventual consistency (SAGA)Speed and independent servicesA short window where data is inconsistent, plus compensation code
One shared databaseSimple ACID transactionsServices are tied together and cannot scale or deploy alone
Long timeoutsFewer false alarmsLocks held longer, users wait longer
Short timeoutsFast failureMore 'unknown outcome' cases to handle

10Common Problems and Mistakes

Common mistakes

  1. Chaining calls with no plan. Charge, then reserve, then ship, with nothing to handle a failure in the middle.
  2. Treating a timeout as a failure. The work may have been done. Retrying without an idempotency key can do it twice.
  3. Assuming a message arrives exactly once. Networks give at-least-once at best, so duplicates happen.
  4. Saving data, then publishing an event in two separate steps. A crash between them loses the event or sends one for data that was rolled back.
  5. Forgetting that some things cannot be undone. A sent email or a physical shipment has no real rollback.
  6. Using 2PC across a slow or unreliable network. Locks are held for long periods and one crash freezes everyone.
  7. No way to find stuck work. Half-done transactions sit for weeks because nothing watches for them.

Things to watch

โ“Unknown outcome
After a timeout, check the state or retry safely. Never guess.
๐Ÿ‘ฏDuplicates
Every handler must cope with seeing the same request twice.
๐Ÿ‘€Dirty reads
Other users may see the half-done state while a SAGA runs.
๐ŸงŸStuck transactions
Alert on anything that has been 'in progress' for too long.

11Real-World Examples

๐ŸฆBanks
Transfers between banks use ledgers, reconciliation and reversals instead of one global lock.
๐Ÿ›’E-commerce
Large shops use SAGA-style order flows: reserve, pay, ship, and refund or release on failure.
๐ŸŒGoogle Spanner
Spanner runs a two-phase commit across shards, made safe by replicating each participant with Paxos.
๐ŸจTravel sites
Holds on flights and rooms expire after a time, which is a built-in way to undo a half-done booking.
๐Ÿ’ณPayment providers
Stripe and others use idempotency keys, so a retried charge does not charge twice.
๐Ÿ—ƒ๏ธXA transactions
Java and many databases support the XA standard, which is a 2PC interface across resources.
๐Ÿ“Note
Company details change over time. Treat these as common patterns rather than exact descriptions of any one system.
Mini case: a checkout with a safety net
๐Ÿ’ณCharge
โ†’โ†“
๐Ÿ“ฆReserveout of stock
โ‡ขโ‡ฃundo
โ†ฉ๏ธRefundcompensation
Done Failed Undo step
Each step is local. A failure triggers the undo of the steps before it.

12Related Topics to Read Next

ACID Transactionsโ†’

The promises one database gives you, which we now want across many.

Two-Phase Commit (2PC)โ†’

The classic protocol for all-or-nothing across machines.

Three-Phase Commit (3PC)โ†’

An attempt to fix the blocking problem of 2PC.

SAGA Patternโ†’

Undo steps with compensations instead of one big transaction.

Outbox Patternโ†’

Save the data and the event together, then publish safely.

Idempotencyโ†’

Makes retries safe after an unknown outcome.

Challenges of Distributionโ†’

The wider list of reasons why distributed systems are hard.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: one job that changes data in several databases, all or nothing.
  • โœ”Why hard: no shared log, lost messages, crashes at any moment, and timeouts hide the truth.
  • โœ”Best fix: avoid it by keeping related data together.
  • โœ”Strong: 2PC. All commit or all abort, but slow and it can block.
  • โœ”Eventual: SAGA with compensations, and the Outbox pattern for safe events.
  • โœ”Always: idempotent steps, timeouts, and an alert for stuck work.
  • โœ”Order: do hard-to-undo steps (emails, shipping) last.
  • โœ”One line: โ€œAcross machines you cannot have one commit, so you either vote first or plan the undo.โ€
โ† Previous
Byzantine Fault Tolerance (BFT)
Next โ†’
Two-Phase Commit (2PC)