AlgoViz

Concurrency control

medium 27 min

Concurrency control keeps data right when many transactions use it at once.

Video lesson · Chapter 1 of 5

One cash drawer and two withdrawals

0:00 / 3:30

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

  1. 1978

    David P. Reed's dissertation at MIT describes multi-version concurrency control.

  2. 1979

    H. T. Kung and John T. Robinson propose optimistic concurrency control; the journal paper follows in 1981.

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

Step 1 of 3

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.

Two painters, one wall
WallPaintingWaitingAshaLee

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

Somebody always loses time in a conflict: by waiting, or by repeating.

When to use which

PessimisticOptimistic
Conflicts are commonConflicts are rare
Short transactionsLong thinking time, such as a form
Critical steps, such as moving moneyMostly reading
Repeating is expensive or has side effectsRepeating is cheap

Pessimistic

Locks

  1. 1

    Request

    The transaction asks for a lock before it uses the data.

  2. 2

    Acquire

    If the lock is free it is granted. Otherwise the transaction waits.

  3. 3

    Access

    Read and change the data safely.

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

SQL
-- 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;
Risky and safe. The last one needs no extra lock, because one statement reads and writes.

Locking reads

ClauseMeaning
FOR UPDATEExclusive row lock; blocks writers and other locking reads
FOR SHAREShared row lock; others may share it, writers wait
NOWAITFail at once if the row is locked
SKIP LOCKEDPass over locked rows, for job tables
A plain SELECT is not blocked by any of them in a database with row versions.

A job table with SKIP LOCKED

A jobs table with three jobs. Three workers each take one job, skipping rows that are locked: worker 1 holds job 1, worker 2 holds job 2, worker 3 holds job 3.
Each worker takes the first free job. A worker that dies loses its lock, so a job may run again.

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

One database machine. Readers use the old version of row 1, balance 1000, with no lock and no wait. Writers go through the lock manager, one at a time, and then write the new version, balance 900.
Readers take the old version. Writers of one row still go one at a time.

Which version?

VersionBalanceCommitted atSnapshot 120Snapshot 160
11000100SeenReplaced
2900150Not yet thereSeen

The visibility rule

seen=created≤s;∧;(never replaced;∨;replaced>s)\text{seen} = \text{created} \le s ;\wedge; (\text{never replaced} ;\vee; \text{replaced} > s)
Both times are commit times, and s is the snapshot. Version 1: 100 <= 120 and 150 > 120, so it is seen at 120. A transaction also sees its own changes.

Two writers, one row

LevelThe second writer
Read committed in PostgreSQLWaits, then checks its condition again on the new version
Repeatable read in PostgreSQLWaits; if the first one committed, it aborts and must retry
Optimistic checkChanges 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

SQL
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.
A version column. The application looks at the number of changed rows.

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.

Python
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 again
SQLAlchemy, both ways. With version_id_col the check happens when changes are flushed.

When does optimistic stop paying?

E=w1−pw=20 ms:;p=0.05⇒21 ms,p=0.6⇒50 msE = \frac{w}{1 - p} \qquad w = 20\ \text{ms}:; p = 0.05 \Rightarrow 21\ \text{ms}, \quad p = 0.6 \Rightarrow 50\ \text{ms}
w is the time of one try and p the chance that it fails, assumed independent. With many conflicts a short wait for a lock is cheaper than doing it 2.5 times.

Lock types

Shared, exclusive, big and small

May they hold it together?

Wanted / heldSharedExclusive
SharedYesNo
ExclusiveNoNo

What can be locked

SizeExampleEffect
DatabaseMaintenanceCoarsest, rare
TableLOCK TABLE, many schema changes, bulk workEverybody else may wait
PageSQL Server, 8 KB pagesSeveral rows at once
RowUPDATE, SELECT ... FOR UPDATEFinest, most work at once
Smaller locks let more run together and need more bookkeeping. SQL Server may replace many small locks with one table lock.

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.

SQL
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;
PostgreSQL: lock both rows in id order, then move the money.

Decide

Which tool first?

From simple to strong

Operate

What to watch

SignalMeansDo
Long lock waitsLong transactions or a hot rowShorten, split
Deadlocks per minuteTwo paths with different ordersSort the locks, retry
Old transactionsCleaning cannot go onLimit their age
Many version conflictsOptimistic is the wrong choice hereLock or redesign
Table grows without new rowsDead versionsCheck 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.

Sources