DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on Originally published at sreekarreddy.com

🤞 Optimistic Locking Explained Like You're 5

Assume no conflict, check before saving

Day 150 of 155

👉 Full deep-dive with code examples


Two Waiters, One Ticket

Two waiters grab the same order ticket off the rail.

  • Waiter A writes "no onions"
  • Waiter B writes "extra cheese"
  • Waiter B pins his copy back last

Waiter A's note is gone, and nobody noticed 😱

That is the lost update problem.


The Same Thing in a Database

Alice reads row 42: note="", version=7
Bob   reads row 42: note="", version=7

Alice saves note="no onions"    -> row says "no onions"
Bob   saves note="extra cheese" -> row says "extra cheese"
Enter fullscreen mode Exit fullscreen mode

Alice's edit vanished. The database did nothing wrong: it applied both writes in arrival order.


Attach a Version Marker

Optimistic locking assumes collisions are rare, so it locks nothing up front and checks at save time instead.

Keep a version column on the row, and send back the version you read:

UPDATE orders
SET note = 'extra cheese', version = version + 1
WHERE id = 42 AND version = 7;
Enter fullscreen mode Exit fullscreen mode

If Alice saved first, the row is on version 8, the WHERE matches nothing, and zero rows are affected.

That zero tells Bob he lost the race.

On stricter isolation levels some engines raise a serialization error instead, so production code handles both.

The check and the write are one statement, so nothing can slip in between them.


What You Do On Conflict

Zero rows is information, not a crash. Pick a response:

  • Retry: refetch, reapply your change, save again
  • Merge: combine edits that touch different fields
  • Ask: tell the user "this record changed while you were editing"

Web APIs use the same trick with the HTTP ETag and If-Match headers.


In One Sentence

Optimistic locking lets everyone edit freely, then rejects any save whose version marker no longer matches the row.


🔗 Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)