Skip to main content

饾悗饾惄饾惌饾悽饾惁饾悽饾惉饾惌饾悽饾悳 饾惎饾惉 饾悘饾悶饾惉饾惉饾悽饾惁饾悽饾惉饾惌饾悽饾悳 饾悑饾惃饾悳饾悿饾悽饾惂饾悹, 饾悽饾惂 饾悆饾悮饾惌饾悮饾悰饾悮饾惉饾悶饾惉

Published 2 min readMarkdown

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.

No comments yet. Be the first to comment.

More from this blog