7.2 Lock Basics

The oldest and simplest solution is the lock. Before handling a row, a transaction locks it, and while the lock is held, other transactions are prevented from making incompatible accesses to that row. Locks come in two kinds.

  • Shared lock: A lock for reading. Several transactions can hold a shared lock on the same row at the same time, because reads do not conflict with each other.
  • Exclusive lock: A lock for writing. Only one transaction can hold it, and while a row is exclusively locked, no other transaction can take either a shared or an exclusive lock on it.

Locks are released when the transaction ends (commit or rollback).

"Holding locks until the transaction ends" is not a mere implementation convenience but a rule. The theoretical name for this rule is two-phase locking (2PL). It divides a transaction's life into a growing phase in which it only acquires locks and a shrinking phase in which it only releases them, and once it starts releasing locks it may not acquire new ones. It has been proven that doing so makes the result of concurrently executed transactions equivalent to running them one at a time in some order. Real DBMSs go one step further and release all locks at once at commit or rollback (strict 2PL), because releasing a lock midway would allow a Dirty Read, in which another transaction reads a value that has not yet been committed. The statement in Section 4.5 that long transactions hold locks for a long time is a direct consequence of this rule.

Let us try to solve the problems of Section 7.1 with locks alone. While T1 holds an exclusive lock on Hong Gildong's row and modifies it, the total query T2 tries to take a shared lock on that row, is blocked, and waits until T1 ends. The Dirty Read is prevented. T3 also tries to take an exclusive lock, is blocked and waits, and after T1 ends it reads 400,000 and subtracts 200,000, so the Lost Update is prevented as well. Correctness is secured.

Figure 7-1. Timeline with locks only

sequenceDiagram
  participant T1 as T1 (transfer)
  participant R as Hong Gildong row
  participant T2 as T2 (total query)
  participant T3 as T3 (withdraw 200K)
  T1->>R: Acquire exclusive lock (X)
  T1->>R: Change 500K to 400K
  T2->>R: Request shared lock (S)
  Note over R,T2: S and X are incompatible. T2 waits
  T3->>R: Request exclusive lock (X)
  Note over R,T3: X and X are incompatible. T3 waits
  T1->>R: COMMIT, release locks
  R-->>T2: Acquire S, read 400K
  T2->>R: Query ends, release S
  R-->>T3: Acquire X, read 400K and subtract 200K

From the left, the diagram shows the transfer T1, Hong Gildong's row, the total query T2, and the withdrawal T3, with time flowing from top to bottom.

  1. T1 first takes an exclusive lock (X) on Hong Gildong's row and changes the balance from 500,000 to 400,000.
  2. T2 requests a shared lock (S) to read this row. Since X is already held, S is not granted and T2 enters the wait queue. T2 has no way to read the uncommitted 400,000, so the Dirty Read is prevented.
  3. T3 requests X for its withdrawal. X and X are also incompatible, so T3 waits too.
  4. T1 commits and releases its lock. Only now does T2 obtain S and read the committed 400,000, and after T2 finishes, T3 obtains X and subtracts 200,000 from 400,000. T3 computes on top of T1's result, so no Lost Update occurs either.

Correctness is preserved, but the cost of this approach is that T2 and T3 can do nothing at all until T1 ends.

This cost grows as the query gets longer. Suppose the query T2 is a long one that totals all 1,000,000 accounts of the bank. T2 must take a shared lock on every row it reads and hold it until the query ends (if it released a lock midway, the value could change after being read and the total could be wrong). For those several minutes, none of the 1,000,000 accounts can be modified. Every transfer in the bank stops because of a single report. Conversely, on a server where transfers arrive continuously, the report may not even be able to start. That reads block writes and writes block reads is the fundamental limitation of the lock approach.

Deadlock

Locks have one more classic problem. If T1 holds Hong Gildong's row and waits for Kim Cheolsu's row, while at the same moment T4 holds Kim Cheolsu's row and waits for Hong Gildong's row, the two wait for each other forever. This is a deadlock. The database periodically detects such circular waits, forcibly rolls back one side, and returns an error. The application must receive that error and retry the transaction. The classic way to reduce deadlocks is to have every transaction acquire rows in the same order (for example, by account number).

Figure 7-2. Deadlock

flowchart LR
  subgraph LOCKS ["Lock holders and waiters"]
    T1["T1 (transfer)"]
    T4["T4"]
    H["Hong Gildong row"]
    K["Kim Cheolsu row"]
    T1 -->|"holds X"| H
    T4 -->|"holds X"| K
    T1 -.->|"waits for X"| K
    T4 -.->|"waits for X"| H
  end
  subgraph WFG ["Wait-for graph"]
    W1["T1"] -->|"waits for"| W4["T4"]
    W4 -->|"waits for"| W1
  end

The left box shows the relationships between transactions and rows. Solid lines are locks already held, and dotted lines are locks requested but not obtained.

  1. T1 holds X on Hong Gildong's row, and to finish the transfer it also needs X on Kim Cheolsu's row.
  2. T4 works in the opposite order: it holds X on Kim Cheolsu's row and waits for X on Hong Gildong's row.
  3. The row T1 waits for, Kim Cheolsu's, is held by T4, and the row T4 waits for, Hong Gildong's, is held by T1. Neither releases its lock first, so the wait never ends.

The right box is the wait-for graph the database uses to judge this situation. Drawing "T1 waits for T4" and "T4 waits for T1" as edges produces the cycle T1 → T4 → T1. This cycle is the definition of a deadlock, and the database breaks it by choosing one transaction in the cycle as the victim and rolling it back. If both transactions had acquired locks in the same order, such as Hong Gildong → Kim Cheolsu (or by account number), the later arrival would simply wait at the first row and no cycle would form.

There are two ways of handling deadlocks, and the two are often confused. One is deadlock detection. The database maintains a graph of "who is waiting for whom" like the one above, and when a cycle forms it declares a deadlock, picks one side as the victim, and rolls it back. InnoDB and SQL Server detect a cycle immediately or within a few seconds, while PostgreSQL waits for a set time (deadlock_timeout, default 1 second) and then checks. The victim is usually the side with less work to undo. The other is the lock wait timeout. Regardless of whether there is a deadlock, if a lock is waited on for longer than a set time, the wait is abandoned and an error is returned (PostgreSQL's lock_timeout, InnoDB's innodb_lock_wait_timeout, SQL Server's LOCK_TIMEOUT). It also fires when there is no deadlock and the wait is simply because an earlier transaction is long. The two produce different error messages, so you must tell which one occurred to find the cause quickly. For a deadlock error, look for "code that acquires the same resources in opposite order"; for a timeout error, look for "a transaction that holds locks for a long time".

There are also options to give up or skip immediately instead of waiting. SELECT ... FOR UPDATE NOWAIT raises an error right away if the lock cannot be taken, and SELECT ... FOR UPDATE SKIP LOCKED skips locked rows and returns only the rest. SKIP LOCKED is widely used in the job queue pattern, where several workers each take one job at a time from the same table. These clauses are variants of the "locking reads" covered in Section 7.6.

So far we have described locks as only shared and exclusive. Those two suffice conceptually, but the lock manager of a real DBMS uses more finely divided lock types across several granularities: row, page, and table. You will certainly encounter them when analyzing lock waits in practice, so the next two sections cover lock types, compatibility rules, and the phenomenon of locks changing to a larger granularity, and then we move on to MVCC in Section 7.5.