๐๐ฉ๐ญ๐ข๐ฆ๐ข๐ฌ๐ญ๐ข๐ ๐ฏ๐ฌ ๐๐๐ฌ๐ฌ๐ข๐ฆ๐ข๐ฌ๐ญ๐ข๐ ๐๐จ๐๐ค๐ข๐ง๐ , ๐ข๐ง ๐๐๐ญ๐๐๐๐ฌ๐๐ฌ

When building applications that deal with concurrent access to shared data, data consistency becomes a real challenge. Two popular approaches to handle this are Optimistic Locking and Pessimistic Locking. But they serve different purposes and come with trade-offs.
๐๐ฉ๐ญ๐ข๐ฆ๐ข๐ฌ๐ญ๐ข๐ ๐๐จ๐๐ค๐ข๐ง๐ :
๐๐ฌ๐ฌ๐ฎ๐ฆ๐ฉ๐ญ๐ข๐จ๐ง: Conflicts are rare.
๐๐ฉ๐ฉ๐ซ๐จ๐๐๐ก: Let everyone access the data, but verify before committing changes.
๐๐จ๐ฐ ๐ข๐ญ ๐ฐ๐จ๐ซ๐ค๐ฌ:
- A version field (e.g., version or updatedAt) is stored with the record.
- Before updating, the application checks whether the version matches.
- If not, the operation fails and must be retried.
For e.g. in SQL:
UPDATE orders SET status = 'shipped', version = version + 1 WHERE id = 101 AND version = 2;
Mongodb Example:
db.items.updateOne(
{ id: itemId, version: 3 },
{ $set: { name: "New Name" }, $inc: { version: 1 } }
)
If version has changed, the update fails indicating someone else modified it.
๐๐ก๐ข๐ฌ ๐ข๐ฌ ๐๐ฌ๐๐ ๐ข๐ง:
- High-read, low-write systems
- APIs with stateless communication
- Systems needing scalability over strict locking
๐๐๐ฌ๐ฌ๐ข๐ฆ๐ข๐ฌ๐ญ๐ข๐ ๐๐จ๐๐ค๐ข๐ง๐
๐๐ฌ๐ฌ๐ฎ๐ฆ๐ฉ๐ญ๐ข๐จ๐ง: Conflicts are likely.
๐๐จ๐ฐ ๐ข๐ญ ๐ฐ๐จ๐ซ๐ค๐ฌ:
- Lock the data to prevent others from modifying it until the lock is released.
- Other operations must wait or fail.
For e.g. in SQL
SELECT * FROM orders WHERE id = 101 FOR UPDATE;
MongoDB does not natively supports Pessimistic Locking but this can still be implemented with adding an additional lock field:
db.items.updateOne(
{ id: itemId, locked: false },
{ $set: { locked: true } }
)
Pessimistic Locks are needed in high concurrency systems such as BookMyShow or District where multiple people might attempt to book the same seat or spot.
Subscribe to my newsletter
Read articles from Sankalp pol directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
