[Avg. reading time: 6 minutes]
Optimistic concurrency
Optimistic Concurrency is a concurrency control strategy used in databases and distributed systems that allows multiple users or processes to access the same data simultaneously—without locking resources.
Instead of preventing conflicts upfront by using locks, it assumes that conflicts are rare. If a conflict does occur, it’s detected after the operation, and appropriate resolution steps (like retries) are taken.
How It Works
- Multiple users/processes read and attempt to write to the same data.
- Instead of using locks, each update tracks the version or timestamp of the data.
- When writing, the system checks if the data has changed since it was read.
- If no conflict, the write proceeds.
- If conflict detected, the system throws an exception or prompts a retry.
Let’s look at a simple example:
Sample inventory
Table
| item_id | item_nm | stock |
|---------|---------|-------|
| 1 | Apple | 10 |
| 2 | Orange | 20 |
| 3 | Banana | 30 |
Imagine two users, UserA and UserB, trying to update the apple stock simultaneously.
User A’s update:
UPDATE inventory SET stock = stock + 5 WHERE item_id = 1;
User B’s update:
UPDATE inventory SET stock = stock - 3 WHERE item_id = 1;
- Both updates execute concurrently without locking the table.
- After both operations, system checks for version conflicts.
- If there’s no conflict, the changes are merged.
New price of Apple stock = 10 + 5 - 3 = 12
- If there was a conflicting update (e.g., both changed the same field from different base versions), one update would fail, and the user must retry the transaction.
Optimistic Concurrency Is Ideal When
Condition | Explanation |
---|---|
Low write contention | Most updates happen on different parts of data |
Read-heavy, write-light systems | Updates are infrequent or less overlapping |
High performance is critical | Avoiding locks reduces wait times |
Distributed systems | Locking is expensive and hard to coordinate |