Isolation levels

Author      Ter-Petrosyan Hakob

In PostgreSQL—as in many relational database management systems (RDBMS)—isolation levels control how transactions interact with each other and with the data they access. Different isolation levels offer trade-offs between consistency, concurrency, and performance by determining which changes become visible to concurrent transactions.

In this post, we explain each isolation level, discuss common concurrency anomalies, and show practical examples of setting isolation levels in PostgreSQL.

Concurrency Anomalies in Transactions

Understanding the anomalies that isolation levels aim to address can help in choosing the right one for your application:

Higher isolation levels (i.e., REPEATABLE READ and SERIALIZABLE) are designed to eliminate these anomalies—but with the trade-off of potentially reduced concurrency and performance.

Overview of Isolation Levels

The SQL standard defines four isolation levels, each increasing the level of protection against anomalies:

Configuring Transaction Isolation in PostgreSQL

You can set the isolation level for a transaction at the beginning of the transaction block. For example:

BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;

Or, omitting the optional keyword for brevity:

BEGIN;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

IMPORTANT:

The SET TRANSACTION statement must be the first command in the transaction block. Any statement executed before setting the isolation level causes subsequent attempts to change it to fail:

BEGIN;
SELECT count(*) FROM categories;

-- a query has been executed, the SET TRANSACTION
-- is not anymore the very first command

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
ERROR:  SET TRANSACTION ISOLATION LEVEL must be called before any query

Once the transaction has started, the isolation level cannot be changed.

In-Depth: Isolation Levels in PostgreSQL

READ UNCOMMITTED

READ COMMITTED

REPEATABLE READ

SERIALIZABLE

Phantom Reads: A Closer Look

Although discussed above, phantom reads deserve special attention:

Unrepeatable Reads vs. Phantom Reads

Both anomalies relate to changes observed during a transaction:

By choosing the appropriate isolation level, you can balance the need for consistency with performance: