Currently Available: Need a skilled Software Developer for your next project?
Categories
Databases PostgreSQL

PostgreSQL Transaction Isolation vs. Explicit Row Locking

When a web request reads data from PostgreSQL and then changes it, another request can modify the same rows in between. PostgreSQL gives you two related controls for this. Transaction isolation sets what data a transaction sees and which concurrent outcomes PostgreSQL allows to commit. Row locks make other transactions wait before they change specific rows.

PostgreSQL uses multiversion concurrency control (MVCC), so readers and writers can work with different versions of the same row. A snapshot is the view of committed data visible to a statement or transaction. You use isolation to control that view and the outcomes PostgreSQL permits, and you use a row lock to protect selected rows from conflicting changes while a transaction holds it.

Which tool you pick depends on the rule your code must preserve. Run a conditional UPDATE when one statement can express the rule. Run SELECT ... FOR UPDATE when your code must inspect a row and then act on it before another transaction changes it. When a rule spans a broader set of data, add a database constraint or run the transaction under SERIALIZABLE isolation, and write your application to retry transactions that PostgreSQL aborts. PostgreSQL’s transaction isolation rules spell out what each level guarantees.

Isolation controls visibility and allowed outcomes

PostgreSQL defaults to READ COMMITTED. A transaction groups statements so they commit or roll back together, and at this level each statement gets its own snapshot. Because each statement sees data committed before that statement began, two statements inside the same transaction can see different committed data.

Isolation level What PostgreSQL provides What to keep in mind
READ UNCOMMITTED Behaves like READ COMMITTED. PostgreSQL does not offer a separate behavior at this level.
READ COMMITTED Gives each statement its own snapshot. Concurrent commits can change what a later statement sees.
REPEATABLE READ Uses one stable snapshot for the whole transaction. PostgreSQL also prevents phantom reads at this level. Some serialization anomalies can still happen.
SERIALIZABLE Ensures committed transactions produce results consistent with some serial order. PostgreSQL aborts transactions that violate this guarantee, so your application must retry them.

A serialization anomaly happens when concurrent transactions commit results that you could not get by running those transactions one at a time in any order. REPEATABLE READ stops a transaction's snapshot from shifting mid-transaction, though it still allows some of these anomalies. SERIALIZABLE gives you the stronger guarantee for every transaction that commits, but you have to handle the aborts PostgreSQL raises when transactions conflict. These rules are specific to PostgreSQL; other databases often implement the same isolation-level names differently. The PostgreSQL isolation documentation covers the full details.

Under READ COMMITTED, when two transactions try to update the same row at the same time, PostgreSQL waits for the first transaction to finish. If that first transaction commits, PostgreSQL rechecks the WHERE condition against the updated row before applying the second update. That behavior makes targeted conditional updates reliable, though separate statements in the same transaction can still read different snapshots.

Updates already lock the rows they change

PostgreSQL automatically locks rows whenever an UPDATE or DELETE changes them. Another writer or a locking read (SELECT ... FOR UPDATE) targeting the same row waits until the transaction holding the lock finishes. Ordinary SELECT queries do not wait for row locks.

When your code needs to read a row before deciding how to change it, an explicit locking read holds that row against conflicting changes while your code runs. For example, if your application checks a payment's current state before approving it, you can lock that payment row first:

BEGIN;

SELECT status, amount
FROM payments
WHERE id = $1
FOR UPDATE;

-- Check the returned values and decide what to do.
UPDATE payments
SET status = 'approved'
WHERE id = $1;

COMMIT;

FOR UPDATE locks the selected row against conflicting changes until the transaction ends. It does not lock rows the query did not return, and it does not refresh a transaction-wide snapshot. Under READ COMMITTED, a locking read waits for a concurrent update to finish and then returns the updated row. Under REPEATABLE READ or SERIALIZABLE, if another transaction has already changed that row since your transaction's snapshot began, PostgreSQL raises a serialization error instead. You can check the details in PostgreSQL's documentation on explicit row locking.

Lock only the rows your decision depends on, and finish the transaction quickly so conflicting writers do not sit waiting. When your code locks multiple rows, lock them in the same order every time to reduce the chance of deadlocks. PostgreSQL detects deadlocks and aborts one of the transactions involved, so your application needs to handle that failure instead of assuming which transaction PostgreSQL will pick.

