Sub topic 3
Write-ahead logging and crash recovery
This chapter assumes you know basic SQL, transactions with BEGIN and COMMIT, primary keys, and the four ACID properties.
Write-ahead logging
A write-ahead log (WAL) is an append-only file. The database writes a record of each change to the WAL before it changes the table data. When a transaction commits, its WAL records are flushed to disk. After a crash, the database replays the log to redo committed changes and to undo unfinished ones. This is how durability holds.
Locking with SELECT ... FOR UPDATE
SELECT ... FOR UPDATE locks the rows it reads. Other transactions that try to update or lock those rows wait until you commit or roll back.
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
UPDATE accounts SET balance = balance - 20 WHERE id = 1;
COMMIT;MVCC: readers do not block writers
Multiversion concurrency control (MVCC) keeps several versions of a row. A plain SELECT reads a snapshot of committed versions, so it does not wait for writers. Writers still lock the rows they change.
Deadlocks
A deadlock occurs when transaction A waits for a lock held by B while B waits for a lock held by A.
PostgreSQL detects the cycle and aborts one transaction. You avoid most deadlocks by locking rows in the same order in every transaction.
Retrying after deadlocks and serialization failures
Deadlocks and serialization failures both abort the transaction. The application should roll back and run the whole transaction again, with a limit on attempts.
| Error | SQLSTATE | Action |
|---|---|---|
| Deadlock detected | 40P01 | Retry the transaction |
| Serialization failure | 40001 | Retry the transaction |
Designing transactions well
- Keep transactions short.
- Lock rows in a fixed order.
- Do not wait for user input or network calls while a transaction is open.
- Use the lowest isolation level that still prevents the anomalies your code cannot tolerate.
Distributed transactions and two-phase commit
When one transaction spans several databases, two-phase commit (2PC) coordinates them. In the first phase, each database prepares and promises it can commit. In the second phase, the coordinator tells all of them to commit. If the coordinator crashes between the phases, prepared databases keep their locks until it recovers. That blocking is why 2PC is costly.
Exercise
Why must a deadlock victim be retried rather than simply waited on?
Show answer
PostgreSQL aborts one transaction to break the cycle. That transaction cannot finish by waiting, so it must be rolled back and run again from BEGIN.