Skip to main content

Understanding Database Isolation Levels

The default isolation level in many databases allows race conditions. Do you know what yours is set to?

The Phenomena
#

  1. Dirty Read: Reading uncommitted data from another transaction.
  2. Non-Repeatable Read: Reading the same row twice gets different data (someone updated it).
  3. Phantom Read: Running the same conceptual query gets different rows (someone inserted a new row).

The Levels
#

LevelDirty ReadNon-RepeatablePhantom
Read UncommittedYesYesYes
Read Committed (Postgres Default)NoYesYes
Repeatable ReadNoNoYes
SerializableNoNoNo

When to use Serializable?
#

When correctness is more important than speed. E.g., Preventing double-spending in a banking ledger.

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN;
-- Your logic
COMMIT;

It guarantees that the result is the same as if transactions were executed one after another.