What is a distributed lock?

Distributed lock

A distributed lock is a lock held outside the database so two workers cannot apply conflicting posts at the same time. The ledger locks the balances in a request, in a fixed order, then reads and writes. If it cannot get every lock, it releases what it has and retries. Without the order, two transfers deadlock.

How does a distributed lock work?

The worker lists the balance ids on the transfer. It sorts them. It takes each lock in that order. Then it reads the latest amounts, checks overdraft and inflight, applies, and commits. After the commit it drops the locks. Another worker can now take the same balances.

Distributed lock vs optimistic locking

The distributed lock stops two applies from running together. Optimistic locking is the write-time check that the version you read is still the version on disk. Use both. The lock reduces collisions. The version check catches the ones the lock missed, such as a crash between read and write.

What happens if a lock is stuck?

A worker died while holding it. A wait timeout or a lock TTL should free it. If you wait forever, the queue stops on that pair. If you steal the lock too early, two applies can land. Tune the wait. Do not disable the lock because a hot balance is slow. Shard that balance.

Blnk takes Redis locks on the balances in a request, always in the same order, then applies under an optimistic version check. See concurrency.