Taking Locks in a Consistent Order

Transactions accessing multiple resources can reduce circular waits by acquiring shared types of locks in a consistent order where their design permits.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace two workers
  2. Verify the chosen policy
  3. Draw the two resources and their waiting edges
  4. Include locks acquired by related operations

Trace two workers

One takes A then waits for B. Another takes B then waits for A. The wait graph contains a cycle. Directed prerequisite cycles illustrate the structure.

Verify the chosen policy

Having both workers request A before B removes this particular circular wait, but other operations may still introduce different dependencies. Two-phase locking explains where ordering and isolation meet.[1]

Draw the two resources and their waiting edges

Transaction A locks row one and then requests row two. B locks row two and waits for one. This waiting cycle is a deadlock. Having both code paths request rows in a stable order prevents this particular cycle. See cycles in dependency graphs.

A owns 1, awaits 2
B owns 2, awaits 1
Proposed common order: 1 before 2
The second transaction can wait without holding 2 first

Include locks acquired by related operations

Foreign keys, indexes and other code paths can introduce locks beyond this pair. Use a bounded concurrency test with the real database and handle deadlock errors according to its retry policy.

References

  1. PostgreSQL Global Development Group, Concurrency Control ↩