# 𝐎𝐩𝐭𝐢𝐦𝐢𝐬𝐭𝐢𝐜 𝐯𝐬 𝐏𝐞𝐬𝐬𝐢𝐦𝐢𝐬𝐭𝐢𝐜 𝐋𝐨𝐜𝐤𝐢𝐧𝐠, 𝐢𝐧 𝐃𝐚𝐭𝐚𝐛𝐚𝐬𝐞𝐬

  
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:

```typescript
UPDATE orders SET status = 'shipped', version = version + 1 WHERE id = 101 AND version = 2;
```

Mongodb Example:

```typescript
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

```typescript
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:

```typescript
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.
