When would you choose optimistic versus pessimistic locking for a high-concurrency web application?
Last updated
Optimistic locking holds no lock: it checks a version at write time (
UPDATE ... WHERE version = ?) and retries if 0 rows change. Use it when conflicts are rare, the usual web-app default.Pessimistic locking grabs a lock up front (
SELECT ... FOR UPDATE). Use it when conflicts are frequent or retries are costly, but it reduces concurrency and risks deadlocks.Decide by conflict probability and retry cost, and never hold DB locks across user think-time.