Subscribe

Transactions and isolation levels in Postgres with runnable examples

Two psql sessions against Postgres 18 to reproduce a lost update, a non-repeatable read and write skew, then fixing them with atomic updates, SELECT FOR UPDATE, REPEATABLE READ and SERIALIZABLE with a retry loop in Go.

Transactions and isolation levels in Postgres with runnable examples

Wrapping code in BEGIN and COMMIT does not make it safe. Two transactions that run at the same time can still read the same old value, both write, and one write quietly disappears. Postgres won't throw an error for that by default.

In this blog we will reproduce the classic problems with two psql sessions, then fix each one: lost updates, non-repeatable reads and write skew. It is an intermediate post. You need Docker and a bit of SQL. It follows the index design post in my Postgres in production series. I used Postgres 18.7 (postgres:18-alpine), Go 1.27.3 and pgx v5.13.0, and every output below is pasted from those runs.

Two sessions that line up

You can do all of this by hand with two terminal tabs, typing one line in each in turn. For this post I wanted outputs I could paste, so I put each session in a file and used pg_sleep to line up the steps. My first version had the sleeps wrong and B's update ran before A's, which still lost the update but made the story confusing. A small script runs both at once:

#!/usr/bin/env bash
# run2.sh <setup.sql> <a.sql> <b.sql>: runs two psql sessions at the same time
set -euo pipefail
C=pg18
OUT=$(mktemp -d)
for f in "$@"; do docker cp "$f" "$C:/tmp/$(basename "$f")" >/dev/null; done
docker exec "$C" psql -q -U postgres -d shorty -f "/tmp/$(basename "$1")"
docker exec "$C" psql -U postgres -d shorty -e -f "/tmp/$(basename "$2")" > "$OUT/a.txt" 2>&1 &
docker exec "$C" psql -U postgres -d shorty -e -f "/tmp/$(basename "$3")" > "$OUT/b.txt" 2>&1 &
wait
echo "===== session A"; cat "$OUT/a.txt"
echo "===== session B"; cat "$OUT/b.txt"

The setup puts a click counter and a small links table into a fresh database:

docker run -d --name pg18 -e POSTGRES_PASSWORD=secret postgres:18-alpine
docker exec pg18 psql -U postgres -c "CREATE DATABASE shorty"
DROP TABLE IF EXISTS link_stats, links_t;
CREATE TABLE link_stats (
    code   text PRIMARY KEY,
    clicks int  NOT NULL
);
INSERT INTO link_stats VALUES ('abc123', 10);

-- free plan: at most 3 active links per owner
CREATE TABLE links_t (
    id       bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    owner_id bigint NOT NULL,
    code     text   NOT NULL UNIQUE
);
INSERT INTO links_t (owner_id, code) VALUES (7, 'a1'), (7, 'a2');

Lost update at READ COMMITTED

READ COMMITTED is the default. Each statement sees data committed before that statement started. Here both sessions read the counter, add 1 in "the app", and write the result back. In the outputs below I left out the pg_sleep lines and trimmed psql's column headers, nothing else.

-- a.sql
BEGIN;
SELECT clicks FROM link_stats WHERE code = 'abc123';
SELECT pg_sleep(1) \g /dev/null
UPDATE link_stats SET clicks = 11 WHERE code = 'abc123';   -- 10 + 1
SELECT pg_sleep(1) \g /dev/null
COMMIT;
-- b.sql
SELECT pg_sleep(0.5) \g /dev/null
BEGIN;
SELECT clicks FROM link_stats WHERE code = 'abc123';
SELECT pg_sleep(1) \g /dev/null
\timing on
UPDATE link_stats SET clicks = 11 WHERE code = 'abc123';   -- also 10 + 1
\timing off
COMMIT;
SELECT clicks FROM link_stats WHERE code = 'abc123';
===== session A
SELECT clicks FROM link_stats WHERE code = 'abc123';
     10
UPDATE link_stats SET clicks = 11 WHERE code = 'abc123';
COMMIT;
===== session B
SELECT clicks FROM link_stats WHERE code = 'abc123';
     10
