Locking and MVCC in practice
Pick the right tool when two requests change the same row, and learn how your database keeps reads fast while rows change.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
On 2 March 2014, a small Bitcoin exchange called Flexcoin lost every coin in its hot wallet. The attacker took 896 BTC. The next day, Flexcoin closed for good. 1
The attacker did not break in. They created a normal account and deposited some coins. Then they used Flexcoin's feature for transfers between users. 1
They sent thousands of transfer requests at the same moment. Coins moved out of the sending account "until the sending account was overdrawn, before balances were updated". They repeated this across several accounts to grow the amount, then withdrew it. 1
Flexcoin did not publish its code. Our reading of the notice: each request checked the balance, then wrote a new balance a moment later. Many requests passed the check before the first writes landed.
You have seen this bug before as the lost update. This lesson is about the tools that stop it, and what each one costs.
The idea in simple words
The transactions lesson showed that a transaction alone is not a lock. Here you choose how to protect the rows you change. There are three main tools.
- One atomic statement. The database checks and changes the row in a single
UPDATE. No read in your app code, so no gap. - Pessimistic locking. You lock the row first, then read and change it. Others who want to change it wait.
- Optimistic locking. You read with no lock. When you write, you check that nobody changed the row in between. If someone did, you retry.
All three protect writers from each other. None of them should slow down plain reads. That is the job of MVCC, the way the database keeps old row versions so readers do not wait.
The key idea. First try to make the change one statement. If you must read first, lock when conflicts are common and the lock is short. Check a version when conflicts are rare or a person is thinking.
How it works
Pessimistic: lock the rows you will change
For a transfer, lock both accounts in one statement, in ID order:
BEGIN;
SELECT id, balance FROM accounts
WHERE id IN (17, 42)
ORDER BY id
FOR UPDATE;
-- app checks: balance of 17 >= 50
UPDATE accounts SET balance = balance - 50 WHERE id = 17;
UPDATE accounts SET balance = balance + 50 WHERE id = 42;
COMMIT;FOR UPDATE stops other transactions from updating, deleting or locking these rows until you commit. Plain SELECTs are not blocked. 2 In Read Committed (the default), a second Flexcoin-style request would wait here, then read the new balance. 4
There are softer and faster versions:
FOR SHAREblocks updates and deletes, but otherFOR SHAREreaders can lock the row too. 2 Use it when the row must not change while you work, but you will not change it yourself.NOWAITreturns an error at once if a row is already locked. 3 Use it to tell a user "someone else is editing this" instead of making them wait.SKIP LOCKEDskips rows that are locked. 3 Postgres added it in 9.5. 12 MySQL 8.4 hasNOWAITandSKIP LOCKEDtoo. 14
SKIP LOCKED is built for job queues:
SELECT id, payload FROM jobs
WHERE status = 'ready'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;Each worker gets a different job, and nobody waits. Both manuals warn that skipping rows gives an inconsistent view. So use it for queue-like tables, not for general work. 3 14
Optimistic: check a version when you write
Add a version column. Read it with the row. When you save, require that it has not changed:
UPDATE tickets
SET body = $1, version = version + 1
WHERE id = 7 AND version = 3;Step through two agents saving the same ticket.
- Two support agents open the same ticket. Both read the row and get version 3. No lock is taken.
- Agent A saves first: UPDATE … WHERE id = 7 AND version = 3. The row still has version 3, so 1 row changes. The version becomes 4.
- Agent B saves with the same condition, version = 3. The row now has version 4, so nothing matches. The database reports 0 rows. This is not an error, so B's code must check the count.
- B's code treats 0 rows as a conflict. It reads the row again and gets version 4, with A's change in it.
- B merges or re-applies the edit and saves with version = 4. This time 1 row changes. Both edits survive, and nobody waited on a lock.
Postgres answers UPDATE 1 or UPDATE 0. A count of 0 is not an error. 5 So your code must read the count. On 0, reload the row and retry, or show the user a conflict.
What if the other writer has not committed yet? In Read Committed, your UPDATE waits for it. Then Postgres checks your WHERE again on the new row. 4 The version no longer matches, so you get 0 rows.
The big win is time. The read and the write can be minutes apart, in two HTTP requests. No lock is held in between. Martin Fowler's catalog calls this pattern Optimistic Offline Lock. It "assumes that the chance of conflict is low". 16
The atomic statement, again
For counters and balances you often need no version at all:
UPDATE accounts SET balance = balance - 50
WHERE id = 17 AND balance >= 50;In Read Committed, 0 rows means "not enough money" (or no such account). A waiting update checks its WHERE again on the new row. 4 In Repeatable Read, you get error 40001 instead. 4 The check and the change are one step. That is the shape Flexcoin's transfers needed. The flash sales lesson uses the same idea for stock.
MVCC: why readers do not wait
The Postgres docs say it plainly: "reading never blocks writing and writing never blocks reading". 6 The trick is that a write keeps the old version of the row for readers who still need it.
In Postgres, each UPDATE makes a new row version. Each version has hidden columns. xmin is the ID of the transaction that created it. xmax is the ID of the transaction that deleted or replaced it. 7 It is 0 for an undeleted row. A visible row can still show a number, usually because the deleting transaction has not committed or was rolled back. 7 Try SELECT xmin, xmax, * FROM accounts; on a test database.
The old version stays on disk. It must not be removed "while it is still potentially visible to other transactions". VACUUM later frees that space for reuse. Autovacuum runs it for you. 8
Plain VACUUM does not usually give space back to the operating system. After a big spike of updates, a table can bloat until you need VACUUM FULL. That takes an ACCESS EXCLUSIVE lock, so the table is unusable while it runs. 8
Here is the trap. A row version stays while it is "still potentially visible to other transactions". 8 So, we infer, one transaction left open for hours can stop VACUUM from removing dead versions. This applies to a transaction that holds a snapshot or has written something. Table bloat grows. Find such transactions in pg_stat_activity, where the docs check backend_xid and backend_xmin. 8
In MySQL InnoDB, the row is changed in place. The old content goes to an undo log. Each row has a hidden transaction ID and a pointer to its undo record. Readers rebuild older versions from there. 13
A background purge removes old undo records. It can only discard them when no open snapshot needs them. The manual asks you to commit regularly, "including transactions that issue only consistent reads". 13 Same lesson, different engine.
Deadlocks: two locks, opposite order
Transfer A locks account 17, then wants 42. Transfer B locks 42, then wants 17. Each waits for the other forever.
Postgres waits deadlock_timeout (default 1 second) before it checks for this. 9 Then it aborts one transaction. Which one "is difficult to predict and should not be relied upon". 2 The error code is 40P01. 10 InnoDB also detects deadlocks by default and rolls back a victim. 15
The fix has two parts. Lock rows in a consistent order, like the ORDER BY id above. 2 Then retry the whole transaction on a deadlock, because the InnoDB manual says you must handle retries "even if your application logic is correct". 15
Advisory locks, and beyond one database
Sometimes you want to lock an idea, not a row. For example: "only one nightly billing job runs". Postgres advisory locks take a number you choose. The database does not enforce their meaning; your code must ask for them. 2
BEGIN;
SELECT pg_try_advisory_xact_lock(4242); -- true or false, no wait
-- if true: do the work
COMMIT; -- releases the lockThe xact versions take the lock without waiting or with a wait, as you choose. 11 They are released at the end of the transaction. 2 Session-level ones stay until you unlock them or the session ends, even after a rollback. 2 Our advice: with a connection pool, prefer the transaction-level versions. For a long job, take a session-level lock on one connection that you keep for the whole job, and unlock it at the end. Or use a lock row with an expiry.
Locks across several databases or services are a different problem. They need a distributed lock with expiry and a fencing token. Don't reach for one if a single database can do the job.
Trade-offs
| Option | Best when | Waits? | Watch out for |
|---|---|---|---|
Atomic UPDATE ... WHERE | The rule fits in one statement: counters, balances, stock. | Briefly, only on the same row. | Read the row count. 0 means the rule said no. |
| Optimistic (version column) | Conflicts are rare, or a person edits between read and write. | Briefly, at write time, only if another write to the row is in progress. | Every caller must check the count and retry. Many retries under heavy contention. |
SELECT ... FOR UPDATE | Conflicts are common and the logic needs a read first. | Yes | Hold time. Never call a slow API or wait for a user inside it. Lock order. |
FOR UPDATE NOWAIT | A user should hear "busy" now, not wait. | No It fails fast. | You must handle the error. |
FOR UPDATE SKIP LOCKED | Many workers pull from a queue table. | No | Inconsistent view. Queues only. |
| Advisory lock | You lock a task, not a row. | Your choice. | Not enforced. Session locks can leak through a pool. |
At work: how a senior uses this
- In code review, find every read-then-write on a shared row. Ask: "Can this be one
UPDATE ... WHERE?" Often it can. - Check that every optimistic or atomic update reads the row count. An ignored
UPDATE 0is a silent bug. - Keep lock hold time to milliseconds. No HTTP calls, no queue publishes, no user input between
FOR UPDATEandCOMMIT. - Sort IDs before you lock several rows. Write the rule in a comment so the next person keeps it.
- Put the retry in one helper. Catch deadlocks (
40P01) and serialization failures (40001), back off, and retry the whole transaction. 10 Make it safe to repeat, as in idempotency and retries. - Add an index for the
WHEREof every locking query. InnoDB's deadlock advice includes this. 15 - Alert on old open transactions. A query on
pg_stat_activityordered byxact_startfinds them. - Remember that schema changes queue behind long transactions too. See schema migrations.
With AI
What to ask the agent
"List every place in this repo that reads a row and later updates it in the same request. For each, say if it can become one UPDATE ... WHERE, needs FOR UPDATE, or needs a version check."
"Add optimistic locking to the tickets table: a version column, a migration, and an update that returns a conflict error when 0 rows change. Include a test with two concurrent saves."
"Write a Postgres query that lists transactions open longer than 5 minutes, with their state and query text."
What to check yourself
- The code checks rows affected after every guarded
UPDATE. Agents often drop this. - Locks are taken in a fixed order, and nothing slow runs while they are held.
- The retry repeats the whole transaction, with a limit and backoff, not only the failed statement.
SKIP LOCKEDis used only on queue tables, never on balances or stock.- The test uses real parallel connections to a real database. A mock cannot show a race.
- The agent did not add a lock in app memory. It breaks as soon as two servers run.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 16 sources and related lessons
- Flexcoin, “Flexcoin is shutting down” (notice on flexcoin.com, 3–4 March 2014, Wayback Machine copy) (opens in a new tab)
The exchange's own notice. It explains how thousands of simultaneous transfers overdrew an account. - PostgreSQL documentation: 13.3. Explicit Locking (opens in a new tab)
Row-level lock modes and what each one blocks, deadlocks, and advisory locks. - PostgreSQL documentation: SELECT (opens in a new tab)
The Locking Clause: NOWAIT, SKIP LOCKED, and why skipping locked rows suits only queue-like tables. - PostgreSQL documentation: 13.2. Transaction Isolation (opens in a new tab)
In Read Committed, how a second UPDATE waits and then checks its WHERE clause again. - PostgreSQL documentation: UPDATE (opens in a new tab)
The "UPDATE count" result, where 0 rows is not an error. - PostgreSQL documentation: 13.1. Introduction (Concurrency Control) (opens in a new tab)
What MVCC is, and why reading never blocks writing in Postgres. - PostgreSQL documentation: 5.6. System Columns (opens in a new tab)
The hidden xmin and xmax columns on every row version. - PostgreSQL documentation: 24.1. Routine Vacuuming (opens in a new tab)
Why old row versions stay, what VACUUM and autovacuum do, and when VACUUM FULL is needed. - PostgreSQL documentation: 19.12. Lock Management (opens in a new tab)
deadlock_timeout, how long Postgres waits before it looks for a deadlock. - PostgreSQL documentation: Appendix A. PostgreSQL Error Codes (opens in a new tab)
The codes your retry logic should catch, such as 40P01 for a deadlock. - PostgreSQL documentation: 9.28. System Administration Functions (Advisory Lock Functions) (opens in a new tab)
pg_advisory_xact_lock, pg_try_advisory_xact_lock and their session-level versions. - PostgreSQL documentation: Release 9.5 (opens in a new tab)
The release that added SKIP LOCKED. - MySQL 8.4 Reference Manual: 17.3 InnoDB Multi-Versioning (opens in a new tab)
Undo logs, the hidden row fields, purge, and why you should commit read-only transactions too. - MySQL 8.4 Reference Manual: 17.7.2.4 Locking Reads (opens in a new tab)
FOR UPDATE, FOR SHARE, NOWAIT and SKIP LOCKED in InnoDB. - MySQL 8.4 Reference Manual: 17.7.5 Deadlocks in InnoDB (opens in a new tab)
How InnoDB deadlocks happen, how it picks a victim, and how to reduce them. - Martin Fowler (pattern by David Rice), “Optimistic Offline Lock”, Catalog of Patterns of Enterprise Application Architecture (opens in a new tab)
The classic name for a version check that spans more than one database transaction.
Real incident: Flexcoin, 2 Mar 2014: Flexcoin: a race in balance transfers emptied the hot wallet
Related: Transactions and isolation levels · Inventory, overselling and flash sales · Locks, atomics and deadlocks · Idempotency, retries and timeouts · Money and double-entry ledgers · Schema migrations without downtime · Secondary, composite and special indexes
Before this: Transactions and isolation levels. The same ideas in app code: Locks, atomics and deadlocks. Next: Inventory and flash sales, where one hot row meets thousands of buyers. Related: Money and double-entry ledgers and Secondary and composite indexes, which shows how VACUUM affects index-only scans. For vacuum, wraparound and HOT updates in depth: PostgreSQL in depth.