Distributed Locking¶
RedisLock¶
RedisLock
¶
Redis-based distributed lock using SET NX EX.
Release uses an atomic Lua compare-and-delete so a stale holder can never
delete another owner's lock. The per-acquisition UUID is also exposed as a
fencing token via :attr:fencing_token for use in downstream writes that
need to guard against reordered operations.
L3 — ttl has no auto-renewal: if a handler runs longer than ttl,
the lock expires while the handler is still working, and a second
consumer can acquire the same key and start processing concurrently —
the exact condition this lock exists to prevent. There is no watchdog
here that periodically extends the TTL. Set ttl comfortably above
your worst-case handler time (including retries/timeouts on the handler
side), and for any downstream write that must not be applied twice even
under a lost lock, use :meth:fencing_token — pass it along with the
write and have the downstream store reject a token older than the one it
already recorded, so a "lock expired, second holder also wrote" race is
caught at the write itself rather than relying on the lock alone.
Source code in src/rabbitkit/locking.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
Methods:¶
fencing_token(key: str) -> str | None
¶
Return the lock value (UUID) for key as a fencing token.
None if this lock does not currently hold key.
acquire(key: str, timeout: float = 10.0) -> bool
¶
Acquire the lock. Waits up to timeout seconds (polling); timeout
<= 0 makes a single non-blocking attempt.
Source code in src/rabbitkit/locking.py
acquire_async(key: str, timeout: float = 10.0) -> bool
async
¶
Async variant of :meth:acquire (polls with asyncio.sleep).
Source code in src/rabbitkit/locking.py
LockMiddleware¶
LockMiddleware
¶
Bases: BaseMiddleware
Acquire a lock before processing, release after.
If lock cannot be acquired, nacks message with requeue=True. Default key_fn uses routing_key.
Source code in src/rabbitkit/locking.py
DistributedLock Protocol¶
DistributedLock
¶
Bases: Protocol
Protocol for distributed lock implementations.