Lesson 01: The Setup

The Transaction Problem

On a single PostgreSQL server, transferring money between two accounts is simple. You wrap the two operations in a BEGIN TRANSACTION and COMMIT block. The database guarantees ACID semantics: either both the debit and credit succeed, or both fail (Atomicity). You never end up in a state where money is created or destroyed.

But what happens when you shard your database? What if Alice's account lives on Server A in New York, and Bob's account lives on Server B in London?

The Fallacies of Distributed Computing

You write an API endpoint that executes this code:

1. ServerA.query("UPDATE accounts SET balance = balance - 100 WHERE id = 'Alice'")

2. ServerB.query("UPDATE accounts SET balance = balance + 100 WHERE id = 'Bob'")

If step 1 succeeds, but step 2 fails (because Server B crashed, or the network between New York and London went down), you have a massive problem. Alice lost $100, but Bob never received it. The money was literally destroyed.

Money Transfer Simulator

Click "Transfer $100" to simulate a successful transfer across the network. Then, click "Transfer & Crash Network" to watch how a partial failure destroys data integrity.

Server A (NY)
Alice's Account
$1000
+$100
Server B (LON)
Bob's Account
$1000
Total system money: $2000

The Need for Coordination

In a distributed system, you cannot simply execute independent queries on different servers and hope they both succeed. If there's a failure in the middle of the workflow, you are left with an inconsistent system state.

We need an algorithm that can guarantee Atomicity (all or nothing) across multiple physical machines. The classic solution to this is the Two-Phase Commit (2PC) protocol, which we will explore next.

Check yourself

1. Why is a local ACID transaction insufficient for a bank transfer between two different physical servers?

If the network crashes after Server A debits the account, but before Server B credits the account, the money is permanently destroyed. You need a distributed coordination protocol to prevent this.