Both prevent lost updates when two clients modify the same row. Pessimistic locking locks the row (or document) for the duration of the transaction so others must wait. Optimistic locking doesn’t lock; it checks at update time that the row hasn’t changed (e.g. via a version column) and fails the update if it has, so the client can retry.
| Aspect | Pessimistic | Optimistic |
|---|---|---|
| Lock | Hold lock during txn | No lock; check version/timestamp on write |
| Conflict | Second writer waits | Second writer gets 0 rows updated; retry |
| Best for | High contention, critical sections | Low contention, high throughput |
Use pessimistic when conflicts are frequent and blocking is acceptable. Use optimistic when conflicts are rare and you want to avoid holding locks (e.g. version column + WHERE version=old_version).