7.6 Locking Reads: FOR UPDATE, Optimistic and Pessimistic Locking

The Lost Update in Section 7.1 happened because the read and the write were separate statements. No lock is held at the moment of the read, so nothing stops another transaction from slipping in between. There are three ways to fix this.

First, merge the read and the write into one statement. Writing UPDATE account SET balance = balance - 100000 WHERE id = 'hong' makes the database read, compute, and write while holding the lock. This is the simplest and best approach, but it cannot be used when the computation requires application-side logic.

Second, take the lock at read time (pessimistic locking). SELECT ... FOR UPDATE reads the row and takes an exclusive lock on it (X in Section 7.3, or U in some products). If another transaction tries to read the same row with FOR UPDATE or modify it, it waits until the current transaction ends. If T1 and T3 in the Lost Update table of Section 7.1 had both read with FOR UPDATE, T3 would block at time 2, and after T1 commits it would read 400,000 and subtract 200,000. Because it assumes pessimistically that a conflict will occur and blocks it up front, this is called pessimistic locking. FOR SHARE (LOCK IN SHARE MODE in InnoDB, a hint in SQL Server) takes only a shared lock, which "prevents anyone from modifying the row while I am reading it."

In an MVCC database, FOR UPDATE has one more role. Whereas a plain SELECT shows an older version from the snapshot, FOR UPDATE takes the lock and then returns the latest committed version of the row. The InnoDB documentation calls the former a consistent read and the latter a locking read, or current read. That a plain SELECT and a FOR UPDATE in the same transaction can return different values is the point that most often surprises developers new to MVCC databases.

The cost of pessimistic locking is waiting. If the transaction holding the lock is long, every request behind it waits. In flows such as web applications, where the sequence is "read, show it to the user, write when the user submits input," the lock cannot be held while the user looks at the screen, so this approach cannot be used.

Third, check at write time whether the row has changed (optimistic locking). Add a version number (or last-modified timestamp) column to the row, and read that value along with the data. At write time, put "is the version I read still unchanged?" in the condition, as in UPDATE account SET balance = 400000, version = 8 WHERE id = 'hong' AND version = 7. If someone modified the row in the meantime, version is already 8 or higher, the condition does not match, and the updated row count comes back as 0. The application interprets this as a "conflict," reads again, and retries. Because no lock is taken at all, there is no waiting, and the write works even after the long interval while the user looks at the screen. The drawback is that frequent conflicts cause repeated retries, which is inefficient. Because it assumes optimistically that conflicts will be rare and checks afterward, this is optimistic locking. JPA's @Version and the optimistic locking features of many ORMs work this way.

ApproachWhen the conflict is preventedWaitingSuitable when
Merge into one statementAutomatically inside the databaseShort row lockThe computation can be expressed in SQL
Pessimistic locking (FOR UPDATE)At read timeYesConflicts are frequent and transactions are short
Optimistic locking (version column)At write timeNone (retry on failure)Conflicts are rare, or user input wait is involved

All three are means of resolving "write-write conflicts." Because MVCC eliminated read-write conflicts, the developer now has only this one kind to worry about.