I have encountered an issue while using IoRedis and DragonflyDB to implement rate limiting in my web application. Despite setting a TTL of 5 seconds for the keys in the Redis DB, sometimes they do not expire as expected. I am struggling to understand why this is happening and unable to replicate the issue. Can anyone offer any insights or suggestions?
type RateLimitData = { [key: string]: number };
const prefix = 'rateLimit';
const ttl = 5;
const create = async (userId: string, path: string): Promise<void> => {
const data = { [path]: 1 };
await redis.call(
'JSON.SET',
`${prefix}:${userId}`,
'$',
JSON.stringify(data)
);
await redis.expire(`${prefix}:${userId}`, ttl);
};
const update = async (userId: string, path: string): Promise<void> => {
const previousCache = await get(userId);
if (previousCache) {
const aggregate = previousCache[path] ? previousCache[path] + 1 : 1;
const updatedCache = { ...previousCache, [path]: aggregate };
await redis.call(
'JSON.SET',
`${prefix}:${userId}`,
'$',
JSON.stringify(updatedCache)
);
} else {
await create(userId, path);
}
};
const get = async (userId: string): Promise<RateLimitData | null> => {
const data = await redis.call('JSON.GET', `${prefix}:${userId}`);
if (!data) return null;
return JSON.parse(data as string) as RateLimitData;
};
export const rateLimit = { create, update, get };
Dragonfly version:
docker.dragonflydb.io/dragonflydb/dragonfly:v1.2.1
"ioredis": "^5.3.2",