Every backend eventually needs the same primitive: run this job on exactly one
instance at a time. A nightly report. A poller that shouldn't fire twice. A
reconciliation job that would corrupt data if two copies raced each other. The
need is boring and universal — which is exactly why it's strange how heavy the
usual answers are.

  • ZooKeeper / Consul / etcd — a whole coordination service to run, monitor, and page someone about, just so a job doesn't double-fire.
  • Redis Redlock — a new dependency, and its correctness under partition and clock skew has been debated in public for years.
  • SELECT ... FOR UPDATE — fine for a lock held for one transaction. Wrong shape for "hold this for the next 20 minutes" — it blocks other queries and a hung connection holds the lock forever.

If you already run Postgres or MySQL, none of that is necessary. db-mutex is a
distributed mutex that's just one table.

The core trick: let the database enforce exclusivity

CREATE TABLE mutex_lock ( lock_name VARCHAR(64) NOT NULL, locked INT NOT NULL DEFAULT 1, instance_id VARCHAR(64) NOT NULL, last_heartbeat TIMESTAMP NOT NULL, acquired_at TIMESTAMP NOT NULL, CONSTRAINT uq_mutex_lock UNIQUE (locked, lock_name), CONSTRAINT chk_locked CHECK (locked = 1) ); 

UNIQUE(locked, lock_name) plus CHECK (locked = 1) means at most one row can
ever exist per lock_name
— the database's own constraint enforcement does the
mutual-exclusion work. Acquiring a lock is just "try to insert a row." Whoever's
INSERT lands first wins; everyone else's fails on the constraint. No CAS loop,
no advisory locks, no distributed-consensus protocol to reason about — just a
guarantee the database already gives you for free.

Staying alive: heartbeats, and two thresholds instead of one

A lock row has to go away when its holder dies, or every crash becomes a
permanent deadlock. The lock holder sends a heartbeat every 10 seconds
(UPDATE ... SET last_heartbeat = now()), and every other instance watches that
timestamp to decide whether the holder is still alive.

Most tutorials reach for one timeout here — "no heartbeat in N seconds, release
it." That's the wrong call. If you release too aggressively, a holder that's
merely slow (a GC pause, a long query, a noisy neighbor) loses the lock to
another instance that's likely to hit the exact same slowness — and now you're
in a churn loop where nobody makes progress.

db-mutex uses two thresholds instead:

  • 30 seconds without a heartbeat → fire an alert. Let a human (or your on-call tooling) decide: is this holder slow, or actually dead?
  • 10 minutes without a heartbeat → auto-release. Safe to assume it crashed.

The alert window buys time for a human to intervene before the system self-heals
on its own — rather than silently reshuffling the lock between instances that are
all hitting the same problem.

sequenceDiagram participant A as Instance A participant DB as mutex_lock table participant B as Instance B A->>DB: INSERT (lock_name, instance_id=A) DB-->>A: acquired ✅ loop every 10s A->>DB: UPDATE last_heartbeat = now() end B->>DB: try INSERT (lock_name, instance_id=B) DB-->>B: UNIQUE violation → rejected, A still holds it Note over A: A crashes — heartbeats stop Note over DB: 30s since last heartbeat DB-->>B: alert fires (on_alert / metrics hook) Note over DB: 10min since last heartbeat B->>DB: SELECT ... FOR UPDATE → sees stale row B->>DB: DELETE stale row, INSERT (lock_name, instance_id=B) DB-->>B: acquired ✅ (reclaimed_from=A)

On a clean shutdown, release() deletes the row outright instead of waiting out
the 10-minute window — the next instance can acquire immediately.

One more detail that matters more than it sounds: every staleness check —
now(), the interval comparison — runs inside a single database statement.
Results depend only on the database server's clock, never on any client's wall
clock. Skewed or jumping client clocks can't corrupt lock state.

One API, pluggable backend underneath

flowchart LR App["Your app"] -->|"Mutex(dsn=...)"| M["Mutex (public API)"] M --> Core["shared acquire / heartbeat / release control flow"] Core --> PG["Postgres backend\n(psycopg)"] Core --> MY["MySQL backend\n(PyMySQL / asyncmy)"] PG --> PGDB[("Postgres")] MY --> MYDB[("MySQL")]

The public Mutex class doesn't know or care which database it's talking to —
it sniffs the backend from your dsn's scheme (postgres:// vs mysql://), or
you set it explicitly. The locking logic — the dual-threshold decision, heartbeat
scheduling, the acquire/release state machine — lives in one shared control-flow
layer; each backend only implements the SQL dialect underneath it. Sync and
async, a dedicated connection or a connection pool you already manage — same
capabilities, either database.

from db_mutex import Mutex mutex = Mutex(dsn="postgres://user:pass@host/db", lock_name="nightly-report-job") mutex.create_schema() with mutex.acquire(blocking=False) as acquired: if acquired: run_the_job() else: print("another instance is running the job") 
# MySQL — identical API, just a different dsn scheme mutex = Mutex(dsn="mysql://user:pass@host/db", lock_name="nightly-report-job") 
# async works the same way async with mutex.acquire_async(blocking=True, timeout=30): await run_the_job_async() 

How it stacks up

Extra infra? Survives a crash cleanly? Blocks other queries?
db-mutex No — uses the database you already have Yes — heartbeat + dual-threshold auto-release No
Redis Redlock Yes Depends on TTL tuning, debated correctness No
SELECT ... FOR UPDATE No Hung connection holds it forever Yes
ZooKeeper / Consul / etcd Yes — a whole service to operate Yes No

Try it

pip install db-mutex # Postgres pip install db-mutex[mysql] # + MySQL 

Full README (failure modes spelled out explicitly, benchmark numbers, metrics
hooks for Prometheus/OpenTelemetry) at
github.com/rishi-rana/db-mutex.