Jay Taylor's notes

back to listing index

Richard Clayton - Distributed Locking with Postgres Advisory Locks

[web search]
Original source (rclayton.silvrback.com)
Tags: database postgres postgresql concurrency locking leader-election pg_advisory_lock rclayton.silvrback.com
Clipped on: 2025-08-21

Distributed Locking with Postgres Advisory Locks

Image (Asset 1/5) alt=

Concurrency is hard

We ran into a problem last month around concurrent mutations of our credit ledger which lead us to adopt a really cool feature of Postgres.

At Peachjar, we track the purchase, usage, and refund of credits as a log of transactions (e.g. a ledger). The ledger system is really just a table in Postgres and a microservice (with many deployments) that contain the rules for interacting with that table.

Image the table looking something like this:

Image (Asset 2/5) alt= - Press the purchase button twice (and the button didn't disable after the first push).
- The user refreshes the page after a form submittal (classic replay of a POST).
- The user is malicious and purposely executes two concurrent purchase requests.
- A timeout is reached and a retry is executed (this was our actual problem).

Image (Asset 3/5) alt= [2]. Spring AOP transaction management in Hibernate – Mkyong.com
[3]. Quick Guide to Spring Bean Scopes | Baeldung

Richard Clayton

Stumbling my way through the great wastelands of enterprise software development.

February 16, 2020