Repository navigation
|
Hi, i am looking at the api and i see only How should I implment a backoff logic to attempt a new acquisition? I would expect |
Answered by
alexpota
Oct 28, 2026
Replies: 1 comment
|
Hi @msalafia, sorry for the very slow reply! You're right: in the current version (0.8.9), import { setTimeout as sleep } from 'node:timers/promises';
import { LockAcquisitionError, type ExtendedAbortSignal, type Lock } from 'redlock-universal';
/**
* lock.using() with exponential backoff and full jitter between attempts.
* Create the lock with retryAttempts: 0 so that only this helper retries.
*/
export async function usingWithBackoff<T>(
lock: Lock,
routine: (signal: ExtendedAbortSignal) => Promise<T>,
{ attempts = 10, baseDelay = 50, maxDelay = 5_000 } = {},
): Promise<T> {
for (let attempt = 1; ; attempt++) {
let started = false;
try {
return await lock.using((signal) => {
started = true;
return routine(signal);
});
} catch (err) {
// Retry only when the lock couldn't be acquired, and at most `attempts` times.
// Errors from the routine are never retried: it already ran.
if (started || !(err instanceof LockAcquisitionError) || attempt >= attempts) throw err;
}
const cap = Math.min(maxDelay, baseDelay * 2 ** attempt);
await sleep(Math.random() * cap);
}
}import { Redis } from 'ioredis';
import { createLock, IoredisAdapter } from 'redlock-universal';
import { usingWithBackoff } from './using-with-backoff.js';
const lock = createLock({
adapter: new IoredisAdapter(new Redis()),
key: 'reports:monthly',
ttl: 30_000,
retryAttempts: 0, // usingWithBackoff does the retrying
});
const report = await usingWithBackoff(lock, () => buildReport(), { attempts: 8 });A few notes:
|
0 replies
Answer selected by
alexpota
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @msalafia, sorry for the very slow reply!
You're right: in the current version (0.8.9),
retryDelayonly takes a number, and the lock waits that same fixed delay between attempts. For now, you can get backoff by turning the built-in retries off (retryAttempts: 0) and retrying in a small helper: