Part 2 of 6 · 2 min read
What a transaction is
Grouping several operations into one unit that succeeds or fails as a whole.
Think of moving 100 rupees from one bank account to another. The bank must take 100 from one account and add 100 to the other. If it takes the money and then crashes before adding it, 100 rupees have vanished. The bank wants the two steps to be one step in the eyes of everyone.
The book "Designing Data-Intensive Applications" explains that almost all relational databases, and some non-relational ones, support transactions, mostly in the style introduced in 1975 by IBM System R. When the NoSQL movement began in the late 2000s, many new databases gave up transactions, or redefined the word to mean much weaker guarantees. A popular belief grew that transactions are the opposite of scalability and that large systems must abandon them. The book calls both that view and the vendors' claim that transactions are essential for any serious application "pure hyperbole". Transactions have advantages and limits, like any design choice.
Transaction
A transaction groups several reads and writes into one logical unit. Either the whole unit takes effect (it commits) or none of it does (it aborts, also called rolls back).
Example: a transfer of 100 from account A to account B is one transaction with two writes. If the second write fails, the first is undone.
The benefit is a simpler programming model. The application can ignore a large class of failures: partial writes, crashes in the middle, and (depending on the isolation level) interference from other clients.
In a relational database, the client marks a transaction on a connection. Everything between a BEGIN and a COMMIT statement is one transaction. The book notes a flaw: if the connection breaks after the client asked to commit but before the server replied, the client does not know whether it committed.
A worked example in plain steps:
BEGIN
UPDATE accounts SET balance = balance - 100 WHERE id = 'A'
UPDATE accounts SET balance = balance + 100 WHERE id = 'B'
COMMIT
If the machine crashes after the first UPDATE and before COMMIT, the database on restart discards the unfinished transaction. A's balance is back to its old value. If it crashes after COMMIT is acknowledged, both changes are kept.
Check yourself:
- What does it mean for a transaction to abort?
- Why did many NoSQL databases drop transactions, and is the claim fully true?