Concurrency control
medium 27 minConcurrency control keeps data right when many transactions use it at once.
Video lesson · Chapter 1 of 5
One cash drawer and two withdrawals
Concurrency control in 75 seconds
1:15Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Concurrency control is the set of methods that keeps shared data correct when several transactions use it at the same time. Isolation levels say what is promised. Concurrency control is how the promise is kept.
There are two attitudes. Pessimistic control expects conflicts: it takes a lock before touching the data, and others wait. Optimistic control expects none: it works without a lock and checks at the end whether something changed.
Multi-version concurrency control (MVCC) is a third idea that combines with both. The database keeps several versions of a row, so a reader can use an older one while a writer makes a new one.
Why it exists
Two withdrawals from one account, two people on one seat, two editors of one page: without control the later write removes the earlier one, and nobody notices.
Too much control is a problem of its own. If everybody waits for everybody, the system does one thing at a time. The art is to protect what must be protected, for as short a time as possible.
A short history
1978
David P. Reed's dissertation at MIT describes multi-version concurrency control.
1979
H. T. Kung and John T. Robinson propose optimistic concurrency control; the journal paper follows in 1981.
1984
VAX Rdb/ELN, made by Jim Starkey at Digital, is released: the first commercial database product with MVCC.
Words to know
- Shared lock (S)
- For reading. Many may hold it at once.
- Exclusive lock (X)
- For writing. Only one, and no shared lock beside it.
- Two-phase locking
- First only take locks, then only release them. It makes results serializable.
- MVCC
- Several versions of a row, so that readers and writers do not block each other.
- Optimistic check
- Write only if the version is the one that was read.
- Deadlock
- Transactions wait for each other in a circle.
- Intent lock
- A sign on a table that rows inside are or will be locked.
- Vacuum
- Cleaning up versions nobody can see any more.
How it works
Step through the idea, or press Play.
Find the conflict. Who writes what another one reads or writes
Understand it
Start here
One brush, or tracing paper
Asha and Lee paint a mural together. They can share one brush, or each draw on tracing paper and copy the result to the wall. Both ways work, and both have a catch.
A lock costs waiting. A sheet may cost doing it again. A print may be old.
The idea
Two attitudes and a third idea
Pessimistic: lock, then work
- Take the lock
- Read and change
- Release at commit
- Simple to think about, conflicts show at once
- Waiting, and deadlocks are possible
Optimistic: work, then check
- Read and remember the version
- Work without a lock
- Write if the version is unchanged
- No waiting while you work
- The loser repeats the work
The same two updates
When to use which
| Pessimistic | Optimistic |
|---|---|
| Conflicts are common | Conflicts are rare |
| Short transactions | Long thinking time, such as a form |
| Critical steps, such as moving money | Mostly reading |
| Repeating is expensive or has side effects | Repeating is cheap |
Pessimistic
Locks
- 1
Request
The transaction asks for a lock before it uses the data.
- 2
Acquire
If the lock is free it is granted. Otherwise the transaction waits.
- 3
Access
Read and change the data safely.
- 4
Release
COMMIT or ROLLBACK gives it to the next one.
It is like a bathroom door: lock it, use the room, unlock it. Simple, and there may be a queue.
-- risky: somebody may change the balance between the two statementsSELECT balance FROM accounts WHERE id = 1;UPDATE accounts SET balance = 900 WHERE id = 1;-- safe: lock firstBEGIN;SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;UPDATE accounts SET balance = 900 WHERE id = 1;COMMIT;-- safe and shorterUPDATE accounts SET balance = balance - 100WHERE id = 1 AND balance >= 100;Locking reads
| Clause | Meaning |
|---|---|
| FOR UPDATE | Exclusive row lock; blocks writers and other locking reads |
| FOR SHARE | Shared row lock; others may share it, writers wait |
| NOWAIT | Fail at once if the row is locked |
| SKIP LOCKED | Pass over locked rows, for job tables |
A job table with SKIP LOCKED
MVCC
Versions instead of waiting
A wiki page shows the idea: every edit makes a new version, and you can read the current one while somebody edits. A database does this per row.
Readers and writers apart
Which version?
| Version | Balance | Committed at | Snapshot 120 | Snapshot 160 |
|---|---|---|---|---|
| 1 | 1000 | 100 | Seen | Replaced |
| 2 | 900 | 150 | Not yet there | Seen |
The visibility rule
Two writers, one row
| Level | The second writer |
|---|---|
| Read committed in PostgreSQL | Waits, then checks its condition again on the new version |
| Repeatable read in PostgreSQL | Waits; if the first one committed, it aborts and must retry |
| Optimistic check | Changes zero rows, reads again |
The life of a row version
PostgreSQL, MySQL InnoDB, Oracle, CockroachDB, and SQL Server with snapshot options all keep row versions. The price is cleaning: PostgreSQL calls it vacuum. A long transaction keeps old versions alive. Oracle keeps old values in separate undo data.
Optimistic
Check at the end
SELECT quantity, version FROM inventory WHERE id = 123;-- quantity 10, version 5UPDATE inventorySET quantity = quantity - 1, version = version + 1WHERE id = 123 AND version = 5 AND quantity >= 1;-- 1 row changed: done. 0 rows: read again and decide again.The same idea runs on the web: a server sends an ETag with a resource, and a client sends it back in If-Match. RFC 9110 describes this as a way to avoid lost updates. Mappers do it too: SQLAlchemy's version counter raises a stale data error when no row matches.
class Product(Base): __tablename__ = "products" id = mapped_column(Integer, primary_key=True) quantity = mapped_column(Integer, nullable=False) version = mapped_column(Integer, nullable=False) __mapper_args__ = {"version_id_col": version}# pessimistic: SELECT ... FOR UPDATEwith Session(engine) as session: stmt = select(Account).where(Account.id == 1).with_for_update() account = session.execute(stmt).scalar_one() account.balance -= 100 session.commit()# optimistic: the version is checked by the UPDATEwith Session(engine) as session: product = session.get(Product, 123) product.quantity -= 1 try: session.commit() except StaleDataError: session.rollback() # load again and decide againWhen does optimistic stop paying?
Lock types
Shared, exclusive, big and small
May they hold it together?
| Wanted / held | Shared | Exclusive |
|---|---|---|
| Shared | Yes | No |
| Exclusive | No | No |
What can be locked
| Size | Example | Effect |
|---|---|---|
| Database | Maintenance | Coarsest, rare |
| Table | LOCK TABLE, many schema changes, bulk work | Everybody else may wait |
| Page | SQL Server, 8 KB pages | Several rows at once |
| Row | UPDATE, SELECT ... FOR UPDATE | Finest, most work at once |
Intent locks
IS: intent shared
Some rows inside will be read under a lock.
IX: intent exclusive
Some rows inside will be written.
SIX
The whole table is read, and some rows are written.
Why
Someone who wants the whole table sees one sign and need not check every row.
Deadlocks
A circle of waiting
Two people meet in a narrow corridor, and each waits for the other to step aside. Transactions do the same when they take locks in different orders.
How it forms
Prevent
- Lock in one order, for example by id
- NOWAIT or a lock timeout
- Short transactions
- Lock only what you need
Resolve (the database)
- Detect a circle in the wait-for graph
- Choose a victim
- Roll it back and free its locks
- The application retries
PostgreSQL waits for deadlock_timeout, one second by default, before it looks for a circle, and its manual says not to rely on which transaction is aborted. InnoDB detects deadlocks by default and tries to roll back small transactions, judged by the rows they changed.
BEGIN;SELECT id FROM accountsWHERE id IN (1, 5)ORDER BY idFOR UPDATE;UPDATE accounts SET balance = balance - 100 WHERE id = 1 AND balance >= 100;-- check: exactly one row changed, or ROLLBACKUPDATE accounts SET balance = balance + 100 WHERE id = 5;COMMIT;Decide
Which tool first?
From simple to strong
Operate
What to watch
| Signal | Means | Do |
|---|---|---|
| Long lock waits | Long transactions or a hot row | Shorten, split |
| Deadlocks per minute | Two paths with different orders | Sort the locks, retry |
| Old transactions | Cleaning cannot go on | Limit their age |
| Many version conflicts | Optimistic is the wrong choice here | Lock or redesign |
| Table grows without new rows | Dead versions | Check vacuum |
Summary
The whole topic in one minute.
Pessimistic control locks first and makes others wait. Optimistic control works first and makes the loser try again. MVCC lets readers use old versions, so they wait for nobody, while two writers of one row still need a lock or an abort.
Locks bring deadlocks: avoid them with one order for the whole program, keep transactions short, and retry the victim. The best protection is often neither lock nor version, but one atomic statement.
- Pessimistic waits, optimistic repeats, MVCC lets readers do neither.
- MVCC does not settle two writers of one row.
- One atomic statement often beats both.
- Shared locks go together, exclusive ones never.
- Deadlocks: one lock order, short transactions, retry the victim.
- Old snapshots stop the cleaning of versions.