What is the difference between optimistic and pessimistic locking?

Answer

Optimistic locking assumes conflicts are rare. Multiple transactions read the same row simultaneously. Before saving changes, the transaction verifies the row hasn't been modified by comparing a version number or timestamp. If it has changed, the save fails with a conflict error and the client retries. No database locks are held during the transaction — high concurrency, low overhead. Pessimistic locking acquires an exclusive lock on the row when it is read (SELECT ... FOR UPDATE), preventing others from modifying it until the transaction completes. Guarantees no conflicts but serializes access, reducing concurrency. Use optimistic for high-read/low-conflict scenarios; pessimistic for high-conflict critical sections.