Concurrency control
medium 27 minConcurrency control keeps data right when many transactions use it at once.
See it run
Locks that make others wait, versions that let readers go on, and checks at the end: what each does step by step.
Operations
Pessimistic lock
A locks the row before reading. B asks for the same lock and waits until A commits.
Step 1 of 8
A starts
Row 1 is free
BEGIN. The row is free.
Step 1: A starts
with db.transaction(): row = db.query("SELECT * FROM accounts" " WHERE id = 1 FOR UPDATE") # waits here db.execute("UPDATE accounts SET balance = %s" " WHERE id = 1", row.balance - 100)# COMMIT releases the lock- Under conflict
- B waits
- Price
- Less at once
- Work wasted
- none
- Deadlocks
- possible
In a database with row versions a plain SELECT does not wait for this lock. Only writers and other locking reads do.
In the real world
The same concurrency control doing real jobs. Pick one and step through it.
Old versions can go only when nobody might read them.
Step 1 of 3
Versions come and go
- Old versions
- 10%
Balanced
Updates leave old versions, and a background task removes them.
Step 1: Versions come and go
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Read, then write without protection
criticalAnother transaction may change the value in between. The second write removes the first.
Wrongbal = SELECT balance ... WHERE id = 1UPDATE ... SET balance = bal - 100RightUPDATE accounts SET balance = balance - 100WHERE id = 1 AND balance >= 100Locks in a random order
criticalTwo transfers in opposite directions form a circle.
Wronglock(src); lock(dst)Rightfor id in sorted({src, dst}): lock(id)Waiting for a person while holding a lock
criticalSomeone opens a form and goes to lunch. Everybody else waits.
Wronglock(row); show_form(); save()Rightshow_form(row, version) # no locksave_if_version(row, version)Ignoring zero changed rows
majorAn optimistic check only works if somebody looks at the result.
Wrongupdate_where_version(5)return "saved"Rightif update_where_version(5) == 0: return "changed meanwhile: reload"
Interview tips
How to explain it
- Pessimistic: take the lock, then work.
- Optimistic: work, then check.
- MVCC: readers use old versions and wait for nobody.
Memory trick
- Pessimistic: lock first, ask later.
- Optimistic: hope first, check later.
- Deadlock: a circle. Break it with one order.
Choose pessimistic when
- Conflicts are common.
- Work is short.
- Doing it again is expensive.
Choose optimistic when
- Conflicts are rare.
- A person edits for minutes.
- Reads are far more common than writes.