Sub topic 14
Choosing an isolation level for your workload
This chapter assumes you know the anomalies (dirty read, non-repeatable read, phantom read, lost update, write skew) and the four SQL standard levels. It also assumes you can run BEGIN, COMMIT and ROLLBACK. The goal here is a decision procedure: given a workload, which level do you set, and what else do you add?
Start from the invariant, not the level
An isolation level is a means. The real question is which rule your data must obey and which transactions can break it. Work through these steps for each transaction type:
- Write down the invariant in one sentence. Example: "an account balance never goes below zero" or "at least one doctor is on call."
- List the statements that read data to decide something, and the statements that write based on that decision.
- Ask which anomaly could break the invariant if another transaction ran in between.
- Pick the cheapest tool that closes that gap.
Many transactions have no such invariant. A page view counter or a read of a product description cannot be corrupted by interleaving. These need no special care.
What each level buys you
The table shows what each level permits under the SQL standard. Real engines often forbid more, so treat it as the minimum you can rely on in portable code.
| Level | Dirty read | Non-repeatable read | Phantom read | Lost update | Write skew |
|---|---|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible | Possible | Possible |
| READ COMMITTED | No | Possible | Possible | Possible | Possible |
| REPEATABLE READ | No | No | Possible in the standard | Engine dependent | Possible |
| SERIALIZABLE | No | No | No | No | No |
The "engine dependent" entry matters. PostgreSQL's REPEATABLE READ is snapshot isolation and aborts a lost update with a serialization error. MySQL InnoDB's REPEATABLE READ does not abort it for plain read-then-write code, because UPDATE works on the latest committed row. Check your engine before you rely on the level alone.
The cost side
Stronger isolation costs something, and the cost differs by implementation.
- Lock-based serializable (SQL Server's default SERIALIZABLE, MySQL InnoDB's SERIALIZABLE): readers take shared locks, including range locks. Throughput drops and blocking and deadlocks rise.
- Snapshot-based serializable (PostgreSQL's SERIALIZABLE, using serializable snapshot isolation): readers do not block writers. The cost is bookkeeping and extra aborts. Your application must retry.
- Snapshot levels in general: long-running transactions hold old row versions, which can bloat storage and delay cleanup.
So the trade-off is not simply "safe versus fast." It is "blocking versus aborting versus handling the anomaly yourself."
Common workloads and a sensible default
Simple reads and independent writes
Web pages that render a product, a profile or a feed do not depend on a consistent multi-statement view. READ COMMITTED, the default in PostgreSQL, SQL Server and Oracle, works well. Each statement sees committed data and nothing blocks.
Reports and exports
A report that runs several queries must agree with itself. If one query counts orders and another sums their totals, a commit between them gives numbers that do not match. Use REPEATABLE READ (a single snapshot) and, where possible, mark it read-only so the engine can optimize.
-- PostgreSQL: a consistent snapshot for a multi-query report
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT count(*) FROM orders WHERE created_at >= date '2026-11-01';
SELECT sum(total) FROM orders WHERE created_at >= date '2026-11-01';
COMMIT;Both queries see the same set of orders, even if new orders commit while the report runs.
Counters, balances and inventory
These are read-modify-write on one row. Do not rely on a high isolation level for this. Make the change atomic.
-- Decrement stock only if enough remains; check the affected row count
UPDATE products
SET stock = stock - 1
WHERE id = 42 AND stock > 0;If the driver reports zero rows affected, the item is sold out. The condition and the write happen in one statement, so no other transaction can slip between them, at any isolation level. When logic is too complex for one statement, use SELECT ... FOR UPDATE and read the row under its lock.
Invariants across several rows
"At least one doctor on call," "no two bookings overlap," "total allocated stays under the budget": the decision reads many rows and the write touches a different one. Snapshot isolation lets two transactions both pass the check. You have three options:
- Use SERIALIZABLE and retry on failure.
- Lock the rows that the decision reads, with
SELECT ... FOR UPDATE, or lock one parent row that guards the whole group. - Encode the rule as a constraint the database enforces, such as a unique index or an exclusion constraint in PostgreSQL.
Constraints are often the best answer. They hold at every isolation level and need no retry logic beyond handling the constraint error.
Uniqueness and "insert if absent"
Checking "does this row exist?" and then inserting is a phantom problem. A unique index is the correct fix. Use INSERT ... ON CONFLICT in PostgreSQL or INSERT ... ON DUPLICATE KEY UPDATE in MySQL rather than a check followed by an insert.
Using SERIALIZABLE safely
SERIALIZABLE is the only level that lets you reason about a transaction as if it ran alone. That convenience comes with conditions.
- Every transaction must be retryable. PostgreSQL raises SQLSTATE
40001. SQL Server snapshot conflicts and deadlocks raise errors 3960 and 1205. MySQL reports deadlocks as error 1213. The application must catch these and rerun the whole transaction. - Keep transactions short. Long transactions raise the chance of conflict.
- Make retries safe. Do not send an email or call a payment API inside the transaction. Perform side effects after a successful commit.
- Apply it to everything involved. In PostgreSQL, serializable guarantees only hold if all transactions that touch the related data run at SERIALIZABLE. Mixing levels weakens the guarantee.
A retry loop looks like this:
import psycopg2
from psycopg2 import errors
def run_serializable(conn, work, max_attempts=5):
for attempt in range(max_attempts):
try:
conn.set_session(isolation_level="SERIALIZABLE")
with conn: # commits on success, rolls back on error
with conn.cursor() as cur:
return work(cur)
except (errors.SerializationFailure, errors.DeadlockDetected):
conn.rollback()
if attempt == max_attempts - 1:
raiseReal code should also wait a short, random delay between attempts so that two conflicting transactions do not collide again at the same moment.
Choosing between the techniques
| Situation | Preferred tool | Why |
|---|---|---|
| Single-row counter or balance | Atomic `UPDATE` expression | No window between read and write |
| Complex single-row logic | `SELECT ... FOR UPDATE` | The lock holds the row until commit |
| Consistent multi-query report | REPEATABLE READ, read-only | One snapshot, no blocking |
| Rule across several rows | Constraint, or SERIALIZABLE with retries | Closes write skew and phantoms |
| Existence check before insert | Unique index and upsert | Database enforces it |
| General request handling | READ COMMITTED | Low cost, no retry burden |
Edge cases to check before you decide
- MySQL and PostgreSQL share the name but not the behavior. REPEATABLE READ in MySQL still lets locking reads (
FOR UPDATE) and writes see the latest committed rows, which differs from its plain reads. Test your exact scenario. - Oracle has no true REPEATABLE READ. Its SERIALIZABLE is snapshot isolation and still permits write skew. Oracle also raises
ORA-08177when it cannot serialize. - SQL Server's default is lock-based READ COMMITTED. Enabling
READ_COMMITTED_SNAPSHOTswitches it to row versioning, which changes blocking behavior for existing code. - Read-only replicas and snapshots. A report on a replica sees the replica's state, which may lag. Isolation does not fix replication delay.
- Autocommit. Outside an explicit transaction, each statement is its own transaction. Two separate statements in autocommit mode get no isolation between them.
Verify with a test, not an assumption
Reproduce your invariant with two sessions before shipping. Open two connections, interleave the statements by hand, and check the result at the level you plan to use. If the invariant breaks, you need a stronger tool. If it holds, record in a comment which mechanism protects it (isolation level, lock or constraint), so a later change to the level does not silently remove the protection.
Exercise
A ticketing app checks SELECT count(*) FROM seats WHERE event_id = 7 AND held_by IS NULL, and if the count is above zero it runs UPDATE seats SET held_by = :user WHERE id = :seat_id. Two users sometimes get the same seat. Name two different fixes, and say what the application must do if you choose SERIALIZABLE.
Show answer
Fix 1: make the claim atomic by using UPDATE seats SET held_by = :user WHERE id = :seat_id AND held_by IS NULL and checking that one row was affected. Fix 2: lock the seat row first with SELECT ... FOR UPDATE, then update it. Running at SERIALIZABLE also works, but the application must catch serialization failures (SQLSTATE 40001 in PostgreSQL) and rerun the entire transaction, without performing side effects such as sending confirmations until the commit succeeds.
Exercise
Why is a unique index often a better answer to write skew or "insert if absent" than raising the isolation level?
Show answer
The database enforces a constraint at every isolation level, for every client, without retry logic beyond handling the constraint error. An isolation level protects only transactions that run at that level, and the application must handle aborts.