Skip to the page

Transactions and locking · Trade-off

Optimistic or pessimistic locking

The 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

  1. What happens under optimistic locking when 1,000 people update the same row at once?
  2. What do NOWAIT and SKIP LOCKED do?
  3. Can you hold a FOR UPDATE lock while the user fills in a form?
  4. How do JPA's @Version and 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 UPDATE in 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_timeout caps waiting.
  • Under heavy contention, optimistic locking causes retry storms; pessimistic locks held across user think time or network calls block everyone.
  • @Version is optimistic locking in JPA; If-Match with 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 voice

Practise 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.

Start your free interview