Optimistic vs Pessimistic Concurrency
Problem
Alice and Bob both want to change the same product row, currently priced at €10. Alice chooses €12 and Bob chooses €15. Their updates need coordination so one person's change is protected from an unnoticed overwrite.
Solution — Concurrency Strategies
Pessimistic: Alice's transaction locks the row before reading and changing it. Bob's transaction requests the same lock and waits. Alice saves €12 and commits, releasing the lock; Bob then reads €12 and can decide how to update it. The lock normally lasts for a short database transaction.
Optimistic: both read €10 at version 7 and edit independently. Alice saves €12 with the condition “version is still 7,” and the database advances it to 8. Bob's save of €15 with version 7 is rejected. He must reload and review the change before trying again; the version check and write happen atomically.
Core idea: pessimistic concurrency makes competing updates wait; optimistic concurrency rejects updates based on stale versions.