Postgres advisory locks for cross-process deduplication
If you already have a Postgres connection, you already have a distributed lock. pg_try_advisory_lock(key) takes a 64-bit integer, returns true if it got the lock, false if someone else holds it, and releases automatically when the session ends. No need to stand up Redis or Redlock just to make sure only one replica runs a cron job.
The convention I use: the key is the hash of a stable string. Hashing is done in SQL so the key is the same across languages.
-- Acquire: returns true exactly once across all sessions.
SELECT pg_try_advisory_lock(hashtext('cron:daily-rollup'));
-- Do work here...
-- Release (or just end the session).
SELECT pg_advisory_unlock(hashtext('cron:daily-rollup'));
And a wrapper pattern I use from Go or any language: wrap the whole job in a single transaction and use the transaction-scoped variant, so the lock releases even if the client crashes.
BEGIN;
SELECT pg_try_advisory_xact_lock(hashtext('cron:daily-rollup')) AS got;
-- if got = true, do the work
COMMIT; -- lock released automatically
Caveats: hashtext is not a cryptographic hash; collisions are possible but rare enough for lock names. Advisory locks are per database, not per cluster. See also /posts/pgbouncer-transaction-pooling-footgun/.