Sub topic 1
Transactions and the I in ACID
Prerequisites
This chapter assumes you already know the following:
- Basic SQL:
SELECT,INSERT,UPDATEandDELETE. - How to use
BEGIN,COMMITandROLLBACK. - Relational tables and primary keys.
- A database serves many clients at the same time.
You do not need to know anything about locks, MVCC or isolation levels yet. This chapter introduces the vocabulary that the rest of the tutorial builds on.
What a transaction is
A transaction is a group of SQL statements that the database treats as one unit of work. Either all of its changes become permanent, or none of them do. You mark the boundaries with BEGIN (or START TRANSACTION) and finish with COMMIT or ROLLBACK.
The classic example is a money transfer. Moving 30 from one account to another takes two updates:
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100), (2, 50);
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;If the server crashes between the two UPDATE statements, you do not want 30 to vanish. The transaction guarantees it will not. After recovery, either both updates are visible or neither is.
Most databases also wrap a single statement outside BEGIN in its own transaction. This is called autocommit mode. Every statement you have ever run in a plain client session was already a tiny transaction.
The four ACID properties
ACID is a set of four guarantees that a transactional database offers.
| Property | Meaning | Typical mechanism |
|---|---|---|
| Atomicity | All statements take effect, or none do | Undo information, rollback |
| Consistency | A transaction moves the database from one valid state to another | Constraints, triggers, application logic |
| Isolation | Concurrent transactions do not interfere with each other | Locks, multiversion snapshots |
| Durability | Once committed, data survives crashes | Write-ahead log, flushing to disk |
Two of these are easy to misread.
Consistency is partly your job. The database enforces the rules you declare, such as NOT NULL, UNIQUE, foreign keys and CHECK constraints. A rule like "at least one doctor must be on duty" is not declared anywhere, so the database cannot enforce it unless you make isolation do the work. Later chapters show this failure, called write skew.
Isolation is the property this tutorial is about. It is the one with a real cost, which the next sections explain.
The I in ACID
Isolation means that a transaction should behave as if it were running alone, even though other transactions are running at the same moment. The strictest form is called serializability. A set of concurrent transactions is serializable if the result is the same as running them one after another in some order. The database may interleave the work internally, but you could never tell from the outcome.
Here is a schedule with two transactions, A and B, each moving money out of account 1. The balance starts at 100.
The last read is the interesting one. If the database returns 100, transaction A has a stable view of the data. If it returns 50, A saw another transaction's work appear halfway through. Neither answer is a bug. Each is the documented behavior of a particular isolation level.
Why full isolation is traded against concurrency
The simplest way to give perfect isolation is to run transactions strictly one at a time. That is correct, but it wastes the hardware. While one transaction waits for disk or for a slow client, every other client waits too. A busy application would have throughput of one transaction at a time.
Databases therefore allow transactions to overlap, and the more they overlap, the more ways they can interfere. Stronger isolation needs more of one or more of these costs:
- Blocking. A transaction waits for a lock held by another.
- Aborts. The database cancels a transaction that cannot be fit into a consistent order, and the application must retry it.
- Memory and bookkeeping. The database keeps old row versions or tracks which rows each transaction read.
Weaker isolation avoids those costs but lets some anomalies through. An anomaly is a result that could not have happened if the transactions had run one at a time. The SQL standard defines four isolation levels as a menu. Each level allows a different set of anomalies, and you choose per transaction.
The goal is not to always pick the strongest level. The goal is to pick the weakest level that is still correct for the work you are doing, and to know which risks you have accepted.
Seeing isolation at work
Isolation is easiest to understand by running two sessions side by side. Open two terminals connected to the same PostgreSQL database and use the accounts table from above (account 1 holds 100).
Session A starts a transaction and reads:
-- Session A
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- returns 100Session B changes the row and commits:
-- Session B
BEGIN;
UPDATE accounts SET balance = 50 WHERE id = 1;
COMMIT;Session A reads again:
-- Session A
SELECT balance FROM accounts WHERE id = 1; -- returns 50 in PostgreSQL's default level
COMMIT;In PostgreSQL's default level, READ COMMITTED, the second read returns 50. Each statement sees whatever was committed when it started. If you repeat the experiment starting Session A with BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;, the second read still returns 100.
The same data and the same two sessions gave different answers. Only the isolation level changed. That is the whole subject of this tutorial.
What isolation does not cover
It helps to be clear about what the I in ACID does not promise.
- It does not mean "no locking". Many engines provide isolation without readers ever blocking.
- It does not mean serializable by default. Most databases ship with a weaker default level for speed. PostgreSQL and Oracle default to READ COMMITTED, MySQL InnoDB defaults to REPEATABLE READ, and SQL Server defaults to READ COMMITTED.
- It does not apply across transactions that your application splits up. If your code reads a balance in one transaction and writes in another, the database sees two unrelated units of work.
- It does not protect work outside the database, such as sending an email or calling an API. Those actions are not rolled back.
How the rest of the tutorial is organized
The following chapters follow a path from problems to solutions:
- The specific anomalies: dirty reads, non-repeatable reads, phantom reads, lost updates and write skew.
- The four standard isolation levels and how each one allows or forbids those anomalies.
- How to set a level in PostgreSQL, MySQL and SQL Server.
- How locking and multiversion concurrency control (MVCC) work inside the engine.
- Engine differences, retry handling and how to choose a level for a workload.
Each anomaly gets a short schedule of two transactions that you can run yourself. Learning to read such schedules is the core skill. Given the order of statements from two sessions, you should be able to say what each read returns and whether the final state could have come from a serial execution.
Common misunderstandings
- "A transaction makes my code safe from races." Not by itself. A transaction at a weak level still allows races between a read and a later write.
- "Higher isolation is always better." It is safer, but it may cause more blocking and more transaction failures that your code must handle.
- "My ORM handles this." An ORM opens transactions, but it usually does not change the isolation level or retry failed transactions unless you configure it to.
- "SERIALIZABLE means the same thing everywhere." The name is shared, but engines implement it differently. Some use locks and some use conflict detection, and the visible behavior differs. A later chapter covers this.
Exercise
A transaction reads an account balance of 100. Another transaction then commits a change to 50. The first transaction reads the balance again and sees 50. Which ACID property is being weakened, and why is this behavior still allowed by the database?
Show answer
Isolation is being weakened, because the first transaction saw another transaction's committed work appear while it was still running. It is allowed because the database is running at a level such as READ COMMITTED, which permits this anomaly in exchange for less blocking and fewer aborted transactions. A stronger level, such as REPEATABLE READ, would return 100 both times.
Exercise
Why does a database not simply run every transaction one at a time to get perfect isolation?
Show answer
Serial execution gives correct results but removes concurrency. Every transaction would wait for all earlier ones, including time spent on disk reads or waiting for the client, so throughput would be very low. Databases allow transactions to overlap and offer weaker isolation levels as a trade-off, with stronger levels costing more blocking, retries or bookkeeping.
Exercise
The rule "at least one doctor must stay on duty" is not declared as a constraint. Which ACID property is mainly responsible for keeping this rule true, and who is responsible for it?
Show answer
Consistency. The database only enforces rules you declare, so the application must either express the rule in a constraint or use a sufficiently strong isolation level or explicit locking to prevent concurrent transactions from breaking it.