๐Ž๐ฉ๐ญ๐ข๐ฆ๐ข๐ฌ๐ญ๐ข๐œ ๐ฏ๐ฌ ๐๐ž๐ฌ๐ฌ๐ข๐ฆ๐ข๐ฌ๐ญ๐ข๐œ ๐‹๐จ๐œ๐ค๐ข๐ง๐ , ๐ข๐ง ๐ƒ๐š๐ญ๐š๐›๐š๐ฌ๐ž๐ฌ

Sankalp polSankalp pol
2 min read

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.

0
Subscribe to my newsletter

Read articles from Sankalp pol directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sankalp pol
Sankalp pol