AlgoViz

Concurrency control

medium 27 min

Concurrency 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

Transaction ABEGINTransaction B-Row 1free

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

Our systemupdatescleansWritersTablefew old versionsVacuum
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

    critical

    Another transaction may change the value in between. The second write removes the first.

    Wrong
    bal = SELECT balance ... WHERE id = 1UPDATE ... SET balance = bal - 100
    Right
    UPDATE accounts SET balance = balance - 100WHERE id = 1 AND balance >= 100
  • Locks in a random order

    critical

    Two transfers in opposite directions form a circle.

    Wrong
    lock(src); lock(dst)
    Right
    for id in sorted({src, dst}):    lock(id)
  • Waiting for a person while holding a lock

    critical

    Someone opens a form and goes to lunch. Everybody else waits.

    Wrong
    lock(row); show_form(); save()
    Right
    show_form(row, version)      # no locksave_if_version(row, version)
  • Ignoring zero changed rows

    major

    An optimistic check only works if somebody looks at the result.

    Wrong
    update_where_version(5)return "saved"
    Right
    if 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.