When would you use optimistic locking versus pessimistic locking?
BackendMid-level
In shortOptimistic locking checks a version column at update time and fails on conflict, which suits mostly-read data with rare conflicts. Pessimistic locking takes a database lock while reading, which suits short, high-contention updates where retrying is expensive.
Model answer
The problem: two requests read the same row, both change it, and the second write silently overwrites the first (a lost update).
Optimistic locking: add a @Version column. Every update runs update … set …, version = version + 1 where id = ? and version = ?. If another transaction changed the row first, zero rows match and JPA throws OptimisticLockException. Then retry the whole operation (re-read, re-apply) or return 409 Conflict so the user can reload. No locks are held while the user edits, so it scales well when conflicts are rare: editing profiles, documents, admin data. It also works across requests: send the version to the client and back.
Pessimistic locking: @Lock(PESSIMISTIC_WRITE) issues SELECT … FOR UPDATE, so other writers wait until the transaction ends. It suits short transactions with real contention where retries would be costly: decrementing stock for a flash sale, assigning the next seat. Keep the transaction tiny, set a lock timeout, and lock rows in a consistent order to avoid deadlocks.
Often better than both: a single atomic statement, update stock set quantity = quantity - 1 where sku = ? and quantity > 0, checking the affected row count. Or a unique constraint that makes the database reject duplicates.
What they're looking for
How each works (version column vs SELECT FOR UPDATE), the trade-offs, how conflicts are handled (retry or report), deadlock and lock timeout awareness, and alternatives like atomic updates.
Common mistakes
- Using no locking and getting lost updates.
- Holding pessimistic locks across user think time or remote calls.
- Catching OptimisticLockException and silently ignoring it.
More backend questions
- What is the N+1 query problem, and how do you find and fix it?Mid-level
- What does Spring Boot's auto-configuration do, and how do you change what it set up?Mid-level
- How does a Spring backend authenticate requests from a mobile app, and how do you make sure users only see their own data?Mid-level
- Your Spring Boot service in Kubernetes keeps restarting with exit code 137. How do you investigate and fix it?Senior