Skip to main content

django-database-locks

tests Test coverage status Current version on PyPi monthly downloads PyPI - Python Version PyPI - Django Version

Distributed locks for Django using DB (MySQL/Postgres)

Given the limitation that Percona Cluster does not support MySQL locks, this app implements locks using select_for_update() (row locks).

Installation

pip install django-database-locks

Usage

django-database-locks exposes one single the lock contextmanager and the locked decorator.

The locked decorator will wrap a django management command (subclasses of django.core.management.base.BaseCommand) or any function with the lock contextmanager:

from django.core.management.base import BaseCommand

from database_locks import locked

@locked
class Command(BaseCommand):
    ...
    def handle(self, *args, **options):
        self.stdout.write('Got the lock')
from database_locks import locked

class SomeClass:
  def non_locked(self):
    pass

  @locked
  def locked(self):
    print('got lock')
from database_locks import lock

class SomeClass:
  def non_locked(self):
    pass

  def locked(self):
    with lock():
        print('got lock')

Docs

Both lock and locked have the same optional args:

:param lock_name: unique name in DB for this function
:param timeout: numbers of seconds to wait to acquire lock
:param lock_ttl: expiration timer of the lock, in seconds (set to None to infinite)
:param locked_by: owner id for the lock (if lock is active but owner is the same, returns acquired)
:param auto_renew: if set to True will re-acquire lock (for `lock_ttl` seconds) before `lock_ttl` is over.
                   auto_renew thread will raise LockException (via SIGUSR1) on the main thread in case
                   re-acquiring keeps failing (see `max_failures`)
:param retry: retry every `retry` seconds acquiring until successful. set to None or 0 to disable.
:param lost_lock_cb: callback function when lock is lost (when re-acquiring). defaults to raising LockException
:param max_failures: number of consecutive renew failures (DB unreachable) tolerated before giving up the
                      lock (default `1`, i.e. no tolerance - same as before this option existed). A renewal
                      that fails because someone else genuinely owns the lock always gives up immediately,
                      regardless of this value.

There are also the following options you can specify in the project settings.py

  • DATABASE_LOCKS_STATUS_FILE: file that will be updated with the lock status (default None). Useful when you have multiple shared-lock processes, to quickly inspect which one has the lock.

  • DATABASE_LOCKS_ENABLED: set to False to globally disable locks (default True)

  • DATABASE_LOCKS_DEFAULT_TTL: global lock TTL value (default 60) which is ignored when lock_ttl is specified

  • DATABASE_LOCKS_DEFAULT_TTL_RENEW: number of seconds to renew lock before TTL expires (default 45)

max_failures invariant

If you use max_failures > 1, keep:

max_failures * (lock_ttl - lock_ttl_renew) < lock_ttl

i.e. the total tolerated outage must fit inside the lease, with margin - a warning is logged at lock-acquisition time if it doesn’t. Example: lock_ttl=120, lock_ttl_renew=100 -> renew is attempted every 20s, so max_failures=3 tolerates roughly 60s of DB unavailability before giving up the lock.

Clock requirements

Lock expiry is evaluated in SQL against the database’s clock (NOW()), not the application server’s clock, so contending processes share a single time source regardless of NTP drift between them. The Lock.active property still uses the local clock and is for admin/debug convenience only - it is not used to decide acquisition.

Galera / multi-master caveats

SELECT ... FOR UPDATE row locks are node-local on a synchronous multi-master cluster such as Galera/Percona XtraDB Cluster: a transaction on one node does not block a conflicting transaction on another node. Galera is optimistic - conflicting writes are only caught at commit time, surfacing as a certification failure reported to the client as a regular MySQL deadlock (error 1213). Two processes on two different nodes can both believe they hold the row lock; one of them loses at commit and gets 1213 (handled internally by retrying acquisition, see timeout/retry).

Also, with the default wsrep_sync_wait=0, a node may serve a read from a snapshot that has not yet applied a write already committed elsewhere in the cluster - so a process can observe an expired lease that another node just renewed, and (incorrectly) treat the lock as free.

Before relying on this library on a Galera-like cluster, determine whether your setup is:

  • Single-writer (e.g. all writes routed to one node via ProxySQL): everything serialises there, row locks behave as this library assumes, no extra work needed.

  • Multi-writer (each node accepts writes locally): set wsrep_sync_wait=1 for the lock queries (at least), and expect MySQL error 1213 on acquire as normal operation - this library retries the acquire loop on db.Error for exactly this reason.

Testing

Install the development dependencies with uv sync --group dev. The GitHub Actions matrix tests Python 3.9 with Django 4.2, Python 3.10 with Django 5.2, and Python 3.12 and 3.14 with Django 6.1, using both MySQL and PostgreSQL.

For a local run with the latest matrix versions, start MySQL and PostgreSQL containers:

docker run -d –name locks-test

-p 8877:3306 -e MYSQL_ROOT_PASSWORD=root mysql:8.4

docker run -d –name locks-test-psql

-p 8878:5432 -e POSTGRES_PASSWORD=postgres postgres:15

List environments with uv run tox -l, then run the matching Python/Django/database environment:

uv run tox -e py39-dj42-mysql # or uv run tox -e py310-dj52-postgresql # Python 3.12 and 3.14 use Django 6.1 uv run tox -e py312-dj61-mysql

Metadata

Release files for django-database-locks 1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-database-locks 1.0
File Size Uploaded Provenance Actions
django_database_locks-1.0.tar.gz 12.0 kB Without provenance Details for django_database_locks-1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-database-locks 1.0
File Interpreter ABI Platform Actions
django_database_locks-1.0-py3-none-any.whl Python 3 none any Details for django_database_locks-1.0-py3-none-any.whl

Total release size: 23.0 kB

Release files / django_database_locks-1.0.tar.gz

Download URL django_database_locks-1.0.tar.gz
Size 12.0 kB
Tags Source
SHA-256 checksum
How to use checksums
e3731196c453c7f65c915138f2d890c7ce25d7467bb9d8c3196abdf015a69897
BLAKE2b-256 checksum
How to use checksums
e6f3039c6c7250f1bb601779964a393722255841ee260864ec3903554a0c5898
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.1

Release files / django_database_locks-1.0-py3-none-any.whl

Download URL django_database_locks-1.0-py3-none-any.whl
Size 11.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0afd1d32b8cb29ac1cd55634ef3bb6d1c173166f9e749263a7cf78f20e61ee3d
BLAKE2b-256 checksum
How to use checksums
cd558c1af04374f18f3650e7c39bdf8d83699468def0e9e79f2922609c796a3c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.1

Security for django-database-locks 1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page