Easy distributed locking using PostgreSQL Advisory Locks.
Project description
Introduction
PALs makes it easy to use PostgreSQL Advisory Locks to do distributed application level locking.
Do not confuse this type of locking with table or row locking in PostgreSQL. It’s not the same thing.
Distributed application level locking can be implemented by using Redis, Memcache, ZeroMQ and others. But for those who are already using PostgreSQL, setup & management of another service is unnecessary.
Usage
Install with:
pip install PALs
Then usage is as follows:
import datetime as dt
import pals
# Think of the Locker instance as a Lock factory.
locker = pals.Locker('my-app-name', 'postgresql://user:pass@server/dbname')
lock1 = locker.lock('my-lock')
lock2 = locker.lock('my-lock')
# The first acquire works
assert lock1.acquire() is True
# Non blocking version should fail immediately
assert lock2.acquire(blocking=False) is False
# Blocking version should fail after a short time
start = dt.datetime.now()
acquired = lock2.acquire(acquire_timeout=300)
waited_ms = duration(start)
assert acquired is False
assert waited_ms >= 300 and waited_ms < 350
# Release the lock
lock1.release()
# Non-blocking usage pattern
if not lock1.acquire(blocking=False):
# Aquire returned False, indicating we did not get the lock.
return
try:
# do your work here
finally:
lock1.release()
# If you want to block, you can use a context manager:
try:
with lock1:
# Do your work here
pass
except pals.AcquireFailure:
# This indicates the aquire_timeout was reached before the lock could be aquired.
pass
Docs
Just this readme, the code, and tests. It a small project, should be easy to understand.
Feel free to open an issue with questions.
Running Tests Locally
Setup Database Connection
We have provided a docker-compose file to ease running the tests:
$ docker-compose up -d $ export PALS_DB_URL=postgresql://postgres:password@localhost:54321/postgres
Run the Tests
With tox:
$ tox
Or, manually (assuming an activated virtualenv):
$ pip install -r requirements/dev.txt $ pip install -e . $ pytest pals/tests/
Lock Releasing & Expiration
Unlike locking systems built on cache services like Memcache and Redis, whose keys can be expired by the service, there is no faculty for expiring an advisory lock in PostgreSQL. If a client holds a lock and then sleeps/hangs for mins/hours/days, no other client will be able to get that lock until the client releases it. This actually seems like a good thing to us, if a lock is acquired, it should be kept until released.
But what about accidental failures to release the lock?
If a developer uses
lock.acquire()
but doesn’t later calllock.release()
?If code inside a lock accidentally throws an exception (and .release() is not called)?
If the process running the application crashes or the process’ server dies?
PALs helps #1 and #2 above in a few different ways:
Locks work as context managers. Use them as much as possible to guarantee a lock is released.
Locks release their lock when garbage collected.
PALs uses a dedicated SQLAlchemy connection pool. When a connection is returned to the pool, either because a connection
.close()
is called or due to garbage collection of the connection, PALs issues apg_advisory_unlock_all()
. It should therefore be impossible for an idle connection in the pool to ever still be holding a lock.
Regarding #3 above, pg_advisory_unlock_all()
is implicitly invoked by PostgreSQL whenever a
connection (a.k.a session) ends, even if the client disconnects ungracefully. So if a process
crashes or otherwise disappears, PostgreSQL should notice and remove all locks held by that
connection/session.
The possibility could exist that PostgreSQL does not detect a connection has closed and keeps
a lock open indefinitely. However, in manual testing using scripts/hang.py
no way was found
to end the Python process without PostgreSQL detecting it.
See Also
Changelog
0.3.2 released 2021-02-01
Support shared advisory locks (thanks to @absalon-james) (ba2fe21)
0.3.1 released 2020-09-03
readme: update postgresql link (260bf75)
Handle case where a DB connection is returned to the pool which is already closed (5d730c9)
Fix a couple of typos in comments (da2b8af)
readme improvements (4efba90)
CI: fix coverage upload (52daa27)
Fix CI: bump CI python to v3.7 and postgres to v11 (23b3028)
0.3.0 released 2019-11-13
Enhancements
Project Cleanup
adjust flake8 ignore and other tox project warning (ee123fc)
fix comment in test (0d8eb98)
Additional readme updates (0786766)
update locked dependencies (f5743a6)
Remove Python 3.5 from CI (b63c71a)
Cleaned up the readme code example a bit and added more references (dabb497)
Update setup.py to use SPDX license identifier (b811a99)
remove Pipefiles (0637f39)
move to using piptools for dependency management (af2e91f)
0.2.0 released 2019-03-07
Fix misspelling of “acquire” (737763f)
0.1.0 released 2019-02-22
Use
lock_timeout
setting to expire blocking calls (d0216ce)fix tox (1b0ffe2)
rename to PALs (95d5a3c)
improve readme (e8dd6f2)
move tests file to better location (a153af5)
add flake8 dep (3909c95)
fix tests so they work locally too (7102294)
get circleci working (28f16d2)
suppress exceptions in Lock __del__ (e29c1ce)
Add hang.py script (3372ef0)
fix packaging stuff, update readme (cebd976)
initial commit (871b877)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file PALs-0.3.2.tar.gz
.
File metadata
- Download URL: PALs-0.3.2.tar.gz
- Upload date:
- Size: 14.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.12.1 pkginfo/1.4.2 requests/2.21.0 setuptools/42.0.2 requests-toolbelt/0.9.1 tqdm/4.28.1 CPython/3.6.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2cece09380fd67635cb6117e182d99cd716904430ca76f516553e306780bc519 |
|
MD5 | 6f6ff2861fe45bf7bcf05e175da9fde2 |
|
BLAKE2b-256 | 0194c0267ccf5df4d2ef7af03781187394d108e8e3a91550b4744b9a4aeecc0e |
File details
Details for the file PALs-0.3.2-py2.py3-none-any.whl
.
File metadata
- Download URL: PALs-0.3.2-py2.py3-none-any.whl
- Upload date:
- Size: 8.6 kB
- Tags: Python 2, Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.12.1 pkginfo/1.4.2 requests/2.21.0 setuptools/42.0.2 requests-toolbelt/0.9.1 tqdm/4.28.1 CPython/3.6.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1f9a20f9e40fbaa73468af6a8d362ac05aa330ef352afa5ac4286e76b89e6618 |
|
MD5 | 65a92bdc10d943528b2710bbeec47d47 |
|
BLAKE2b-256 | bda10d644850a6750782e5698fdf140d35dbc9ee08cd129d1ba7f94984c01d53 |