UPDATE link_stats SET clicks = 11 WHERE code = 'abc123';
Time: 513.941 ms
COMMIT;
SELECT clicks FROM link_stats WHERE code = 'abc123';
     11

Two clicks, counter went from 10 to 11. B's UPDATE waited about half a second for A's row lock, then went ahead and wrote 11 on top of A's 11. No error anywhere. This is basically the bug that shows up as "the numbers are a bit low" and nobody can explain.

The easiest fix is not to read at all. Let the database do the arithmetic:

UPDATE link_stats SET clicks = clicks + 1 WHERE code = 'abc123';

When B's update waits on A's lock, Postgres re-reads the committed row after A commits and adds 1 to that. Shorty already does it this way only, its AddClicks query in the pgx and sqlc post is SET clicks = clicks + delta.

SELECT FOR UPDATE when you must read first

Sometimes the app really needs to read, decide, then write (check a balance, check a status). Then lock the row when you read it:

-- a.sql
BEGIN;
SELECT clicks FROM link_stats WHERE code = 'abc123' FOR UPDATE;
SELECT pg_sleep(1) \g /dev/null
UPDATE link_stats SET clicks = 11 WHERE code = 'abc123';
COMMIT;

B runs the same SELECT ... FOR UPDATE half a second later, then writes 12.

===== session B
SELECT clicks FROM link_stats WHERE code = 'abc123' FOR UPDATE;
     11
Time: 508.426 ms
UPDATE link_stats SET clicks = 12 WHERE code = 'abc123';
COMMIT;
SELECT clicks FROM link_stats WHERE code = 'abc123';
     12

B's read blocked until A committed, and then it saw 11, not 10. Correct result. The price is that B waits, so keep these transactions short and never call an HTTP API while holding the lock. If you want workers to skip locked rows instead of waiting, that's FOR UPDATE SKIP LOCKED, which I covered in Postgres job queues in golang.

REPEATABLE READ turns it into an error

Same lost update scripts, only BEGIN ISOLATION LEVEL REPEATABLE READ in both:

===== session B
SELECT clicks FROM link_stats WHERE code = 'abc123';
     10
UPDATE link_stats SET clicks = 11 WHERE code = 'abc123';
psql:/tmp/b.sql:8: ERROR:  could not serialize access due to concurrent update
Time: 501.794 ms
COMMIT;

B waited for A, saw that row changed after its snapshot was taken, and gave up. The final value was A's 11, and B's COMMIT just rolled back (psql printed ROLLBACK for it, I had quiet mode on). Now the bug is loud. The app has to catch the error and run whole transaction again, which we'll do in Go further down.

Non-repeatable reads

This one is less about losing data and more about a report that disagrees with itself. Session A reads the same row twice inside one transaction while B updates it in between:

===== session A
BEGIN;
SELECT clicks FROM link_stats WHERE code = 'abc123';
     10
SELECT clicks FROM link_stats WHERE code = 'abc123';
     50
COMMIT;
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT clicks FROM link_stats WHERE code = 'abc123';
     50
SELECT clicks FROM link_stats WHERE code = 'abc123';
     50
COMMIT;

B set the value to 50 during the first transaction and to 99 during the second. At READ COMMITTED, A saw both 10 and 50 in one transaction. At REPEATABLE READ the snapshot is taken at the first query, so A kept seeing 50 even after B committed 99. For a report that sums several tables, that's what you want. I'd run any report like that at REPEATABLE READ, it costs nothing for read only work.

Write skew: REPEATABLE READ is not enough

Now the shorty plan limit. A free owner may have 3 links. Owner 7 has 2. Now what happens is, two requests arrive together, both count, both see 2, both insert.

BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM links_t WHERE owner_id = 7;
SELECT pg_sleep(0.5) \g /dev/null
-- count was 2, under the limit of 3, so add one
INSERT INTO links_t (owner_id, code) VALUES (7, 'a3');   -- 'b3' in session B
COMMIT;
===== session A
SELECT count(*) FROM links_t WHERE owner_id = 7;
     2
