science Concurrency Lab
Select a model to simulate multi-user behavior
Shared Database
Optimistic Locking
"Ask forgiveness, not permission."
Assume conflicts are rare. Allow multiple users to read and edit data without locking. Check for conflicts only when saving.
How it works
- check_circle Read data along with a version number (e.g., v1).
- check_circle Modify data locally.
-
warning
On save, database checks:
IF current_ver == read_ver. - error If versions differ, the update fails and user must retry.
Low contention systems, read-heavy apps, web applications (REST APIs), Wiki edits.
Pessimistic Locking
"Better safe than sorry."
Assume conflicts are likely. Lock the record as soon as a user wants to read/edit it. Block others until finished.
How it works
-
lock
User acquires a lock (e.g.,
SELECT FOR UPDATE). - check_circle Other users trying to lock must wait (queue).
- edit User processes and updates data safely.
- lock_open Lock is released, allowing next user to proceed.
High contention, strict data integrity (finance), inventory systems preventing overselling.
Key Differences at a Glance
| Feature | Optimistic | Pessimistic |
|---|---|---|
| Performance | High throughput (no waiting) | Can bottleneck (queuing for locks) |
| Conflict Cost | High (Must retry entire operation) | Low (Conflicts prevented upfront) |
| Deadlocks | Impossible (no locks held) | Possible (careful management needed) |
| User Experience | Fast, but occasional "Please try again" errors | Slower, but guaranteed success once started |