Repository navigation
|
I’m trying to see if I’m using this library correctly in cases where I want to achieve stampede request prevention. For example, I’m giving a simple Express web server simulating resource endpoint and stampede endpoint. From what I understand, there is no difference between creating lock instance outside and inside route handler other than each lock instance creating new lock identifier. Work is done as expected: first lock is acquired, others wait and retry their job in retry interval; when the lock is released, next one is acquired and the work repeats. I’m aware that this is not the same situation as with in-memory locks such as the ones created with async-mutex where each mutex for a specific resource must be shared, but do the same principles regarding created instances work here also? import express from "express";
import { Redis } from "ioredis";
import { createLock, IoredisAdapter } from "redlock-universal";
import { setTimeout } from "node:timers/promises";
const app = express();
const port = 3000;
const redisClient = new Redis({ port: 3333 });
const redisAdapter = new IoredisAdapter(redisClient);
async function simulateWork(mode, requestId, done) {
console.log(`[${mode}] request=${requestId} start, finished: ${done}`);
await setTimeout(getTimeout());
console.log(`[${mode}] request=${requestId} done`);
return requestId;
}
const lock = createLock({
adapter: redisAdapter,
key: "hello",
ttl: 15000,
retryAttempts: 150,
retryDelay: 100,
});
let done = false;
app.get("/redislock", async (req, res) => {
const release = await lock.acquire();
const result = await simulateWork("redislock", req.query.request, done);
done = true;
await lock.release(release);
res.send(result);
});
app.get("/stampede-redislock", async (req, res) => {
console.log("stampede redislock");
(fetch("http://localhost:3000/redislock?request=1"),
fetch("http://localhost:3000/redislock?request=2"),
fetch("http://localhost:3000/redislock?request=3"),
res.send(null));
}); |
Replies: 1 comment
|
Hi @niksy, sorry for the slow reply! Instances: right, you don't need to share the lock instance the way you do with async-mutex. The lock lives in Redis under its key, so any instance with the same key, in this process or another, competes for the same lock. One correction, though: the identifier is created per acquisition, not per instance. Every The differences are minor. A new instance pings Redis once, on its first Stampedes: your example serializes the requests, but it doesn't prevent the stampede, because every request still runs the work, one after another. To run the work only once, keep the result somewhere shared (a Redis key), let one request compute it, and have the others wait for that result: import { setTimeout as sleep } from 'node:timers/promises';
import { Redis } from 'ioredis';
import { createLock, IoredisAdapter, LockAcquisitionError } from 'redlock-universal';
const redis = new Redis();
const adapter = new IoredisAdapter(redis);
/**
* Returns the cached value for `key`. On a miss, one caller (across all servers)
* runs compute(); the others wait for its result instead of computing it again.
*/
export async function getOrCompute(
key: string,
compute: () => Promise<string>,
{ cacheTtlSeconds = 60, maxWaitMs = 10_000 } = {},
): Promise<string> {
const cacheKey = `cache:${key}`;
// The lock gets its own key: never lock the cache key itself
const lock = createLock({
adapter,
key: `lock:${key}`,
ttl: 10_000,
retryAttempts: 0,
circuitBreaker: false, // new lock per call: skip the health-check PING
});
const deadline = Date.now() + maxWaitMs;
for (let delay = 25; ; delay = Math.min(delay * 2, 500)) {
const cached = await redis.get(cacheKey);
if (cached !== null) return cached;
try {
// using() keeps extending the lock while compute() runs, even past the TTL
return await lock.using(async () => {
// Check again: the previous holder may have just stored the value
const fresh = await redis.get(cacheKey);
if (fresh !== null) return fresh;
const value = await compute();
await redis.set(cacheKey, value, 'EX', cacheTtlSeconds);
return value;
});
} catch (err) {
if (!(err instanceof LockAcquisitionError)) throw err; // compute() or Redis failed
}
// Another caller holds the lock and is computing: wait, then check the cache again
if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${cacheKey}`);
await sleep(delay / 2 + Math.random() * (delay / 2));
}
}In a test with 50 concurrent calls for one key,
If a slightly stale value is acceptable, nobody has to wait at all: keep serving the old value and refresh it in the background under the same lock. Let me know how it goes! |
Hi @niksy, sorry for the slow reply!
Instances: right, you don't need to share the lock instance the way you do with async-mutex. The lock lives in Redis under its key, so any instance with the same key, in this process or another, competes for the same lock. One correction, though: the identifier is created per acquisition, not per instance. Every
acquire()generates a new random token and returns it in the handle. So one shared instance can safely serve concurrent requests, and an instance per request works too.The differences are minor. A new instance pings Redis once, on its first
acquire(): that's the health check of the built-in circuit breaker, andcircuitBreaker: falseturns it o…