Menu

1 / 5

Optimistic vs Pessimistic Locking: Stopping Lost Updates

DEV Community: backend·Abdeldjalil Chougui·about 6 hours ago
#3ivuNqBs
#devtobackend#devto#dev#version#locking
Long article (1187 words) — no AI summary yet.
Reading 0:00
15s threshold

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

Enter fullscreen mode

Exit fullscreen mode

If two requests run steps 1 to 3 at the same time, both read 100, both write 70, and one withdrawal disappears.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.