INSERT INTO links_t (owner_id, code) VALUES (7, 'a3');
COMMIT;
SELECT count(*) FROM links_t WHERE owner_id = 7;
     4

Four links. No error, even at REPEATABLE READ, because the two transactions never touched the same row. Each one read a set of rows and wrote a new row the other one didn't read. That is write skew. Row locks can't help here either since there is no row to lock yet (you could lock the owner's row instead, which is a fine fix too).

With BEGIN ISOLATION LEVEL SERIALIZABLE in both files:

===== session B
SELECT count(*) FROM links_t WHERE owner_id = 7;
     2
INSERT INTO links_t (owner_id, code) VALUES (7, 'b3');
psql:/tmp/b.sql:7: ERROR:  could not serialize access due to read/write dependencies among transactions
DETAIL:  Reason code: Canceled on identification as a pivot, during write.
HINT:  The transaction might succeed if retried.

The count stayed at 3. Postgres tracks what each serializable transaction read, notices that the result could not have come from running them one after the other, and cancels one of them. The hint itself is the important part: retry.

Retrying serializable transactions in Go

Both errors above have SQLSTATE 40001. A deadlock is 40P01. The retry has to re-run the whole function, reads included, because the old reads are exactly what was wrong. Here is the helper I use with pgx:

func withSerializableRetry(ctx context.Context, pool *pgxpool.Pool, name string, fn func(pgx.Tx) error) error {
    for attempt := 1; attempt <= 5; attempt++ {
        err := pgx.BeginTxFunc(ctx, pool, pgx.TxOptions{IsoLevel: pgx.Serializable}, fn)
        var pgErr *pgconn.PgError
        if errors.As(err, &pgErr) && (pgErr.Code == "40001" || pgErr.Code == "40P01") {
            log.Printf("%s: attempt %d: %s (%s), retrying", name, attempt, pgErr.Message, pgErr.Code)
            time.Sleep(time.Duration(attempt*20) * time.Millisecond)
            continue
        }
        return err
    }
    return fmt.Errorf("%s: gave up after 5 attempts", name)
}

And the plan limit check inside it:

var errLimit = errors.New("link limit reached")

func addLink(ctx context.Context, pool *pgxpool.Pool, name string, owner int64, code string) error {
    return withSerializableRetry(ctx, pool, name, func(tx pgx.Tx) error {
        var n int
        if err := tx.QueryRow(ctx, `SELECT count(*) FROM links_t WHERE owner_id = $1`, owner).Scan(&n); err != nil {
            return err
        }
        if n >= 3 {
            return errLimit
        }
        _, err := tx.Exec(ctx, `INSERT INTO links_t (owner_id, code) VALUES ($1, $2)`, owner, code)
        return err
    })
}

My test program starts two goroutines calling addLink for owner 7, with a sync.WaitGroup barrier after the first read so they really overlap (left out above, it is only there for the demo). After resetting the tables:

go mod init example.com/isolation
go get github.com/jackc/pgx/v5@v5.13.0
DATABASE_URL="postgres://postgres:secret@localhost:5432/shorty" go run .
2026/11/19 12:07:40 worker-a3: attempt 1: could not serialize access due to read/write dependencies among transactions (40001), retrying
2026/11/19 12:07:40 worker-b3: result: <nil>
2026/11/19 12:07:40 worker-a3: result: link limit reached
2026/11/19 12:07:40 owner 7 has 3 links

One worker won. The other retried, counted 3 this time and returned the business error. Run the container with -p 5432:5432 for this part so Go can reach it.

Which level do I use

My default is READ COMMITTED with atomic updates and the odd FOR UPDATE. That covers counters, balances and status changes. REPEATABLE READ is for reports. SERIALIZABLE is for rules that span several rows, like limits and "no overlapping bookings", and only together with a retry loop, without it you've just swapped a silent bug for a 500 error.

One more thing you can see in the REPEATABLE READ output: after an error the transaction is aborted, every statement fails with "current transaction is aborted" and COMMIT only rolls back. pgx's BeginTxFunc rolls back for you on error, which is one reason I like it over hand written Begin and Commit.

When you're done, docker rm -f pg18 removes the container.