Video in progress

For a distributed lock, when do you choose Redis, a PostgreSQL advisory lock, or etcd/ZooKeeper?

For short locks used for efficiency, Redis: fast and simple. If the lock is tied to a change in the DB, PostgreSQL (an advisory lock or SELECT ... FOR UPDATE), because it lives together with the transaction. For leader election and coordination where correctness matters, etcd/ZooKeeper, because they provide consensus and fencing.

📖 Answer

Before choosing a lock, I ask: what happens if the lock fails? If two workers send the same report twice, it's annoying. If they transfer money twice, it's an incident.

Redis (SET NX PX, Redisson).

  • under a millisecond, high throughput;
  • works with a TTL, so if the owner dies the lock frees itself;
  • but a lock can be lost on failover, and there's no fencing token;
  • suitable for: running a cron job on a single pod, merging cache rebuilds, quick per-user serialization.

PostgreSQL.

SELECT pg_try_advisory_xact_lock(hashtext('invoice:' || :id));
-- released automatically when the transaction ends
  • the lock and the data change are in one transaction, so there's no "I took the lock, wrote, but the lock had already expired" problem;
  • if the connection drops, the lock is released;
  • but it ties up a DB connection, is awkward for long jobs, and adds load to the DB;
  • libraries like ShedLock also work on a table basis.

etcd / ZooKeeper.

  • consensus (Raft/ZAB), so the lock really has one owner;
  • session/lease and watch mechanisms, with revision/zxid as a fencing token;
  • leader election (Kubernetes itself stores leases through etcd on the API server);
  • the cost: a separate cluster, slower (milliseconds), operational know-how.

In practice I often do:

  • for scheduled jobs in Spring Boot, ShedLock + the DB or Redis;
  • for business invariants, not a lock but a DB constraint and optimistic locking;
  • if I need real leader election, the Kubernetes Lease API (leader election in Spring Cloud Kubernetes) or etcd.

One more thing: making the problem disappear without touching a lock is often the best solution, for example putting the work into a queue partitioned by key, so that one consumer always processes a given key.