Use one conditional update for a simple rule

When a rule applies to a single row and fits inside a WHERE clause, a conditional update often lets you skip the separate read, decision, and write. For inventory, the rule to decrement stock only when at least one item remains fits in one statement:

UPDATE products
SET stock = stock - 1
WHERE id = $1
  AND stock > 0
RETURNING stock;

Your application treats a returned row as a successful purchase. If the query returns nothing, the item is out of stock. If another request updates the same product first, PostgreSQL waits for that transaction and then checks stock > 0 against the updated row.

You can use the same pattern for a state transition:

UPDATE payments
SET status = 'approved'
WHERE id = $1
  AND status = 'pending'
RETURNING id;

PostgreSQL checks the condition and updates the payment in one step, so the change goes through only if the payment is still pending when PostgreSQL processes it. Reach for a locking read when your application code has to inspect values and make a decision that does not fit cleanly into the UPDATE itself. For more on how isolation choices affect application code, see transaction isolation levels in practice.

A row lock does not lock a whole search condition

A locking query protects only the rows it actually returns. On its own, it cannot stop another transaction from inserting a new row that also matches the query. That gap matters when a business rule applies to a whole set of rows, such as preventing overlapping bookings for the same resource.

When PostgreSQL can enforce an invariant directly, use a constraint. PostgreSQL offers constraints such as UNIQUE and EXCLUDE for rules across rows, whereas a CHECK constraint that looks up other rows in a table will not reliably enforce a cross-row rule. See the PostgreSQL constraints documentation for what each constraint covers.

If no constraint can enforce your rule across the rows your code reads and modifies, you can run the transaction under SERIALIZABLE isolation. PostgreSQL tracks dependencies between transactions using predicate locks to catch unsafe concurrent outcomes. Unlike explicit row locks, predicate locks do not block conflicting writes; instead, PostgreSQL lets them run and aborts a transaction if committing it would break serializability. You can also protect a broader rule with a locking protocol of your own, as long as every code path that touches the relevant data follows the same protocol.

Use SKIP LOCKED for competing queue workers

If you store jobs in a queue-like table, workers can claim rows while skipping any rows another worker has already locked. PostgreSQL documents SKIP LOCKED as a good fit for multiple consumers, while warning that it returns an inconsistent view and should not be used for general-purpose queries. One statement can both pick and claim a batch of jobs:

WITH picked AS (
    SELECT id
    FROM jobs
    WHERE status = 'ready'
    ORDER BY created_at, id
    FOR UPDATE SKIP LOCKED
    LIMIT 10
)
UPDATE jobs AS j
SET status = 'claimed'
FROM picked
WHERE j.id = picked.id
RETURNING j.id;

Commit the claim before the worker does slow work outside the database. When the worker commits, PostgreSQL releases the row locks right away, so other database requests do not sit waiting while the worker makes a network call or runs a long task. The SELECT locking clauses documentation explains SKIP LOCKED and which rows each clause locks.

Retry the whole transaction when PostgreSQL aborts it

Transactions running at REPEATABLE READ or SERIALIZABLE can fail when concurrent changes conflict with their snapshot or with serializable execution. PostgreSQL reports serialization failures with SQLSTATE 40001, and deadlocks also cause PostgreSQL to abort a transaction. When either happens, your application must retry the whole transaction, because the earlier statements ran against a state that never committed.

Keep external side effects out of the retried transaction, or design them so a retry cannot run them twice. For example, do not call a payment provider and assume the database transaction will commit afterward. For more on this failure mode, see why serializable transactions still need retries.

Choose the mechanism that matches the invariant

Start by writing down the exact rule your code has to protect. If one conditional UPDATE or DELETE can enforce it, use that statement. If your code must inspect an existing row and act on its values, lock that row for the short transaction that makes the decision. If the rule spans multiple rows or depends on which rows match a condition, add a suitable constraint, or run under SERIALIZABLE isolation and retry aborted transactions from the start.

You can combine isolation and explicit locks, because they handle different parts of concurrency control. Isolation governs what each transaction sees and which concurrent outcomes PostgreSQL allows to commit. Row locks control access to specific rows. Either way, you still have to identify the invariant your code needs to preserve.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *