Two support agents open the same customer record at the same time. Agent A changes the phone number and saves. A few seconds later, agent B, who still has the old version on screen, changes the address and saves. B's save writes the whole record, including the old phone number. A's change is gone, and nobody got an error.

This is the lost update problem. It appears whenever a program reads data, changes it in memory, and writes it back, while someone else does the same. Databases offer two families of solutions: pessimistic locking and optimistic locking.

The problem in code

Here is the read-modify-write pattern that causes it:

1. read balance of account 7 → 100 2. compute new balance in code → 100 - 30 = 70 3. write balance = 70 

If two requests run steps 1 to 3 at the same time, both read 100, both write 70, and one withdrawal disappears. The account should be at 40.

Note that a single SQL statement such as UPDATE accounts SET balance = balance - 30 WHERE id = 7 does not have this problem: the database reads and writes the row atomically, and a concurrent update waits for the first one to finish. When you can express the change as one statement, do that first. Locking strategies matter when the logic must run in application code between the read and the write.

Pessimistic locking: lock first, then work

Pessimistic locking assumes conflicts are likely, so it prevents them. You lock the row when you read it, and anyone else who wants to change it must wait until you commit.

In SQL this is SELECT ... FOR UPDATE:

BEGIN; SELECT balance FROM accounts WHERE id = 7 FOR UPDATE; -- row is now locked -- application checks the balance and computes the new value UPDATE accounts SET balance = 70 WHERE id = 7; COMMIT; -- lock released 

Step by step with two requests:

  1. Request A runs SELECT ... FOR UPDATE and gets the lock. It reads 100.
  2. Request B runs the same SELECT ... FOR UPDATE and blocks.
  3. A writes 70 and commits. The lock is released.
  4. B's select now returns, and it reads 70, not 100. It writes 40.

Correct result, at the cost of B waiting.

Strengths: simple to reason about; conflicts never reach the user; good when the same rows are contended often, such as seat booking or stock counters during a sale.

Costs:

  • Waiting. Other transactions block while you hold the lock, so the lock must be short.
  • Deadlocks. If two transactions lock rows in different orders, each waits for the other. The database detects this and aborts one of them.
  • It only works inside one database transaction. You cannot hold a row lock while a user stares at an edit form for five minutes.

Variants help in specific cases: FOR UPDATE NOWAIT fails immediately instead of waiting, and FOR UPDATE SKIP LOCKED skips rows locked by others, which is a common way to build job queues on top of a table.

Optimistic locking: work freely, check at save time

Optimistic locking assumes conflicts are rare. Nobody locks anything during the read. Instead, each row carries a version (an integer, or sometimes an update timestamp), and the write checks that the version has not changed since you read it.

-- read SELECT id, phone, address, version FROM customers WHERE id = 7; -- returns version = 4 -- write, only if nobody changed it meanwhile UPDATE customers SET address = 'New address', version = version + 1 WHERE id = 7 AND version = 4; 

The application then checks how many rows were updated:

  • 1 row: success. The version is now 5.
  • 0 rows: someone else saved first and the version is no longer 4. This is a conflict.

Back to the two agents:

  1. A and B both load the customer with version 4.
  2. A saves first. The update matches version = 4, writes, and sets version 5.
  3. B saves. The update looks for version = 4, finds version 5, and updates 0 rows.
  4. The application tells B: "This record was changed by someone else. Reload and apply your change again."

No change is lost silently.

Many frameworks support this directly. JPA and Hibernate have @Version, Entity Framework has concurrency tokens, and Rails has a lock_version column. HTTP APIs use the same idea with ETag and If-Match headers, returning 412 Precondition Failed on a mismatch.

Strengths: no locks held, no waiting, no deadlocks from this pattern; works across long user sessions and across requests, which is exactly the "edit form" case pessimistic locking cannot handle.

Costs:

  • Conflicts surface as errors you must handle: retry automatically, or ask the user to merge.
  • Under heavy contention, many attempts fail and retry, which wastes work. If ten requests fight over the same row every second, most of them will lose.

Choosing between them

Pessimistic Optimistic
Assumes conflicts are Likely Rare
Mechanism Row lock (FOR UPDATE) Version check on write
On conflict Second writer waits Second writer gets an error
Spans user think time No Yes
Deadlock risk Yes No (from this pattern)
Best for Hot rows, short transactions Forms, APIs, low contention

A practical rule:

  • If the conflict window is inside one short transaction and the same rows are busy, use pessimistic locking.
  • If the read and the write are separated by user think time or by separate HTTP requests, use optimistic locking.
  • If the change fits in one atomic UPDATE ... SET x = x - 1 WHERE ... AND x >= 1, you may need neither.

Common mistakes

  • Read-modify-write with no protection at all, assuming traffic is low. It works in testing and loses data in production.
  • Holding a pessimistic lock across slow work, such as an external API call or an email send. Every other request on that row waits.
  • Forgetting to check the affected row count in optimistic locking. Without the check, the version column does nothing.
  • Using a timestamp with low precision as the version. Two updates in the same millisecond can pass the check. An integer counter is safer.
  • Retrying forever on optimistic conflicts. Cap the retries and report the failure.
  • Locking rows in random order in pessimistic code. Always lock in a consistent order (for example by ID) to avoid deadlocks.

Watch the animated version: https://youtu.be/HgGuQpHeitQ

In short

  • Lost updates happen when two writers read, change and save the same data concurrently.
  • Pessimistic locking locks the row on read (SELECT ... FOR UPDATE) so others wait. Good for hot rows in short transactions.
  • Optimistic locking checks a version on write and fails if it changed. Good for forms, APIs and low contention.
  • Prefer a single atomic statement when you can; pick the locking style by how likely conflicts are and how long the gap is between read and write.

Originally published at abdeldjalilchougui.biz.