Transactions, from One Database to Many Services
Almost every system design interview has a moment where two things need to happen together, or not at all. Money leaves one account and arrives in another. A seat is reserved and an order is created. An order is saved and an event is published. How you handle that moment says a lot about how well you understand the systems you're drawing.
When everything lives in one database, the answer is a transaction, and the database does the hard work. Once the data is split across shards or services, there's no single database to do that work, and you have to choose between a few patterns with very different trade-offs.
We'll build this up from the bottom:
- What a transaction promises (ACID), and how a database keeps those promises, starting with rollback in a tiny in-memory key-value store.
- Isolation: what goes wrong when transactions run at the same time, and how databases prevent it.
- Distributed transactions: two-phase commit, sagas, and the outbox pattern, and when to use each one in an interview.
What a Transaction Promises
A transaction groups several reads and writes into one unit. The guarantees are usually summarized as ACID:
- Atomicity: all of the writes happen, or none of them do. If anything fails halfway, the database rolls back to how things were before. "Abortability" would honestly be a better name.
- Consistency: the data moves from one valid state to another. In practice this is mostly your job (constraints, invariants like "balance never goes negative"). The database helps with things like foreign keys and unique constraints.
- Isolation: transactions running at the same time don't step on each other. Ideally each one behaves as if it ran alone. In practice, databases offer weaker levels for speed, and this is where most real bugs come from.
- Durability: once the database says "committed," the data survives a crash.
The classic example is a transfer:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 'alice';
UPDATE accounts SET balance = balance + 100 WHERE id = 'bob';
COMMIT;
If the server crashes between the two updates, atomicity means Alice doesn't lose $100 into thin air. If two transfers from Alice run at the same moment, isolation decides whether both can see her $150 balance and both succeed.