pydistlock
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 (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 |
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 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.
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)
ttlis the lease length in seconds (default: the client'sdefault_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.waitis how long acquiring may wait:None(default) as long as the server allows,0not at all, otherwiseLockTimeoutafter that many seconds.- A
Lockis 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 ownLockGuard. - 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. Forpublish_forseconds 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.Noneuses the server's default (10 s),0wakes only the clients already waiting, and long windows are capped by the server.wait(timeout=None):Nonewaits as long as the server allows,0only checks whether the event is published right now, anything else raisesLockTimeout(aTimeoutError) when it runs out. Cancelling the task or pressing Ctrl-C withdraws the wait.- An
Eventobject remembers the last publication itswait()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()andset_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=0a wake-up lost that way is gone. Asetis never retried: if its connection fails,ConnectionFailedis 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 / 3the Rust client sends a lease extension, on its own threads. That is independent of Python, so a blocked event loop (time.sleepin 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 |
unchanged |
nothing at all changed |
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.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pydistlock-0.3.0.tar.gz | 121.1 kB | With provenance | Details for pydistlock-0.3.0.tar.gz |
Built distributions (wheels)
| File | Actions Reset | |||
|---|---|---|---|---|
| pydistlock-0.3.0-cp39-abi3-win_amd64.whl | CPython 3.9 | abi3 | Windows x86-64 | Details for pydistlock-0.3.0-cp39-abi3-win_amd64.whl |
| pydistlock-0.3.0-cp39-abi3-manylinux_2_28_aarch64.whl | CPython 3.9 | abi3 | Linux glibc 2.28+ ARM64 | Details for pydistlock-0.3.0-cp39-abi3-manylinux_2_28_aarch64.whl |
| pydistlock-0.3.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.3.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl |
| pydistlock-0.3.0-cp39-abi3-macosx_11_0_arm64.whl | CPython 3.9 | abi3 | macOS 11.0+ ARM64 | Details for pydistlock-0.3.0-cp39-abi3-macosx_11_0_arm64.whl |
| pydistlock-0.3.0-cp39-abi3-macosx_10_12_x86_64.whl | CPython 3.9 | abi3 | macOS 10.12+ x86-64 | Details for pydistlock-0.3.0-cp39-abi3-macosx_10_12_x86_64.whl |
Total release size: 8.8 MB
Release files / pydistlock-0.3.0.tar.gz
| Download URL | pydistlock-0.3.0.tar.gz |
|---|---|
| Size | 121.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a7fc737eaa673f1f7bba46e3add8c2306f46ce9114eee8188ff17ab3838375ef
|
|
BLAKE2b-256 checksum How to use checksums |
9b0c227380314a3cfca963eefc787db3f0c45711fac87968c284157755c19d3b
|
| 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 21, 2026.
Transparency logRelease files / pydistlock-0.3.0-cp39-abi3-win_amd64.whl
| Download URL | pydistlock-0.3.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 |
436af5d83fe5fdadeb3258ffb321e0750f92863b8687311dc637f1f25b445e14
|
|
BLAKE2b-256 checksum How to use checksums |
e22871142203227cc5a6b86b815ddd299a5eefb0ae03c1bece3f40cf20ac4256
|
| 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 21, 2026.
Transparency logRelease files / pydistlock-0.3.0-cp39-abi3-manylinux_2_28_aarch64.whl
| Download URL | pydistlock-0.3.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 |
a1d39e167c0de8714dc94f309244305cc2c570b18a2b7f9c83378813a1de7242
|
|
BLAKE2b-256 checksum How to use checksums |
c38ea6b19c1555a7a6d4d9272b4e6076b88a0cb746fe6875fe852bd1802aba0d
|
| 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 21, 2026.
Transparency logRelease files / pydistlock-0.3.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
| Download URL | pydistlock-0.3.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 |
07b91a456157633200fe3953d8492966d5110746bff0535636031309b892f670
|
|
BLAKE2b-256 checksum How to use checksums |
e47f266d5c1eaedfa6c2c9d975242c72019868db99b912e5226052770313d541
|
| 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 21, 2026.
Transparency logRelease files / pydistlock-0.3.0-cp39-abi3-macosx_11_0_arm64.whl
| Download URL | pydistlock-0.3.0-cp39-abi3-macosx_11_0_arm64.whl |
|---|---|
| Size | 1.6 MB |
| Tags | CPython 3.9 abi3 macOS 11.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
b1d47ba71fd4ff74a9fb0657e7b80211abcb1d0e6f02df2f5e2292a954015b2e
|
|
BLAKE2b-256 checksum How to use checksums |
2b0f5cee0dfcf488f11919d669e14e037cef0977d394e00c3d0a4606d2632abe
|
| 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 21, 2026.
Transparency logRelease files / pydistlock-0.3.0-cp39-abi3-macosx_10_12_x86_64.whl
| Download URL | pydistlock-0.3.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 |
5e00e47e975bef65d600dcb1edbb0f90f50d2b832cbfaadd404a2b04999e07f9
|
|
BLAKE2b-256 checksum How to use checksums |
8755bb816ed2cf49c5b5cfb1b5c31ed09faf6a21ddd387630f4da02c0c936dd7
|
| 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 21, 2026.
Transparency logSecurity for pydistlock 0.3.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.
Attestation for pydistlock-0.3.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 21, 2026.
Transparency logA 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.