PostgreSQL Lost Updates: Isolation, Row Locks and Versions
Diagnose stale read-modify-write updates in PostgreSQL. Compare atomic UPDATE, FOR UPDATE, version checks and transaction retries with a two-session walkthrough.
A transaction can still overwrite a value computed from an earlier read. Match the protection to the operation: use atomic UPDATE expressions for current-state changes, row locks for read-dependent decisions, or version conditions for stale-edit detection. Higher isolation may reject conflicts and require a complete transaction retry.
A successful transaction can still write a stale decision
Two requests read an inventory quantity of 100. One reserves 10 units and writes 90. The other reserves 20 units and writes 80. Both transactions commit, yet the final quantity is 80 instead of 70. The second request saved a value calculated from an old observation. Putting each request inside BEGIN and COMMIT does not, by itself, make that application calculation current.
This is a useful concrete form of a lost update: the database executes both writes, but one business change disappears from the stored result. Diagnose the read, the calculation and the write together. A query plan or an index may make the operation faster without correcting the concurrency rule.
The examples below target PostgreSQL behavior described in its official concurrency documentation. They are a two-session learning procedure for a disposable database. PostgreSQL was not installed in the authoring environment, so the SQL and expected concurrency outcomes were reviewed against documentation rather than executed. No production database or performance test was used.
Prepare one disposable table and two independent sessions
Connect two psql sessions to the same disposable database, with an account permitted to create a table in the intended schema. Run the setup below once. The deliberately specific table name avoids suggesting a production inventory table; if it already exists, inspect that environment rather than automatically dropping it.
Keep autocommit enabled outside explicit transaction blocks. Execute the schedule one row at a time in the named session. Do not paste the whole schedule into one connection: that would remove the overlap the demonstration is intended to explain. After a test, end every open transaction before resetting the row.
Check the server version and isolation configuration in the sessions you are actually using. The example explicitly requests Read Committed for its first schedule instead of relying on a connection pool’s defaults. A separate tab in a database interface is useful only if it really owns a separate database connection.
CREATE TABLE pwp_inventory_isolation_demo (
id integer PRIMARY KEY,
quantity integer NOT NULL CHECK (quantity >= 0),
version bigint NOT NULL DEFAULT 0
);
INSERT INTO pwp_inventory_isolation_demo (id, quantity) VALUES (1, 100);
SHOW server_version;
SHOW transaction_isolation;Follow the stale-value schedule exactly
At Read Committed, an ordinary SELECT uses a statement-level snapshot of committed data. That protects against dirty reads, but it does not reserve the selected row for a later application calculation. In this schedule both reads occur before either write. Session B’s later assignment is still the literal 80, even though A has committed 90.
The expected final quantity is 80. The CHECK constraint remains satisfied: both 90 and 80 are nonnegative. A constraint can protect a stated invariant while failing to capture a different business requirement, such as preserving both reservations.
After step 8, run SELECT quantity FROM pwp_inventory_isolation_demo WHERE id = 1 in either session. For the next experiment, reset with UPDATE pwp_inventory_isolation_demo SET quantity = 100, version = 0 WHERE id = 1, only after both sessions are outside transactions.
| Step | Session | Statement / observation |
|---|---|---|
| 1 | A | BEGIN ISOLATION LEVEL READ COMMITTED; |
| 2 | A | SELECT quantity FROM pwp_inventory_isolation_demo WHERE id = 1; — reads 100 |
| 3 | B | BEGIN ISOLATION LEVEL READ COMMITTED; |
| 4 | B | SELECT quantity FROM pwp_inventory_isolation_demo WHERE id = 1; — reads 100 |
| 5 | A | UPDATE pwp_inventory_isolation_demo SET quantity = 90 WHERE id = 1; |
| 6 | A | COMMIT; |
| 7 | B | UPDATE pwp_inventory_isolation_demo SET quantity = 80 WHERE id = 1; |
| 8 | B | COMMIT; |
Express a single-row change as an atomic update
If the operation is “reserve 20 from the current quantity,” express that operation in SQL instead of reading a number and later saving a replacement. The statement below combines the availability condition and decrement. RETURNING supplies the row actually changed; a client must distinguish one returned row from zero returned rows.
Run equivalent statements for reservations of 10 and 20 from the reset quantity of 100. At Read Committed, conflicting row updates coordinate through PostgreSQL’s update behavior. When a matching row has been updated concurrently, the waiting updater evaluates the condition against the updated version. In this simple case both reservations can succeed and the expected result is 70.
Zero rows can mean that the condition no longer holds or that the target does not exist; define the application response. Also validate that the reservation parameter is a positive, bounded integer. This atomic expression prevents this stale-assignment pattern, but repeating the same business request can still reserve twice. Request identity and idempotency are separate concerns.
BEGIN ISOLATION LEVEL READ COMMITTED;
UPDATE pwp_inventory_isolation_demo
SET quantity = quantity - 20,
version = version + 1
WHERE id = 1 AND quantity >= 20
RETURNING id, quantity, version;
COMMIT;
-- In application code, bind and validate the requested amount.
-- Do not use a prior SELECT result as a replacement quantity.Lock before making a decision that needs a read
Some decisions require several fields or additional application logic. In that case SELECT ... FOR UPDATE can lock the existing row before the decision is calculated. Keep the lock and the subsequent write inside the same transaction; a lock acquired and immediately released by autocommit does not protect a later separate transaction.
From the reset state, let A begin at Read Committed and select the row FOR UPDATE. Have B begin and issue the same locking SELECT before A commits. B should wait for the conflicting row lock. Let A write 90 and commit. B’s locking read can then return the updated quantity, from which its application computes 70 before writing and committing.
This protects the selected existing row, not every possible row matching a future business condition. It is not a general lock on an absence or on an aggregate invariant. Keep transactions short, acquire multiple locks in a consistent order, and avoid holding them while waiting for user interaction or a remote API.
BEGIN ISOLATION LEVEL READ COMMITTED;
SELECT id, quantity, version
FROM pwp_inventory_isolation_demo
WHERE id = 1
FOR UPDATE;
-- Compute from the locked value returned above.
-- Apply the intended change before COMMIT, on this same connection.
-- Use ROLLBACK if the business operation is not allowed.
ROLLBACK;Use a version condition to detect a stale edit
An optimistic approach is useful when a user edits a record over time and you should not hold a database lock during that interaction. Return the current version with the record. Require that version in the later UPDATE, and increment it whenever a cooperating writer changes the row.
If both clients read version 0, the first conditional update can change it to 1. The second UPDATE with WHERE version = 0 affects zero rows. Treat that as a conflict requiring an application decision, rather than reporting success or removing the condition to force the stale value through.
This is a cooperative protocol: every relevant writer must maintain the version consistently. A manual update that changes the quantity without incrementing the version can defeat the intended check. A version conflict also does not automatically tell you whether to merge, refresh or ask the user to review the newer value.
-- Example: the client originally read quantity 100 and version 0.
UPDATE pwp_inventory_isolation_demo
SET quantity = 90, version = version + 1
WHERE id = 1 AND version = 0
RETURNING quantity, version;
-- A stale second edit with version = 0 must check for zero rows.
-- Bind values in application code; this is a fixed teaching fixture.What changes at Repeatable Read and Serializable?
Repeatable Read gives a transaction a stable snapshot for ordinary reads, established by its first non-transaction-control statement. It does not mean every possible business invariant is enforced. PostgreSQL can reject an attempt to update a row changed since that snapshot with a serialization failure instead of accepting a stale write.
To compare, reset the row and repeat the earlier stale-value schedule with both BEGIN statements set to REPEATABLE READ. Make sure B reads 100 before A updates and commits. B’s later attempt to update that row is expected to fail with SQLSTATE 40001. Roll back B and retry its entire business transaction using a fresh observation.
Serializable goes further by ensuring successfully committed transactions have an effect consistent with some serial ordering. It may also require transaction retries. It does not mean all concurrency becomes a simple queue of blocking transactions, and it does not make application side effects outside the database transactional.
Retry the whole transaction, not the final statement
PostgreSQL’s serialization-failure guidance identifies SQLSTATE 40001 and requires retrying the complete transaction, including the logic that selected values and decided which SQL to run. Reissuing only the failed UPDATE with the same stale application value can preserve the very mistake the retry should resolve.
Use the database driver’s transaction boundary deliberately: on the selected retryable error, roll back, apply a bounded retry policy, begin again and recompute from new reads. Include backoff where appropriate and surface exhaustion clearly. Do not treat every constraint failure or every database error as transient.
If a transaction also sends an email, charges a payment method or calls another service, a database retry can repeat that external action. Keep irreversible effects outside the retried decision where possible and use a durable outbox or other recoverable idempotent workflow. A network failure near COMMIT also requires distinguishing a known rollback from an unknown commit outcome.
Choose the mechanism that matches the invariant
For a single-row increment or decrement, an atomic expression plus a condition is often the smallest clear solution. For a read-dependent decision on an existing row, an explicit row lock can make the critical section visible. For a long-lived user edit, a version condition can expose stale state without keeping a transaction open.
For an invariant spanning several rows, write down the allowed states and examine all concurrent writers. Adding FOR UPDATE to one convenient row may not protect that invariant. Appropriate constraints, a deliberately shared lock target, or Serializable transactions can be relevant, depending on the design. Validate the chosen mechanism under the actual access pattern.
Do not compare these approaches only by whether the happy-path example commits. Compare what waits, what fails, what the caller must retry or reject, and what happens after a process crash. The mechanism is only complete when the application handles those outcomes.
| Need | Candidate | Caller responsibility |
|---|---|---|
| Change one current row value | Atomic UPDATE with condition | Validate input and inspect affected/returned rows |
| Read then decide while excluding conflicting writers | SELECT FOR UPDATE in one transaction | Keep lock scope and duration controlled |
| Detect a stale user edit | Version-conditioned UPDATE | Handle conflict and maintain version on all writes |
| Enforce broader transaction consistency | Serializable where appropriate | Retry complete transactions and manage external effects |
Record the schedule and the evidence
A useful concurrency test controls ordering explicitly: record when each read occurs, which statement holds a lock and when each transaction commits. Arbitrary sleeps can make a test flaky and can accidentally remove the overlap. In an automated harness, coordinate sessions with explicit barriers and place time bounds on expected waits.
Capture SQLSTATE values, returned row counts and the final row state. Also test a zero-row conditional update, a stale version, an aborted transaction and a retry that must recompute its decision. Use isolated fixtures and clean up only objects created for that test.
The expected outcomes in this article are documentation-derived. No local PostgreSQL concurrency run was performed. Before adopting a pattern, execute it against your PostgreSQL version, driver and connection-pool configuration. SQLite or an in-memory imitation would not establish PostgreSQL’s locking or isolation behavior.
Make the decision and the write agree
The durable fix is to align the business decision with the database operation that protects it. An explicit transaction is a starting boundary; it is not proof that a value calculated earlier remains valid. Preserve current-state arithmetic in SQL, lock before the necessary read, or detect stale versions deliberately.
Use the related query-plan guide when the correct transaction is slow, the pagination guide when reads need stable ordering, and the webhook guide when repeated deliveries can duplicate a business request. Keeping correctness, performance and request identity distinct makes each test and each repair easier to interpret.
Your next steps
- BEGIN and COMMIT alone do not make a stale application calculation current.
- Check returned rows and handle lock waits, stale versions and serialization errors explicitly.
- Test real concurrent sessions and retry the whole decision under the chosen isolation level.
Sources & official resources
Linked resources checked on 2026-10-26. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →