Postgres Transaction Isolation Levels from Node.js: Write Skew, SERIALIZABLE, and Retrying 40001
Table of Contents
About the Author

Ahmed Mahmoud
Author & Developer
Software engineer passionate about web development and user experience design.
Founder of Devya · eng-ahmed.com ↗Headline: PostgreSQL runs every transaction at READ COMMITTED by default, so two concurrent Node.js requests can each pass the same check and together break an invariant that neither broke alone. At Devya we protect invariants with a schema constraint, an atomic single-statement UPDATE, or a parent-row lock first, and we use SERIALIZABLE with a bounded whole-transaction retry on SQLSTATE 40001 only when the invariant spans rows with no natural lock target.
A transaction isolation level is the PostgreSQL setting that decides which changes from concurrent transactions a transaction is allowed to see. Isolation bugs rarely appear in unit tests, because unit tests run one request at a time. They appear under load, when two requests interleave in the milliseconds between a SELECT and an UPDATE. These are our team's notes on what each PostgreSQL level guarantees, which tool we pick for which invariant, and how we write the retry loop in Node.js with node-postgres, Prisma, and Drizzle.
Key takeaways
• Default level: PostgreSQL's default isolation level is READ COMMITTED, where each statement sees a fresh snapshot taken when that statement starts.
• No dirty reads: PostgreSQL treats READ UNCOMMITTED as READ COMMITTED, so a transaction never sees uncommitted data at any level.
• REPEATABLE READ does not stop write skew: PostgreSQL's REPEATABLE READ uses one snapshot per transaction and blocks phantom reads, but two transactions that read overlapping data and write different rows can both commit.
• SERIALIZABLE aborts instead of blocking: PostgreSQL's Serializable Snapshot Isolation, available since PostgreSQL 9.1, fails one conflicting transaction with SQLSTATE 40001, and the application must retry the whole transaction.
• Retries must be whole and side-effect free: re-run every read, cap attempts, add jittered backoff, and keep emails, HTTP calls, and queue publishes out of the transaction body.
What does each PostgreSQL isolation level actually guarantee?
Each PostgreSQL isolation level differs in when the snapshot is taken and in what happens when two transactions collide. The SQL standard defines four levels; PostgreSQL implements three distinct behaviors.
• READ COMMITTED (default): the snapshot is taken at the start of each statement. It still allows non-repeatable reads, phantoms, lost updates from read-modify-write in application code, and write skew. A second writer waits for the row lock, then re-checks its WHERE clause against the newly committed row.
• REPEATABLE READ: the snapshot is taken at the first query of the transaction. It still allows write skew. Updating a row changed since the snapshot fails with 40001, "could not serialize access due to concurrent update".
• SERIALIZABLE: the snapshot is taken at the first query, plus predicate-read tracking. It allows no anomalies among transactions that all run at SERIALIZABLE. A dangerous read/write dependency fails one transaction with 40001, "could not serialize access due to read/write dependencies among transactions".
Which concurrency bug does READ COMMITTED let through?
Write skew is the anomaly where two transactions read the same data, each makes a decision that is valid on its own, and each writes a different row, so no row lock ever conflicts. The example we use internally is a rule that every team keeps at least one owner.
The handler opens a transaction, counts the team's owners with SELECT count(*) FROM members WHERE team_id = $1 AND role = 'owner', rejects the request if fewer than two owners exist, and otherwise demotes the requesting member with an UPDATE.
When two owners demote themselves at the same moment, both transactions count two owners, both pass the check, and each updates its own row. Both commit, and the team has zero owners. REPEATABLE READ does not help, because the two transactions never write the same row.
The simpler cousin is the lost update: application code reads a balance, computes a new value in JavaScript, and writes it back. Two concurrent requests both read 100, both write 90, and one withdrawal disappears.
Do we need SERIALIZABLE, or will a constraint, a single statement, or a lock do?
We reach for SERIALIZABLE last, because cheaper tools fix most invariants at READ COMMITTED without any retry logic. Our order of preference:
• A schema constraint: a UNIQUE index, a CHECK constraint, or an exclusion constraint holds at every isolation level. "No overlapping bookings for one room" is an EXCLUDE USING gist (room_id WITH =, during WITH &&) constraint with the btree_gist extension, not application code.
• One atomic statement: UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1 RETURNING balance is safe at READ COMMITTED, because a concurrent second UPDATE waits for the row lock and then re-evaluates the WHERE clause against the committed new balance.
• Lock the parent row: for the owner rule, SELECT 1 FROM teams WHERE id = $1 FOR UPDATE at the start of the transaction serializes every membership change for that team. Every code path that changes owners must take the same lock.
• SERIALIZABLE with retry: we use it when the invariant spans rows with no natural parent to lock, or when many code paths touch the same rule.
How do we run a SERIALIZABLE transaction from Node.js?
We set the isolation level per transaction, so the requirement sits next to the code that depends on it. With node-postgres, the level goes into the BEGIN statement: BEGIN ISOLATION LEVEL SERIALIZABLE. With Prisma interactive transactions, we pass isolationLevel: Prisma.TransactionIsolationLevel.Serializable as the second argument to prisma.$transaction(). With Drizzle on PostgreSQL, we pass isolationLevel: 'serializable' as the second argument to db.transaction().
A global default_transaction_isolation setting also works, but it hides the requirement in database configuration and changes the failure mode of every transaction in the application at once.
How should we retry SQLSTATE 40001 safely?
A serialization failure means PostgreSQL rolled back the transaction to keep its guarantee, and the only correct response is to run the entire transaction again, reads included. Our node-postgres wrapper checks out a client, runs BEGIN ISOLATION LEVEL SERIALIZABLE, calls the callback, and commits. On error it rolls back, reads the SQLSTATE from err.code or err.cause.code, and retries only on 40001 (serialization_failure) or 40P01 (deadlock_detected), up to five attempts with full-jitter exponential backoff.
• The callback must be safe to run more than once: every read happens inside it, so a retry sees fresh data.
• No side effects inside the transaction: an email or webhook sent from inside the callback fires once per attempt, so we write an outbox row and send after commit.
• Bounded attempts: after the last attempt the error propagates, and the API maps it to HTTP 409 or 503 instead of a generic 500.
• Prisma uses its own code: Prisma reports a serialization failure as a PrismaClientKnownRequestError with code P2034, so a Prisma wrapper checks for P2034 as well.
• COMMIT can fail too: under SERIALIZABLE, SQLSTATE 40001 can surface on the COMMIT statement, so the retry boundary must include the commit.
What does SERIALIZABLE cost in production?
SERIALIZABLE costs predicate-lock bookkeeping and some false-positive aborts, and both grow with transaction length and contention.
• Index the predicates: PostgreSQL's documentation notes that a sequential scan always takes a relation-level predicate lock, so any concurrent write to that table can trigger a conflict.
• Keep transactions short: no network calls, no user think-time, and no large batch loops inside a serializable transaction.
• Mark read-only work: BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE waits for a safe snapshot, then runs a long report with no risk of a serialization failure.
• Use it on every path that writes the rule: the SERIALIZABLE guarantee only covers transactions that also run at SERIALIZABLE.
• Count retries: a rising retry rate means one hot row needs an atomic UPDATE or a queue, not more attempts.
FAQ
Q: What is PostgreSQL's default transaction isolation level?
A: PostgreSQL's default is READ COMMITTED. Each statement sees data committed before that statement began. Change it per transaction with BEGIN ISOLATION LEVEL or globally with default_transaction_isolation.
Q: Does REPEATABLE READ in PostgreSQL prevent phantom reads?
A: Yes. PostgreSQL's REPEATABLE READ uses one snapshot for the whole transaction, which is stricter than the SQL standard requires. It still allows write skew.
Q: What does SQLSTATE 40001 mean in PostgreSQL?
A: SQLSTATE 40001 is serialization_failure: PostgreSQL aborted the transaction because committing it would break the isolation guarantee. Roll back and run the entire transaction again from the start.
Q: Is SERIALIZABLE too slow for a web API?
A: It depends on contention. Short, well-indexed SERIALIZABLE transactions with a bounded retry suit most write paths; a single hot row updated by every request is better served by an atomic UPDATE.
Q: Should we use SELECT FOR UPDATE or SERIALIZABLE?
A: Use SELECT ... FOR UPDATE when there is one obvious row to lock and every writer takes that lock. Use SERIALIZABLE when the invariant spans rows with no natural lock target.
Further Reading
Backend Engineering
Postgres LISTEN/NOTIFY in Node.js and NestJS: How We Invalidate Caches Across Replicas Without Losing Notifications on Reconnect
PostgreSQL LISTEN/NOTIFY gives Node.js apps a transactional, zero-infrastructure signal that fires only when a write commits. Here is how we use it to invalidate in-memory caches across NestJS replicas: a trigger that calls pg_notify, a dedicated listener connection that survives reconnects, and the limits that tell us when to switch to Redis or CDC.
Backend Engineering
JSONB in Postgres from Node.js: How We Index It with GIN, jsonb_path_ops, and Expression Indexes — Field Notes
A GIN index on a jsonb column only serves containment and key-existence operators, so a ->> equality filter quietly scans the table. Here is how our team decides what goes into jsonb, picks between jsonb_ops and jsonb_path_ops, uses expression indexes and STORED generated columns, and handles what node-postgres does to JSON arrays and large numbers.