Distributed

Lesson 02.3

Pessimistic locking (SELECT … FOR UPDATE)

Pessimistic locking reserves a database row for one transaction, making competing transactions wait until the lock is released.

Taking turns with a lock

A cookie shop's computer shows how many cookies are left. Right now it says 1 🍪. Two workers, Ava and Ben, each get an order at almost the same moment.

Two workers once sold the same last cookie, because one checked before the other had updated the number. This shop fixes it with a lock 🔒: only one worker at a time may use the number.

In this lesson you'll

  1. 1Watch the lock on a normal day.
  2. 2Guess what happens when Ben wants to check while Ava has the lock.
  3. 3See how long waiting can get.