Skip to main content

pydistlock

CI Release codecov PyPI Python

pip install pydistlock        # imports as `distlock`

The client for the distlock server. Distributed locks for Python: mutexes, read/write locks and semaphores, with leases that renew themselves, on top of the Rust client in crates/distlock-client. Async and blocking, one API.

from distlock import DistLockClient, ProcessingStatus

client = DistLockClient.from_url(
    "distlock://billing:s3cret@10.0.0.5:7878/billing?pool_size=5&default_ttl=30"
)

async with client.Mutex("nightly-report") as guard:
    if guard.status is ProcessingStatus.SUCCEEDED:
        return                                   # the previous holder already did the work
    ...                                          # the lease is renewed for you while this runs
    guard.set_status(ProcessingStatus.SUCCEEDED) # recorded when the block ends

Build from source

The package is a PyO3 extension (distlock._native, built with maturin) plus a pure-Python layer. One abi3 wheel serves Python 3.9 and newer.

cd python
python -m venv .venv && source .venv/bin/activate
pip install maturin pytest "pydantic>=2.5"
maturin develop                    # builds the Rust code and installs the package, editable
cargo build -p distlock-server     # the tests start the real server (from the repo root: ../target/debug)
pytest

maturin build --release makes a wheel. Only pydantic is needed at runtime. The tests need htpasswd (macOS has it; apache2-utils elsewhere) to create a users file with the repo's scripts/hash-password.sh; set DISTLOCK_SERVER_BIN to use a server binary from elsewhere.

Connecting

client = DistLockClient.from_url("distlock://client_id:password@host:port/namespace?pool_size=5&tls=false&default_ttl=30")
client = DistLockClient.from_env()                       # reads $DISTLOCK_URL
stats = await client.stats()                              # health: CPU %, memory, open files, clients, locks, users_md5 (or stats_sync())
client = DistLockClient(client_id="billing", password="s3cret", host="10.0.0.5", namespace="billing")
URL part Meaning Default
client_id:password a user from the server's users file (percent-encode @ : / %) required
host, port the server port 7878
/namespace prefix for every lock name (namespace:...), to keep applications apart none
pool_size TCP connections (1–256); they all share one session 4
default_ttl lease length in seconds for locks that do not set ttl 30
auth_mode 1: password is sent. 2 or v2: log in with an Ed25519 key, password holds the private key (see below) 1
min_version oldest server release accepted, checked right after logging in (ServerTooOld) 0.3.0
tls connect over TLS (the server needs a certificate; see the server README) false
tls_verify_ca require the certificate to chain to a trusted CA true
tls_verify_host require the certificate to name host (DNS name or IP) true
ca_file_path PEM file of CA certificates to trust instead of the built-in public roots none
ca_file_content the same CA certificates as PEM text (for a CA held in a secret or an environment variable); set this or ca_file_path, not both none

The two tls_verify_* flags give four modes:

tls_verify_ca tls_verify_host Mode Use it when
true true full verification normal production use
true false CA only the certificate is from your CA but does not name the address you connect to
false true name only self-signed certificate that names the host; any issuer is accepted, so it does not stop an attacker who presents their own certificate for that name
false false none encrypts, but does not authenticate the server: protects against passive eavesdropping only

A rejected certificate raises TlsError (a ConnectionFailed). All of these are also DistLockClient(...) keyword arguments (tls=True, tls_verify_host=False, ca_file_path=...). To trust your own CA:

DistLockClient.from_url("distlock://billing:s3cret@10.0.0.5:7878?tls=true&ca_file_path=/etc/distlock/ca.crt")
DistLockClient(client_id="billing", password="s3cret", host="10.0.0.5", tls=True,
               ca_file_content=os.environ["DISTLOCK_CA_PEM"])    # no file needed

from_url (and from_env) also take auth_mode, min_version, tls, tls_verify_ca, tls_verify_host, ca_file_path and ca_file_content as keyword arguments. A given argument beats the same setting in the URL, and giving ca_file_path drops a ca_file_content in the URL (and the other way round), so the URL can live in configuration and the CA in a secret:

DistLockClient.from_url(os.environ["DISTLOCK_URL"], tls=True, ca_file_content=os.environ["DISTLOCK_CA_PEM"])

In a URL, percent-encode a ca_file_content value (urllib.parse.quote(pem)). The host in the URL must be in the server certificate's subjectAltName. Making the CA and the server certificate (scripts/tls/*.sh) is covered in the server README, with a table of error messages.

Logging in with a key

