Repository navigation
Limitations
A lock without leaseTime is renewed by Redisson in the background. If Redis becomes unreachable
while the method runs, or the JVM itself stops for longer than the
watchdog timeout, for example in a long garbage-collection pause or a suspended
container, renewal stops and the key expires after the watchdog timeout (30 seconds by default) while
the method keeps running. Another instance can then take the lock. The running method is not told.
The release logs the same WARN as an outrun fixed lease, with fixed lease none
in place of the lease, or release failed if Redis is still unreachable.
With Redisson's defaults (a 3-second timeout, 4 retries), a lock acquire or release blocks about 3
seconds when Redis stops answering, and so does a semaphore acquire of a key already set up; the
first semaphore acquire of a key, and a permit release, block about 20 seconds. A call that timed
out can still take effect once Redis answers again: a lock that nobody holds stays until the
watchdog timeout (30 seconds), a permit that nobody holds until its lease ends (5 minutes by
default). With replicas (Sentinel or Cluster), Redisson also waits up to slavesSyncTimeout (1
second by default) for a replica to confirm each write of a lock or permit, and retries, so these
times can be longer.
An acquire with a waitTime listens on a Redis pub/sub channel for its key, and Redisson's defaults
allow 250 such channels per instance (subscriptionConnectionPoolSize 50 times
subscriptionsPerConnection 5). When more busy keys are waited on at once, or Redis answers slowly,
an acquire can throw Redisson's RedisTimeoutException ("Unable to acquire connection for
subscription") instead of returning "not acquired", so onFailure does not apply. With Redisson's
defaults, a lock or semaphore acquire throws once about 5 to 9 seconds pass without a free channel;
if its waitTime runs out first, it returns "not acquired". An acquire interrupted while waiting
returns at once, but Redisson keeps its channel until the key is next released or expires, or the
wait would have ended. For a lock, that is at most the watchdog timeout, 30 seconds by default, if
the holder took the lock without leaseTime, and up to the rest of the holder's leaseTime
otherwise. Interrupted waits therefore count against the limit for a while too. Raise the two
settings if you wait on many keys at once.
A lock key carries an expiry, so Redis may evict a lock that is still held when memory runs short
under a volatile-* or allkeys-* maxmemory-policy; semaphore keys can go under allkeys-*. Run
the Redis that holds locks with maxmemory-policy noeviction. A semaphore is two Redis keys, <key>
and {<key>}:timeout; if only one of them is lost, for example to an operator's DEL, the count
can rise above permits until an instance restarts or both keys are deleted.
Redis keeps no queue of waiters. When a lock or a permit is released, Redisson wakes one waiter in each instance, and whoever reaches Redis first gets in. Within one instance, waiters get in in the order they started waiting. Across instances that order is not kept (in a test, the later of two waiting writers won 14 times out of 30), and a caller that arrives at that moment can get in ahead of every waiter. After an interrupted wait, the waiter woken can be the abandoned one; see the next section.
When an acquire is interrupted while it waits, for example by Future.cancel(true) or an executor's
shutdownNow(), the first release of that key afterwards can wake the abandoned wait instead of a
live one. Another call waiting on the same key in the same instance is then not woken: it keeps
waiting although the lock or permit is free, and tries again only when a holder's lease would have
ended or its own waitTime runs out, whichever comes first. If its waitTime runs out first, it
gets "not acquired", so onFailure applies. A lock held without leaseTime has the 30-second
watchdog timeout as its lease, and a permit has 5 minutes by default, so a shorter waitTime runs
out first. Waiters in other instances get in as usual. In a test with a 5-second waitTime, such a
waiter gave up after 5 seconds although the lock was released after 0.3 seconds; without the
interrupt it got in after 0.3 seconds. Redisson 4.8.0 does the same on its own when a waiting
tryLockAsync is cancelled. Avoid interrupting threads that wait for a lock or a permit.
Under contention, Redisson 4.8 can leave a permit acquire with a waitTime unanswered, when the
wait time runs out at the moment a permit is released. In a test with 32 callers waiting 1 to 20 ms
for one permit, that happened to 4 of about 86,000 acquires. Locksmith stops such a wait 30 seconds
after its wait time has run out, logs one WARN (Permit [...] wait did not end within 30000ms after its wait time of ...ms; ...) and treats it as not acquired, so onFailure applies; the call
returns 30 seconds late. Redisson keeps the semaphore's channel subscribed afterwards, which counts
against the limit in Many keys waited on at once. An acquire
without waitTime is not affected.
One script every 10 seconds renews all the locks without leaseTime that an instance holds.
Redisson 4.0 to 4.8 start another renewal timer each time an instance goes from holding no such
lock to holding one, and the earlier timers keep running while any such lock is held. An instance
that takes locks one after another, such as a worker loop, therefore sends many more renewal
scripts than it needs: in a test, one thread that held a lock for 100 ms at a time sent 150 renewal
scripts per second after four minutes. No lock is lost by this. The extra timers end once the
instance holds no such lock for 10 seconds, and a lock with a leaseTime is never renewed. While
Redis does not answer, each of these timers logs its own Can't update locks ... expiration ERROR.
A READ lock is granted whenever no WRITE lock is held, even while a writer waits, so a steady
stream of readers can keep a writer out. In a test, a writer's 5-second wait ran out every time
against 8 overlapping readers, and it got in after 2 to 3 seconds against 4. Use READ/WRITE
where reads come with gaps, and give writers a generous waitTime.
Each READ release runs a script that visits every reader holding the key, and Redis serves nothing
else while it runs: about 0.1 ms with 10 readers, 0.35 ms with 100 and 1.75 ms with 1,000. Keep the
readers of one key in the hundreds at most.
In two nested cases on one thread, Redisson 4.7 and 4.8 stop renewing the outer lock, which then expires while its method still runs, so another instance can take the key:
- an outer lock without
leaseTimeand a nested acquisition of the same key with aleaseTime: once the nested lock is released, the key expires when the nested lease runs out; - a
READlock taken inside aWRITElock of the same key: once theREADlock is released, theWRITElock is no longer renewed.
Give every method that can nest on one key the same leaseTime setting, and do not take READ
inside WRITE on one key. A WRITE inside a READ of the same key is never acquired: Redisson
does not upgrade a read lock.
When two instances run the same scheduled job and one finishes before the other starts, both run it: in a test, two instances whose schedules fired 20 ms apart both ran a 5 ms job. Make such a job idempotent, or record when it last ran and skip it if that was recent.
Redis Cluster keeps keys that share a hash tag, such as {42} in order:{42}, in one slot, and
Redisson relies on that for the companion keys of a lock or semaphore. On a Cluster client, a full
key that contains { without forming a tag (a } after it with at least one character between), or
that contains } but no {, throws LocksmithConfigurationException before anything is sent, and
the method does not run; Redis Cluster would otherwise reject the lock's release, leaving the lock
taken until it expires, and every call of the semaphore. Keep braces out of keys built from input,
or use them as a tag. Other Redis setups accept such keys.
The annotations work only on calls that go through the Spring proxy. A call on this from inside
the same bean bypasses the proxy and runs without a lock or permit, exactly as with
@Transactional.
Locksmith registers Spring's auto-proxy creator itself when the context has none, so the annotations
work with or without spring-boot-starter-aspectj and AspectJ, and whatever spring.aop.auto and
spring.aop.proxy-target-class say. With interface proxies (spring.aop.proxy-target-class=false
and no AspectJ, or spring.aop.auto=false when nothing else, such as Spring Boot's transaction
support, asks for class proxies), a bean that implements an interface is reachable only through its
interfaces. Put the annotation on the interface method, or on the method that implements an
interface method. A method that is on no interface is not intercepted in that mode.
A Spring Data repository hands a call to a fragment method on to the fragment's implementation,
which is a Spring bean of its own. When the annotation sits on the fragment interface, the
repository and that bean both carry it, so the call is coordinated twice. A lock is then taken again
by the same thread, which is harmless, but a semaphore takes two permits: with permits = "1",
every such call fails. Put the annotation on the method in the repository interface, or on the
method of the fragment's implementation class, instead; the call is then coordinated once.
Startup fails with a LocksmithConfigurationException for an annotated method that returns a
reactive type (Mono, Flux, any org.reactivestreams.Publisher or
java.util.concurrent.Flow.Publisher, Kotlin's Flow and Deferred, and any other type Spring's
ReactiveAdapterRegistry adapts, such as RxJava's Single), for a Kotlin suspend function, and
for a Future, a CompletionStage, such as CompletableFuture or ForkJoinTask, or a Kotlin
Job, such as the one launch returns, unless the method or the bean's class is @Async. The
work of those can outlive the method, and the lock is released when the method returns. With
@Async, the lock covers the whole body on the worker thread, and the method must return void,
Kotlin Unit, Future or CompletableFuture, the only types Spring's @Async supports; any
other return type, such as CompletionStage, ForkJoinTask, a CompletableFuture subclass or
String, fails startup, because Spring would fail every call. See
methods that return a future.
Startup also fails for the return types Spring MVC runs after the method returns: Callable,
WebAsyncTask, DeferredResult, StreamingResponseBody, ResponseBodyEmitter with its subclasses
such as SseEmitter, a functional endpoint's AsyncServerResponse, or its EntityResponse of a
CompletionStage or a reactive type, and a ResponseEntity, or a subclass of it, of a
StreamingResponseBody, an emitter, a CompletionStage or a reactive type.
This holds on every bean, not only on controllers: a locked method that returns a Callable holds
the lock while it builds the Callable, not while the Callable runs. Put the annotation on the
method that does the work, such as a service method called inside the Callable. An HttpEntity,
or a ResponseEntity of anything else, such as a Callable, starts: Spring MVC runs no work from it
after the method returns.
The check reads the return type as Spring MVC does, with the type variables of the bean's class. A
generic base controller's ResponseEntity<T>, in a controller that extends it with SseEmitter for
T, fails startup like a ResponseEntity<SseEmitter>, and so does a T return type that the
controller binds to one of the types above.
Spring MVC goes by the value a handler actually returns, which a wider declared type hides. A
handler declared to return Object that returns a Callable or an emitter starts, and its work
runs after the lock is released. The same holds for a handler declared to return
ResponseEntity<?>, ResponseEntity<Object> or a raw ResponseEntity whose body is an emitter, a
CompletionStage or a reactive type, and for a functional endpoint handler, which declares
ServerResponse, that returns ServerResponse.sse(...), a stream(...) response,
ServerResponse.async(...) over work that has not completed, or a response whose body is a reactive
type or a future that has not completed, such as ServerResponse.ok().body(mono). The same goes, on
any bean, for any
value whose work is still pending, such as a Mono, or a future or a Kotlin Job that has not
completed, returned through a wider declared type. Locksmith logs one ERROR on each such call,
naming the method, the returned type and the key, with a link to this section; the call still
returns the value. Declare the exact type, so that startup refuses it, or put the annotation on the
method that does the work.
The startup check counts handler beans in the application context that holds the annotated bean
only. A handler bean defined only in a parent context is not counted, so the startup fails with
found 0. Define the handler in the same context.
A lazy, prototype or scoped handler bean declared by its interface, such as
@Lazy @Bean LockFailureHandler audit(), is not counted either: Spring cannot tell its class before
it creates the bean, and the check does not create it. Declare such a handler with its class. With
spring.main.lazy-initialization=true every bean is lazy, so this holds for every handler declared
by its interface, and the failure comes when the annotated bean is first used.