Transactions & Isolation Levels — Database

A transaction runs commands as one package (ACID), and DB::transaction() wraps it in Laravel. When transactions run together there are four problems: a dirty…

In the SQL lesson Transactions, your transaction ran alone: BEGIN, a few commands, COMMIT. In a busy café, two cashiers can sell a Milk Coffee in the same second. There are 10 cups left. Both read 10, both write 9, and two cups are sold but the stock only drops by one. No error at all.

A transaction is a group of database commands that travel as one package: all of them succeed, or all of them are cancelled. An isolation level controls something else: when two transactions run at the same time, how much one may see of the other's work. Those two cashiers are like two people writing the stock in the same notebook. If both read the same number and then both write it back, one of the entries gets overwritten. The isolation level is the rule for sharing that notebook.

Transactions and ACID

BEGIN;
UPDATE products SET stock = stock - 1 WHERE id = 1;
INSERT INTO orders (customer_id, total) VALUES (1, 450);
COMMIT;   -- or ROLLBACK; to cancel all of it

A good transaction has four properties, abbreviated ACID:

In Laravel, DB::transaction(function () { ... }) runs its body in one transaction: it COMMITs when the body finishes, and ROLLBACKs when it throws an exception.

Four problems when transactions run together

Problem What happens Example at Sunset Coffee
Dirty read reading another transaction's change that is not committed yet A sets the stock to 5 and then ROLLBACKs, but B has already read 5
Non-repeatable read reading the same row twice gives different results B reads stock 10, A changes it to 5 and COMMITs, B reads again: 5
Phantom read the same query returns a different number of rows B counts Budi's orders: 2. A adds one and COMMITs. B counts again: 3
Lost update two transactions read the old value and both overwrite it two cups sold, the stock only drops by 1

Lost update

This is the order of events for those two cashiers, at PostgreSQL's default isolation level (READ COMMITTED):

Step Cashier A Cashier B stock in the database
1 SELECT stock gets 10 10
2 SELECT stock gets 10 10
3 UPDATE ... SET stock = 9 10, A's change not committed yet
4 COMMIT 9
5 UPDATE ... SET stock = 9 9
6 COMMIT 9

The final stock is 9, with no error. Two cups sold, one decrement lost, because B worked out 9 from a 10 that was already stale.

The cure: don't do the arithmetic in the app. Let the database subtract:

UPDATE products SET stock = stock - 1 WHERE id = 1;

At READ COMMITTED, this UPDATE locks the row, and the second transaction waits until the first finishes, then subtracts from the latest number: the stock becomes 8. If the app must read first (say, to check there's enough stock), lock the row as you read it with SELECT stock FROM products WHERE id = 1 FOR UPDATE;. A shorter way: put the condition in the UPDATE itself, ... WHERE id = 1 AND stock >= 1, then check how many rows changed. If it is 0, no stock is left, so the stock never goes below 0.

Four isolation levels

The SQL standard defines four levels, from the loosest to the strictest. The stricter, the fewer problems, but the more often transactions wait for each other or get cancelled.

Level Dirty read Non-repeatable read Phantom read
READ UNCOMMITTED possible possible possible
READ COMMITTED prevented possible possible
REPEATABLE READ prevented prevented possible
SERIALIZABLE prevented prevented prevented

SERIALIZABLE is the strictest: the result is guaranteed to be the same as running the transactions one at a time, in some order. A dirty read is only possible at READ UNCOMMITTED.

PostgreSQL and MySQL aren't the same

The table above is the standard's minimum. Each database fills it in its own way:

Level PostgreSQL MySQL (InnoDB)
READ UNCOMMITTED treated the same as READ COMMITTED: a dirty read never happens dirty reads can happen
READ COMMITTED default. Each SELECT sees the data committed at that moment the same
REPEATABLE READ one snapshot for the whole transaction, so phantoms don't happen either. A lost update is stopped with ERROR: could not serialize access due to concurrent update default. A plain SELECT reads a snapshot, but an UPDATE reads the latest value: lost updates still get through
SERIALIZABLE transactions run without waiting for each other, then one of them is cancelled with an error if the result couldn't come from running them in order a plain SELECT becomes SELECT ... FOR SHARE: transactions wait on each other's locks, sometimes ending in Deadlock found when trying to get lock

SQLite is simpler: only one transaction may write at a time. A second writer waits, or gets the error database is locked. The result is always serializable.

In every database, a transaction cancelled because of a conflict (a serialization error or a deadlock) must be retried by the app. In Laravel, the second argument of DB::transaction() is the number of attempts:

DB::transaction(function () {
    DB::table('products')->where('id', 1)->decrement('stock'); // stock = stock - 1
    DB::table('orders')->insert(['customer_id' => 1, 'total' => 450]);
}, 3); // retry up to 3 times on a deadlock or serialization error

Choosing a level

Need Level
maximum speed read uncommitted, the loosest. Rarely used, and in PostgreSQL it's the same as read committed
default, general read committed, PostgreSQL's default and a safe pick for most apps
read consistency repeatable read, say a report that reads many tables that must agree with each other
maximum safety, financial serializable, for money and stock that must never be wrong, with retries in the app

How to set it: in PostgreSQL BEGIN ISOLATION LEVEL SERIALIZABLE;, in MySQL SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; before START TRANSACTION;.

⚠️ Stock that drifts, errors left unhandled

TL;DR: A transaction runs commands as one package (ACID), and DB::transaction() wraps it in Laravel. When transactions run together there are four problems: a dirty read (reading what isn't committed), a non-repeatable read (the same row changes), a phantom read (the number of rows changes), and a lost update (two writers overwrite each other, a stock of 10 decremented twice ends at 9). The four levels from loose to strict: READ UNCOMMITTED, READ COMMITTED (PostgreSQL's default), REPEATABLE READ (MySQL's default) and SERIALIZABLE (the strictest, as if in order). PostgreSQL and MySQL differ at the same level, and SQLite has only one writer. Prevent lost updates with stock = stock - 1 or FOR UPDATE, and retry transactions cancelled by a conflict.

⚡ Two cashiers, one stock

Guess first: the stock is 10. Two cashiers both read 10, then both write 9. What's the final stock?

Still 9, with no error. Two cups sold, but one decrement lost. This is called a lost update.

Meaning: A transaction runs several commands as one package. The isolation level controls how much transactions running at the same time may see of each other's work.

⚡ Let the database subtract

Write:

UPDATE products SET stock = stock - 1 WHERE id = 1;

Meaning: Don't do the arithmetic in the app. This UPDATE locks the row, so the second transaction waits, then subtracts from the latest number: the stock becomes 8.

⚡ Four levels

Meaning: From the loosest: READ UNCOMMITTED, READ COMMITTED (PostgreSQL's default), REPEATABLE READ (MySQL's default), and SERIALIZABLE, the strictest: the result is as if the transactions ran one at a time. A transaction cancelled by a conflict must be retried by the app.

In the exercise, the text is lowercase, for example "read committed".

What you will learn