db-mutex: Using a UNIQUE Constraint as a Distributed Lock in Postgres or MySQL
The article argues that teams needing to run a job on only one instance often reach for ZooKeeper, Consul, etcd, or Redis, each adding operational cost or correctness concerns, while SELECT ... FOR UPDATE is ill-suited to long-held locks. It proposes db-mutex, which relies on a lock table with a UNIQUE(locked, lock_name) constraint and a CHECK (locked = 1) so that the first insert wins and others are rejected by the database itself. Liveness is tracked through periodic heartbeats: after 30 seconds without one an alert fires for human review, and after 10 minutes the lock is automatically reclaimed from the presumed-dead holder. The library exposes the same API for Postgres and MySQL, selected by the DSN scheme, and performs staleness checks inside single database statements.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in