A transaction makes a group of changes all-or-nothing, and locks make concurrent transactions take turns; both are only as good as the boundaries and the order you choose.
Transaction A moves money from Asha to Ben while transaction B moves money from Ben to Asha. Each locks the account it debits first, then the one it credits. Timings are an illustrative model; PostgreSQL checks for deadlocks after waiting deadlock_timeout (1 s by default).
Transaction A
Asha → Ben
Database
lock manager
Transaction B
Ben → Asha
Swipe the diagram sideways to see every column →
Where the time goes
1011 ms total
Transaction A moves money from Asha to Ben while transaction B moves money from Ben to Asha. Each locks the account it debits first, then the one it credits. Timings are an illustrative model; PostgreSQL checks for deadlocks after waiting deadlock_timeout (1 s by default).
Illustrative timings. Real numbers vary with distance, network quality and server load.