Data · L2Locking and MVCC in practice

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.

L2 SeniorData22 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 9 Nov 2026 · How we check content
Section 1 of 8

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.

Section 2 of 8

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.

  1. One atomic statement. The database checks and changes the row in a single UPDATE. No read in your app code, so no gap.
  2. Pessimistic locking. You lock the row first, then read and change it. Others who want to change it wait.
  3. 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.

Section 3 of 8

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 SHARE blocks updates and deletes, but other FOR SHARE readers can lock the row too. 2 Use it when the row must not change while you work, but you will not change it yourself.
  • NOWAIT returns 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 LOCKED skips rows that are locked. 3 Postgres added it in 9.5. 12 MySQL 8.4 has NOWAIT and SKIP LOCKED too. 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.

Optimistic locking: two edits race on a version column, one wins and one retries Agent A ticket row Agent B version = 3 read: v3read: v3 UPDATE v=31 row ✓version = 4 UPDATE v=30 rows reload: v4sees A's edit UPDATE v=4version = 51 row ✓✓ both edits kept, none lostNo lock was held while they typed. SeniorPath
  1. Two support agents open the same ticket. Both read the row and get version 3. No lock is taken.
  2. 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.
  3. 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.
  4. B's code treats 0 rows as a conflict. It reads the row again and gets version 4, with A's change in it.
  5. 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.
Step 1 of 5

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 lock

The 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.

Section 4 of 8

Trade-offs

OptionBest whenWaits?Watch out for
Atomic UPDATE ... WHEREThe 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 UPDATEConflicts 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 NOWAITA user should hear "busy" now, not wait.No It fails fast.You must handle the error.
FOR UPDATE SKIP LOCKEDMany workers pull from a queue table.No Inconsistent view. Queues only.
Advisory lockYou lock a task, not a row.Your choice.Not enforced. Session locks can leak through a pool.
Section 5 of 8

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 0 is a silent bug.
  • Keep lock hold time to milliseconds. No HTTP calls, no queue publishes, no user input between FOR UPDATE and COMMIT.
  • 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 WHERE of every locking query. InnoDB's deadlock advice includes this. 15
  • Alert on old open transactions. A query on pg_stat_activity ordered by xact_start finds them.
  • Remember that schema changes queue behind long transactions too. See schema migrations.
Section 6 of 8

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 LOCKED is 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.
Section 7 of 8

Check yourself

1. You run UPDATE tickets SET body = $1, version = version + 1 WHERE id = 7 AND version = 3. Postgres answers UPDATE 0. What does it mean?

Show answer

Someone changed the row after you read it. Reload it, then retry or show a conflict. The version is no longer 3, so no row matched. Postgres does not treat 0 rows as an error, so your code must check the count.

2. Ten workers take jobs from one jobs table. Each job must run once, and workers should not wait for each other. Which read fits best?

Show answer

SELECT ... FOR UPDATE SKIP LOCKED SKIP LOCKED passes over rows another worker has locked, so each worker gets a different job at once. The docs name queue-like tables as the use case.

3. Someone leaves a Postgres transaction open for six hours. A busy table keeps growing on disk. Why?

Show answer

VACUUM cannot remove old row versions that the open transaction might still need to see. An old row version must stay while it is still potentially visible to an open transaction. So one old transaction can hold back cleanup of dead versions.

4. Two money transfers sometimes fail with "deadlock detected". One locks account 17 then 42, the other 42 then 17. What is the best fix?

Show answer

Lock rows in one fixed order, such as lowest ID first, and retry the transaction on a deadlock error. A consistent lock order removes the wait cycle. A retry handles the rare cases that are left. Removing the transaction breaks atomicity.

5. Users edit a product description in a form for several minutes before they click Save. Conflicts are rare. Which approach fits?

Show answer

Optimistic locking with a version column, checked on Save. You must never hold a database lock while a person thinks. A version check needs no lock until the write.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 16 sources and related lessons
  1. 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.
  2. PostgreSQL documentation: 13.3. Explicit Locking (opens in a new tab)
    Row-level lock modes and what each one blocks, deadlocks, and advisory locks.
  3. PostgreSQL documentation: SELECT (opens in a new tab)
    The Locking Clause: NOWAIT, SKIP LOCKED, and why skipping locked rows suits only queue-like tables.
  4. 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.
  5. PostgreSQL documentation: UPDATE (opens in a new tab)
    The "UPDATE count" result, where 0 rows is not an error.
  6. PostgreSQL documentation: 13.1. Introduction (Concurrency Control) (opens in a new tab)
    What MVCC is, and why reading never blocks writing in Postgres.
  7. PostgreSQL documentation: 5.6. System Columns (opens in a new tab)
    The hidden xmin and xmax columns on every row version.
  8. 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.
  9. PostgreSQL documentation: 19.12. Lock Management (opens in a new tab)
    deadlock_timeout, how long Postgres waits before it looks for a deadlock.
  10. 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.
  11. 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.
  12. PostgreSQL documentation: Release 9.5 (opens in a new tab)
    The release that added SKIP LOCKED.
  13. 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.
  14. 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.
  15. 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.
  16. 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.

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper