Locking a Row Before a Dependent Update

A transaction can use a supported row lock when it must make a decision from a row and protect that decision while changing dependent state.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a seat choice
  2. Keep the transaction brief
  3. Protect the check and the write together
  4. Check transaction duration and competing work

Trace a seat choice

A worker reads the remaining quantity under the necessary lock, checks it, and records a reservation. Another worker may have to wait before performing its own check. Database locks describe the coordination.

Keep the transaction brief

Waiting for user interaction while holding a lock can delay other work. Check both a valid result and a rejected one under the operation contract.[1]

Protect the check and the write together

A capacity operation reads available seats and books one if a seat remains. When serialized by a row lock, the second transaction can observe capacity after the first changes it. The lock must cover the read that justifies a dependent write. See lost updates.

Initial remaining=1
A locks row, confirms capacity, writes remaining=0
B waits under the chosen behavior
B reads zero after A commits

Check transaction duration and competing work

Holding a row during an unrelated external request can delay all other writers. Test contention on the same row and independence on a separate one. State the database's isolation and lock behavior.

References

  1. PostgreSQL Global Development Group, Concurrency Control ↩