All or nothing
A wallet app moves money between accounts: 10,000 req/s, and 60% are transfers. Every transfer must take from one account and add to another, or do neither. One Postgres primary can't take the writes.
Play this levelFree with an account. It runs in your browser: build the design, press Run, and watch what breaks.
The lesson
A transaction groups changes so they all happen or none do. ACID names what it promises: atomic, consistent, isolated and durable.
Isolation decides what transactions running at once can see of each other. Weak levels allow surprises like two transfers both reading a balance of £100 and both spending it. Serializable acts as if they ran one after another, and costs the most.
When one primary can't take the writes, distributed SQL such as CockroachDB or Spanner spreads them over many machines and keeps transactions across all of them, at the price of a little extra time on each write.
What you have to achieve
10,000 requests a second at the busiest hour, 60% of them writes.
- No broken or illegal connections
- Use a Distributed SQL with at least 3 instances
- No component is overloaded
- Fewer than 0.1% of requests fail
What you learn
Transfers stay all or nothing, and the writes are spread across many machines. Distributed SQL kept the guarantees that money needs, where NoSQL would have made you give them up.
Check yourself
A transfer takes £50 from Ana and the server crashes before adding it to Ben. What should a transaction guarantee?
- Ana loses £50
- Neither change is kept
- Ben gets £100
Show the answer
Neither change is kept. Atomic means all or nothing. A half-finished transaction is undone, so no money appears or vanishes.
Two transfers both read a balance of £100 and both spend it. What stops this?
- A bigger server
- A stronger isolation level, such as serializable
- A cache
Show the answer
A stronger isolation level, such as serializable. Stronger isolation makes transactions behave as if they ran one at a time, so the second sees the first one's change.
Why not move the wallet to a NoSQL key-value store?
- It can't store numbers
- Most can't change two accounts in one transaction
- It's always slower
Show the answer
Most can't change two accounts in one transaction. Most key-value stores only promise changes to one item at a time. Moving money between two accounts needs a transaction across both.