auth_mode=2 sends no password: the private key (the URL's password slot, 43 characters) signs a nonce the server sends, and the server checks it against the public key in users.json. Make a pair:

pip install "pydistlock[keys]"
python -m distlock.keys --client-id billing --identifier laptop
from distlock import generate_keypair, public_key_for
private, public = generate_keypair()          # 43 characters each; `public` goes into users.json
client = DistLockClient.from_url(f"distlock://billing:{private}@10.0.0.5:7878?auth_mode=v2")

The private key is a secret: read it from the environment or a secret store, not from source or a command line. A wrong key, an unknown user and an expired key all raise AuthenticationError. A signature does not protect the session that follows, so use TLS too. The server side is in the server README.

URLs are parsed with urllib and validated with pydantic (ClientSettings); mistakes raise ConfigError with a message that never contains the password.

Creating a client does no I/O. The pool connects the first time a lock is acquired (or on await client.connect(), to fail fast on bad credentials). The server assigns a session id when the pool is set up, visible as client.session_id; all connections of the pool share it, so any connection can carry any request, and a dropped connection is re-established and the session re-joined without losing locks.

Locks

lock = client.Lock("name", ttl=None, namespace=None, mode=LockMode.WRITE, wait=None)

client.RLock("name")      # shared: many readers at once, never alongside a writer
client.WLock("name")      # exclusive: blocks and is blocked by every reader and writer of that name
client.Mutex("name")      # exclusive, in its own space: a mutex "x" and an RLock/WLock "x" do not conflict
client.Semaphore("name", capacity=5, permits=1)
  • ttl is the lease length in seconds (default: the client's default_ttl). It is renewed in the background for as long as you hold the lock, so it is a liveness bound, not a time limit on your work.
  • wait is how long acquiring may wait: None (default) as long as the server allows, 0 not at all, otherwise LockTimeout after that many seconds.
  • A Lock is a reusable definition. Enter it as many times as you like, from as many tasks or threads as you like; each entry gets its own grant and its own LockGuard.
  • Read and write locks are fair (FIFO): a waiting writer is not starved by later readers.
  • A semaphore's first acquirer defines its capacity; it disappears when its last holder and waiter are gone.
async with lock as guard: ...                 # or:  with lock as guard: ...   (blocking)
guard = await lock.acquire(wait=5)            # raises LockTimeout; guard.release() when done
guard = await lock.try_acquire()              # None if taken right now
guard = lock.acquire_sync() / lock.try_acquire_sync()

Cancellation is safe: cancelling a waiting acquire (a wait_for timeout, a cancelled task) withdraws the request from the server, so it can never be granted to nobody; Ctrl-C interrupts a blocking acquire the same way.

Events

A named broadcast, like asyncio.Event with a limited memory: many clients wait, one sets, and the set says how many it woke.

event = client.Event("deploy-finished")
value = await event.wait(timeout=60)               # the setter's value, or None; LockTimeout after 60 s

woken = await client.Event("deploy-finished").set("v1.2.3")
assert woken == number_of_clients_waiting_right_now
  • set(value=None, *, publish_for=None): publish window. For publish_for seconds after a set, the event counts as published: a wait that starts in that window returns at once with the same value. After it the event is gone and waiters wait for the next set. None uses the server's default (10 s), 0 wakes only the clients already waiting, and long windows are capped by the server.
  • wait(timeout=None): None waits as long as the server allows, 0 only checks whether the event is published right now, anything else raises LockTimeout (a TimeoutError) when it runs out. Cancelling the task or pressing Ctrl-C withdraws the wait.
  • An Event object remembers the last publication its wait() returned and only returns newer ones, so a loop on one object does not spin while a publication is still inside its window:
event = client.Event("tick")
while True:
    value = await event.wait()          # never the same publication twice

Use a fresh Event, event.reset() or wait(after=...) to see an earlier publication again; event.last_id is the id of the last one returned.

  • Blocking forms: wait_sync() and set_sync().
  • Events are separate from locks: an event and a lock with the same name do not interact. Namespaces apply as for locks.
  • Delivery. A wait survives dropped connections. A set made while this client is disconnected cannot be delivered then, but the client asks again after it reconnects and is answered from the publish window, so use a window longer than a reconnect (the server default is 10 s) for events that must not be missed. With publish_for=0 a wake-up lost that way is gone. A set is never retried: if its connection fails, ConnectionFailed is raised and whether it took effect is unknown.

The guard

guard.status the previous holder's ProcessingStatus (SUCCEEDED, FAILED, STORED, or ABANDONED), else None
guard.previous the same with set_by_token and age
guard.set_status(status, ttl=None) leave your outcome for the next holder; applied when the block ends
guard.fencing_token strictly increasing across all grants; hand it to what you protect and reject older ones
guard.lost / guard.check() / await guard.wait_lost() has the lease been lost?
await guard.release() / guard.release_sync() release early (idempotent)
await guard.extend(ttl) lengthen the lease beyond what renewal gives you (rarely needed)

Statuses: only mutex and write holders can set one (InvalidArgument otherwise); readers and semaphore holders can read it. Releasing without set_status leaves the previous status untouched. ABANDONED is assigned by the server when a holder's lease expired, or its session ended, while it still held the lock; you can read it but not set it. A status stays readable for the server's state_ttl (10 minutes by default; set_status(..., ttl=...) overrides it).

If the lease is lost while you hold the lock (the server restarted, a long network partition), guard.lost turns true, and leaving the block raises LockLost (unless another exception is already propagating, which is never masked). Call guard.check() before irreversible steps of a long job.

Errors

Everything derives from DistLockError. Where a standard exception fits, it is also that: LockTimeout is a TimeoutError, ConnectionFailed a ConnectionError, InvalidArgument/ConfigError a ValueError.

exception when
ConfigError bad URL or settings
AuthenticationError wrong client id / password
ConnectionFailed server unreachable or not ready (the pool keeps retrying in the background)
LockTimeout / LockBusy waited out (a lock not obtained, or an event not set, in time) / wait=0 and it was taken
LockLost the lease expired before release
MaintenanceError a maintenance command could not be carried out; nothing changed
SessionLost the server forgot the session; the client logs in again by itself, but old locks are gone
ClientClosed the client was closed
InvalidArgument / ServerError rejected argument / anything else the server reports

Staying alive

  • Leases renew themselves for as long as a guard is held: every ttl / 3 the Rust client sends a lease extension, on its own threads. That is independent of Python, so a blocked event loop (time.sleep in async code), a CPU-bound loop holding the GIL, or a client object that went out of scope cannot make a lease lapse. Each renewal attempt is bounded and retried on another connection, so one hung connection cannot eat a lease either.
  • Heartbeats keep the pool's connections up. Every connection pings the server at half the server's ping_interval (default 10 s). A connection that hears nothing for a full interval is considered dead and replaced, and TCP keepalive backs this up at the OS level.
  • The pool repairs itself. Dropped connections are re-established with jittered backoff, rejoining the same session (your locks are re-verified against the server's view); if the server forgot the session (a restart), the client logs in again and any locks held through the old session report lost.
client.connections       # pool connections up right now
client.reconnects        # connections re-established since the start
await client.ping()      # round-trip time to the server, in seconds (client.ping_sync() when blocking)

If every connection is down for more than ten seconds, calls raise AuthenticationError when the server refuses the credentials on re-login (a rotated password), and ConnectionFailed (with the underlying reason) otherwise.

Maintenance

report = await client.maintenance.reset_users()      # or client.maintenance.reset_users_sync()

Tells the server to re-read its users file (DISTLOCK_USERS_FILE) and swap it in. Logins are never refused or delayed while this happens (the server swaps an immutable snapshot atomically). Users that are gone from the file or now disabled are thrown out: their sessions end, their locks are released (the next holder sees ABANDONED, after the server's lock-delay) and the server closes every one of their TCP connections, including yours if you removed yourself: you still get the report, with report.invoker_dropped set, and after that your calls raise AuthenticationError until the user is added back, which this client then notices by itself. Users added or re-enabled can log in; a changed password applies to new logins only.

ResetUsersReport
added, removed, disabled, enabled, password_changed counts of users in each category (names are in the server log, not in the reply)
sessions_closed, connections_closed what was thrown out
invoker_dropped you were among them
users_md5 MD5 of the users file now in force on the server (32 hex characters; "" from a server that does not report it). The server logs it too. Compare it with the hash of the file you rolled out
unchanged nothing at all changed (the hash is not counted as a change)

If the file cannot be loaded you get MaintenanceError, nothing changes, and the old users stay in force. Calling it again is always safe. There is no authorization beyond being logged in yet, so any client can send it; it can only make the server re-read a file the administrator controls.

Lifecycle

async with DistLockClient.from_url(url) as client:   # connects now; on exit ends the session
    ...                                              # (the server releases every lock it still holds)
client.close_sync()                                  # or: await client.close()

Dropping the last reference to a guard releases its lock (without a status); a client that is simply dropped stops its pool and leaves its session to expire on the server.

Names on the wire

The server sees namespace:family:name with family one of mutex, rw, sem, or event. That is how a mutex and a read/write lock with the same name stay separate, and how namespaces keep applications apart. : is therefore not allowed in a namespace (it is fine inside a lock name).

Metadata

Release files for pydistlock 0.5.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 pydistlock 0.5.0
File Size Uploaded Provenance Actions
pydistlock-0.5.0.tar.gz 150.8 kB With provenance Details for pydistlock-0.5.0.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for pydistlock 0.5.0
File Actions
pydistlock-0.5.0-cp39-abi3-win_amd64.whl CPython 3.9 abi3 Windows x86-64 Details for pydistlock-0.5.0-cp39-abi3-win_amd64.whl
pydistlock-0.5.0-cp39-abi3-manylinux_2_28_aarch64.whl CPython 3.9 abi3 Linux glibc 2.28+ ARM64 Details for pydistlock-0.5.0-cp39-abi3-manylinux_2_28_aarch64.whl
pydistlock-0.5.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.9 abi3 Linux glibc 2.17+ x86-64 Details for pydistlock-0.5.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
pydistlock-0.5.0-cp39-abi3-macosx_11_0_arm64.whl CPython 3.9 abi3 macOS 11.0+ ARM64 Details for pydistlock-0.5.0-cp39-abi3-macosx_11_0_arm64.whl
pydistlock-0.5.0-cp39-abi3-macosx_10_12_x86_64.whl CPython 3.9 abi3 macOS 10.12+ x86-64 Details for pydistlock-0.5.0-cp39-abi3-macosx_10_12_x86_64.whl

Total release size: 8.9 MB

Release files / pydistlock-0.5.0.tar.gz

Download URL pydistlock-0.5.0.tar.gz
Size 150.8 kB
Tags Source
SHA-256 checksum
How to use checksums
727abc7f50d3550e193ac7d2fbc526a9dde04ec70a1744910f8e4823a57d1343
BLAKE2b-256 checksum
How to use checksums
63284430f12a18bb4a1866d95015a8d3d48b0866eec9e1d149c1c4abcdcaba70
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

Release files / pydistlock-0.5.0-cp39-abi3-win_amd64.whl

Download URL pydistlock-0.5.0-cp39-abi3-win_amd64.whl
Size 1.8 MB
Tags CPython 3.9 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
a8a254797f8d8b3ddd1f1925c80a66498560817f1bb5dbf42a8ba560dd425f5c
BLAKE2b-256 checksum
How to use checksums
a5c5a24bfebaffc43736cfdb43d72d517a2cc1888055b195e02245a3b961cf36
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

Release files / pydistlock-0.5.0-cp39-abi3-manylinux_2_28_aarch64.whl

Download URL pydistlock-0.5.0-cp39-abi3-manylinux_2_28_aarch64.whl
Size 1.7 MB
Tags CPython 3.9 Linux glibc 2.28+ ARM64 abi3
SHA-256 checksum
How to use checksums
4777624ee4d172439d2130aaf7a742390bfef65c663078d775e0d1ec9061f466
BLAKE2b-256 checksum
How to use checksums
d0b507653f359a35164edc28ed8a9df0d45bed30cd70e4cf69957f31c886ae49
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

Release files / pydistlock-0.5.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL pydistlock-0.5.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 1.8 MB
Tags CPython 3.9 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
5b839a40cc97111d5c5b0ce81ba25c2405671561ace89ecd7e1fd458210ca121
BLAKE2b-256 checksum
How to use checksums
f4ad7ff6d6a97c9347fe1284d5b718af1c243c719ad41f2eafb51a75dc9aaabf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

Release files / pydistlock-0.5.0-cp39-abi3-macosx_11_0_arm64.whl

Download URL pydistlock-0.5.0-cp39-abi3-macosx_11_0_arm64.whl
Size 1.7 MB
Tags CPython 3.9 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
864d87acec960e9a95e420cb26d68afb6df538b2b84ed7851cdff0676613cb49
BLAKE2b-256 checksum
How to use checksums
8138078c8d5cd99518d939561e4455d516813adebff52cb3f9210bcfcd179b0c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

Release files / pydistlock-0.5.0-cp39-abi3-macosx_10_12_x86_64.whl

Download URL pydistlock-0.5.0-cp39-abi3-macosx_10_12_x86_64.whl
Size 1.7 MB
Tags CPython 3.9 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
7df0b180a40f37225f6f99d539b5489e784ee2fe0c292bd2a56882805c8e506d
BLAKE2b-256 checksum
How to use checksums
51ea8cb76816b12c6db65537cea34653f3108af0de58c61338825c2c8f2cb3c7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

Security for pydistlock 0.5.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.

Full provenance

All 6 files in this release have been uploaded with provenance metadata.

Select from 6 files

Attestation for pydistlock-0.5.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

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