Reliable distributed mutex for your Postgres or MySQL applications.
Project details
db-mutex provides a simple solution for implementing a distributed mutex on Postgres or MySQL. With features like heartbeat-based liveness and automatic recovery from crashed lock holders, it eliminates the need for additional systems like ZooKeeper and Redis. Perfect for ensuring that jobs run on a single instance.
db-mutex is a powerful distributed mutex for PostgreSQL and MySQL that enables precise job scheduling across multiple instances. With its unique design utilizing a single table and heartbeat-based liveness checks, db-mutex offers automatic recovery from crashed lock holders without the need for additional distributed systems like ZooKeeper, Redis, Consul, or etcd.
To get started, install db-mutex via pip:
pip install db-mutex
Here's a simple example of how to use db-mutex for locking:
from db_mutex import Mutex
mutex = Mutex(dsn="postgres://user:pass@host/db", lock_name="nightly-report-job")
mutex.create_schema() # Creates the mutex_lock table if it doesn't exist; idempotent
with mutex.acquire(blocking=False) as acquired:
if acquired:
run_the_job()
else:
print("another instance is running the job")
For asynchronous jobs, the API is just as straightforward:
async with mutex.acquire_async(blocking=True, timeout=30):
await run_the_job_async()
Users have flexibility in how they supply connection information. For instance, connections can be made using a DSN string:
Mutex(dsn="postgres://user:pass@host:5432/dbname?sslmode=require", lock_name="job")
Or, if managing connection pools in larger applications, users can pass a connection pool or async pool to the Mutex instance:
from psycopg_pool import ConnectionPool
pool = ConnectionPool("postgres://...") # Managed by your application
mutex = Mutex(lock_name="nightly-report-job", pool=pool)
db-mutex supports MySQL as well, allowing users to provide a MySQL connection string with similar API usage:
mutex = Mutex(dsn="mysql://user:pass@host:3306/dbname", lock_name="nightly-report-job")
The core of db-mutex operates through a uniquely designed table structure that creates a record for each lock. The operational logic is simple yet effective—an attempt to insert a lock row allows only one holder thereby eliminating race conditions without the need for complicated advisory mechanisms.
Integrating with monitoring tools is straightforward. Users can implement their own metrics collection interface to track lock acquisition, release events, and other important metrics for effective job processing.
In summary, db-mutex offers an elegant solution for managing distributed locks in PostgreSQL and MySQL, with minimal overhead and maximum reliability, making it ideal for jobs requiring reliable single-instance execution.
Comments
0Start the conversation
Share the first comment.