Reliability
Distributed locks
Make sure only one instance does a job at a time.
The problem
You run three copies of your application. A nightly job "send invoices" is scheduled in all three, so every customer gets three invoices. Or two requests try to pay the same invoice at the same moment. A normal synchronized block only protects one process. You need a lock that all instances share.
Take a lock
@Injectable
class InvoiceJob(private val locks: LockService, private val invoices: InvoiceService) {
@Cron("0 0 2 * * *")
fun nightly() {
// run it here only if nobody else holds the lock; otherwise do nothing
locks.ifFree("job:invoices", ttl = Duration.ofMinutes(30)) { invoices.sendAll() }
}
fun pay(id: String) = locks.withLock("invoice:$id", ttl = Duration.ofSeconds(30), wait = Duration.ofSeconds(5)) {
invoices.pay(id) // one payment of invoice `id` at a time, across all instances
}
}| Method | When the lock is taken |
|---|---|
tryLock(key, ttl) | returns the Lock or null at once |
lock(key, ttl, wait) | waits up to wait, then throws LockNotAcquiredException |
withLock(key, ttl, wait) { } | waits, runs the block, always releases |
ifFree(key, ttl) { } | runs the block if free, else returns null |
As an annotation
@Injectable
open class PaymentService {
@Locked("invoice:{0}", ttlMillis = 30_000, waitMillis = 5_000) // {0} is the first argument
open fun pay(invoiceId: String) { ... }
@Locked("job:cleanup", skipIfLocked = true) // a second caller returns immediately
open fun cleanup() { ... }
}Choose a store
Without a store, locks work inside one process only. For real use share a store between instances:
Kest.run<AppModule> { import(LocksModule.forRoot(RedisLockStore("redis.internal", 6379))) } // package locks-redisThe Redis store takes a lock with SET key token NX PX ttl and releases it with a script that checks the token, so a holder whose lease already expired can never release the lock of whoever took it next.
The lease (ttl): why every lock expires
If the process holding a lock crashes, nobody would ever release it. So every lock has a time to live. Choose ttl a bit longer than the work normally takes. For work that may take longer, renew while you work:
locks.lock("report", ttl = Duration.ofSeconds(30)).use { lock ->
for (chunk in chunks) { process(chunk); if (!lock.renew(Duration.ofSeconds(30))) error("lost the lock") }
}renew returns false when the lock is no longer yours (it expired and someone else took it): stop working.
Be honest about the guarantees
- A lock on one Redis node is not perfect: if Redis fails over at the wrong moment, two holders can exist briefly. For jobs where a double run is merely wasteful (sending a digest) that is fine. For money, also protect the data itself (a unique constraint, a version column, an idempotency key) so a double run is harmless.
- Locks are for mutual exclusion, not for ordering or queues. To process items one by one, use a queue.
Testing
InMemoryLockStore is the default, so tests need nothing. Two threads calling tryLock with the same key: exactly one gets a lock.