Transactions and locking · Trade-off
Optimistic or pessimistic locking
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
When would you use optimistic locking with a version column, and when pessimistic locking with SELECT … FOR UPDATE? Give me one real example of each.
Then
Follow-ups the interviewer asks next
- What happens under optimistic locking when 1,000 people update the same row at once?
- What do NOWAIT and SKIP LOCKED do?
- Can you hold a FOR UPDATE lock while the user fills in a form?
- How do JPA's
@Versionand an HTTP ETag relate to this?
The answer
What a strong answer covers
- Optimistic: no lock while reading.
UPDATE … SET …, version = version + 1 WHERE id = ? AND version = ?; zero rows changed means someone else won, so retry or show "this was changed by someone else". Fits low contention and long think time, like an admin editing a product or a user editing a profile, even across HTTP requests. - Pessimistic:
SELECT … FOR UPDATEin a short transaction; others wait. Fits high contention on a few rows, where retries would be wasted work (a wallet balance, a seat). - Often neither: an atomic single statement (
balance = balance - x WHERE balance >= x) is simplest. - NOWAIT fails at once instead of waiting; SKIP LOCKED skips locked rows (job queues, "any free seat");
lock_timeoutcaps waiting. - Under heavy contention, optimistic locking causes retry storms; pessimistic locks held across user think time or network calls block everyone.
@Versionis optimistic locking in JPA;If-Matchwith an ETag is the same idea over HTTP.
The red pen
Common traps
Avoid:holding a row lock while waiting for a user or another service; optimistic locking on a flash-sale hot row.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.