What is optimistic locking?
Optimistic locking
Optimistic locking updates a row only if no one else changed it since you read it. The row carries a version. You write “set balance where version = 7.” If the version moved, the write fails and you retry. Pessimistic locking holds a lock for the whole read-compute-write. Optimistic assumes collisions are rare.
How does optimistic locking work?
The worker reads the balance and its version. It computes the new amounts in memory. It writes those amounts only if the version is still the one it read. A success increments the version. A miss means another worker won. The loser retries on the new version.
Optimistic vs pessimistic locking
Pessimistic locking blocks other writers until you finish. It is safe and slow when many posts hit one balance. Optimistic locking lets readers proceed and fails the write if they collided. Ledgers often use both: a short lock around the apply, and a version check so two applies cannot both land.
What do you do on a conflict?
Retry the same reference. Do not create a new payment. If one balance is always conflicting, the problem is the hot row, not the lock style. Shard or coalesce that balance.
Blnk versions each balance and rejects an apply when the version has moved. The queue retries that work. See concurrency.