Sub topic 5
Isolation: concurrent transactions without interference
Prerequisites
This chapter assumes you know basic SQL, how BEGIN, COMMIT and ROLLBACK work, and that a database serves many sessions at once. Examples use PostgreSQL syntax. Other databases follow the same ideas but differ in details.
What isolation promises
Isolation is the "I" in ACID. It says that transactions running at the same time should not interfere with each other. The strongest form of this promise is serializability: the result of running transactions concurrently is the same as if they had run one after another in some order.
Running transactions strictly one at a time would give that guarantee, but it would be very slow. A database needs to overlap work to serve many users. Isolation is the set of rules and mechanisms that let transactions overlap while still giving each one a view of the data that makes sense.
Isolation is not all-or-nothing. Databases offer several isolation levels. Each level allows some kinds of interference and prevents others. Weaker levels run faster and block less. Stronger levels protect more but may make transactions wait or fail. The next chapters cover the specific anomalies and levels. This chapter builds the model you need to understand them.
Why interference happens
A transaction usually reads some data, makes a decision in application code, and then writes. Another transaction can change the same data between those steps. The decision is then based on facts that are no longer true.
Consider two sessions working on the accounts table from earlier chapters.
-- Session A
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- returns 100.00
-- application computes 100.00 - 30 = 70.00
UPDATE accounts SET balance = 70.00 WHERE id = 1;
COMMIT;
-- Session B, running at the same time
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- also returns 100.00
-- application computes 100.00 - 50 = 50.00
UPDATE accounts SET balance = 50.00 WHERE id = 1;
COMMIT;Both sessions read 100.00. The final balance is 50.00 or 70.00, depending on who commits last. One withdrawal has vanished. Each transaction was correct when viewed alone. The problem comes from their overlap. This is the kind of failure isolation exists to prevent.
The core idea: each transaction sees a consistent view
A useful way to think about isolation is to ask what data a transaction is allowed to see. There are two questions:
- Can I see changes made by other transactions that have not committed yet?
- If another transaction commits while I am running, do I see its changes?
Different isolation levels answer these questions differently. In every level PostgreSQL offers, you never see uncommitted changes from other sessions. Whether you see changes committed after your transaction started depends on the level.
Your own changes are always visible to you. If you update a row and then select it in the same transaction, you see the new value, even though nobody else can see it yet.
Two ways to implement isolation
Databases use two main techniques, often combined.
| Technique | Idea | Cost |
|---|---|---|
| Locking | A transaction takes a lock on data it uses. Others that need a conflicting lock wait. | Waiting, and the risk of deadlocks. |
| Multiversion concurrency control (MVCC) | The database keeps several versions of a row. Each transaction reads the version that was current for its view. | Extra storage for old versions, and cleanup work. |
PostgreSQL uses MVCC for ordinary reads, so a plain SELECT does not block writers and is not blocked by them. It uses locks for writes and for explicit locking commands. Later chapters cover both techniques in detail.
The following diagram shows how two overlapping transactions can be arranged on a timeline, and what one of them is allowed to see.
Seeing isolation in action
You can watch the effect of the isolation level directly. Open two psql sessions. Create the table first.
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric(12,2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, balance) VALUES (1, 70.00), (2, 50.00);Now run these steps in order. The comments say which session runs each line.
-- Session A
BEGIN ISOLATION LEVEL READ COMMITTED;
SELECT balance FROM accounts WHERE id = 1; -- 70.00
-- Session B
BEGIN;
UPDATE accounts SET balance = 0 WHERE id = 1;
-- Session A
SELECT balance FROM accounts WHERE id = 1; -- still 70.00, B has not committed
-- Session B
COMMIT;
-- Session A
SELECT balance FROM accounts WHERE id = 1; -- 0.00 under READ COMMITTED
COMMIT;The second read in Session A returns 70.00 because Session B has not committed. After B commits, the third read returns 0.00. Session A saw two different values for the same row inside one transaction. Now repeat the experiment, but start Session A with BEGIN ISOLATION LEVEL REPEATABLE READ;. The third read still returns 70.00, because Session A keeps the snapshot it took at its first query.
Reset the data between runs with UPDATE accounts SET balance = 70.00 WHERE id = 1;.
Isolation level syntax
You set the level when you start a transaction, or change it before the first query.
BEGIN ISOLATION LEVEL SERIALIZABLE;
-- or
BEGIN;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;SET TRANSACTION must run before any query in the transaction. To change the default for a session, use SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL .... If you do not set anything, PostgreSQL uses READ COMMITTED.
What isolation does not do for you
Several common mistakes come from expecting more than isolation provides.
- A transaction is not a lock. Wrapping a read and a write in
BEGIN ... COMMITdoes not stop another session from changing the row in between at the default level. The two-withdrawal example above still loses an update under READ COMMITTED if you compute the new value in the application. Fix it by writing the change as one statement (SET balance = balance - 30), by taking a row lock withSELECT ... FOR UPDATE, or by using a stronger level and retrying on failure. - Isolation levels differ between products. The same level name can behave differently. PostgreSQL's REPEATABLE READ uses snapshots and prevents phantom reads. The SQL standard permits phantoms at that level. MySQL's InnoDB uses REPEATABLE READ as its default. Check your database's documentation before you rely on a guarantee.
- Stronger levels can fail. At REPEATABLE READ and SERIALIZABLE, PostgreSQL may abort a transaction with a serialization error rather than let it produce a result that could not have come from a serial order. Your application has to be ready to retry. A later chapter covers retries.
- Long transactions cost more. A transaction that stays open holds its snapshot, so the database cannot clean up old row versions it might still need. It may also hold locks that block others. Keep transactions short.
A mental checklist
When you design a transaction that reads and then writes, ask:
- Does the write depend on something I read earlier in this transaction?
- Could another transaction change that data before I commit?
- What would go wrong if it did?
- Can I turn the read and write into one atomic statement?
- If not, do I need a row lock, or a stronger isolation level with retry logic?
If the answer to question 3 is "nothing important", the default level is fine. If it is "money is lost" or "a rule is broken", pick a stronger tool deliberately.
Exercise
Two sessions both run SELECT balance FROM accounts WHERE id = 1 and get 100.00. Session A then runs UPDATE accounts SET balance = 70.00 WHERE id = 1 and commits. Session B then runs UPDATE accounts SET balance = 50.00 WHERE id = 1 and commits. Both used READ COMMITTED. What is the final balance, what went wrong, and name two ways to prevent it?
Show answer
The final balance is 50.00. Session A's withdrawal of 30 is lost, because Session B wrote a value computed from a stale read (a lost update). Prevent it by writing the change as a relative update (SET balance = balance - 50), which the database applies to the current row value. Or take SELECT ... FOR UPDATE on the row first, so Session B waits for Session A to commit and then reads the new balance. Using REPEATABLE READ or SERIALIZABLE also prevents it, but Session B would then get a serialization error and must retry.
Exercise
In PostgreSQL, Session A runs BEGIN ISOLATION LEVEL REPEATABLE READ; and reads a row. Session B updates that row and commits. Session A reads the row again. Which value does A see, and why?
Show answer
A sees the old value. REPEATABLE READ gives A a snapshot taken at its first query, and A keeps reading from that snapshot for the rest of the transaction, so B's later commit is not visible to it.