diff --git a/server/utils/CacheHelper.test.ts b/server/utils/CacheHelper.test.ts index a455b5ccf2..3b63da7959 100644 --- a/server/utils/CacheHelper.test.ts +++ b/server/utils/CacheHelper.test.ts @@ -19,6 +19,99 @@ describe("CacheHelper", () => { }); }); + describe("getDataOrSet", () => { + it("should coalesce concurrent same-key misses into one callback", async () => { + let calls = 0; + const callback = async () => { + calls++; + return "value"; + }; + + const results = await Promise.all( + Array.from({ length: 10 }, () => + CacheHelper.getDataOrSet("test:dedupe", callback, 60) + ) + ); + + expect(calls).toEqual(1); + expect(results).toEqual(Array.from({ length: 10 }, () => "value")); + expect(await CacheHelper.getData("test:dedupe")).toEqual("value"); + }); + + it("should return a cached falsy value without invoking the callback", async () => { + await CacheHelper.setData("test:falsy", null, 60); + + let calls = 0; + const callback = async () => { + calls++; + return ["value"]; + }; + + expect( + await CacheHelper.getDataOrSet("test:falsy", callback, 60) + ).toBeNull(); + expect(calls).toEqual(0); + }); + + it("should cache a falsy callback result and not re-invoke on the next miss", async () => { + let calls = 0; + const callback = async () => { + calls++; + return null; + }; + + expect( + await CacheHelper.getDataOrSet( + "test:null", + callback, + 60 + ) + ).toBeNull(); + expect(await CacheHelper.getData("test:null")).toBeNull(); + + expect( + await CacheHelper.getDataOrSet( + "test:null", + callback, + 60 + ) + ).toBeNull(); + expect(calls).toEqual(1); + }); + + it("should not cache an undefined callback result", async () => { + let calls = 0; + const callback = async () => { + calls++; + return undefined; + }; + + expect( + await CacheHelper.getDataOrSet("test:undef", callback, 60) + ).toBeUndefined(); + expect( + await CacheHelper.getDataOrSet("test:undef", callback, 60) + ).toBeUndefined(); + expect(calls).toEqual(2); + }); + + it("should call the callback again after the in-flight promise settles", async () => { + let calls = 0; + const callback = async () => { + calls++; + return calls === 1 ? undefined : "value"; + }; + + expect( + await CacheHelper.getDataOrSet("test:retry", callback, 60) + ).toBeUndefined(); + expect( + await CacheHelper.getDataOrSet("test:retry", callback, 60) + ).toEqual("value"); + expect(calls).toEqual(2); + }); + }); + describe("removeData", () => { it("should remove a single key", async () => { await CacheHelper.setData("test:key", "value", 60); diff --git a/server/utils/CacheHelper.ts b/server/utils/CacheHelper.ts index 86c4f92a32..3d0b012d0d 100644 --- a/server/utils/CacheHelper.ts +++ b/server/utils/CacheHelper.ts @@ -21,6 +21,10 @@ export class CacheHelper { // Default expiry time for cache data in seconds private static defaultDataExpiry = Day.seconds; + // In-flight cache population promises keyed by cache key, so that N same-key + // misses within one process share a single lock acquisition and callback. + private static inflight = new Map>(); + /** * Given a key this method will attempt to get the data from cache store first * If data is not found, it will call the callback to get the data and save it in cache @@ -42,45 +46,85 @@ export class CacheHelper { expiry: number, lockTimeout: number = MutexLock.defaultLockTimeout ): Promise { - let cache = await this.getData(key); + const cache = await this.getData(key); - if (cache) { + if (cache !== undefined) { return cache; } + // Coalesce concurrent same-key misses in this process + const existing = this.inflight.get(key) as + | Promise + | undefined; + if (existing) { + return existing; + } + + const promise = this.populate(key, callback, expiry, lockTimeout); + this.inflight.set(key, promise); + try { + return await promise; + } finally { + this.inflight.delete(key); + } + } + + /** + * Acquires the distributed lock, re-checks the cache, and populates it from + * the callback. Serialized per-process by getDataOrSet's in-flight map. + * + * @param key Cache key. + * @param callback Callback to get the data if not found in cache. + * @param expiry Default cache data expiry in seconds. + * @param lockTimeout Lock timeout in milliseconds. + * @returns The data from cache or the result of the callback. + */ + private static async populate( + key: string, + callback: () => Promise | undefined>, + expiry: number, + lockTimeout: number + ): Promise { + let cache: T | undefined; + // Nothing in the cache, acquire a lock to prevent multiple writes let lock; const lockKey = `lock:${key}`; try { try { - lock = await MutexLock.acquire(lockKey, lockTimeout); + lock = await MutexLock.acquire(lockKey, lockTimeout, { + retry: MutexLock.cacheRetrySettings, + }); } catch (err) { Logger.error(`Could not acquire lock for ${key}`, toError(err)); } cache = await this.getData(key); - if (cache) { + if (cache !== undefined) { return cache; } - // Get the data from the callback and save it in cache + // Get the data from the callback and save it in cache. Only undefined + // means "nothing to cache"; falsy values like null are cached normally. const result = await callback(); - if (result) { - // Check if result is a CacheResult with dynamic expiry - const isCacheResult = - typeof result === "object" && - "data" in result && - Object.keys(result).every((k) => k === "data" || k === "expiry"); - - if (isCacheResult) { - const { data, expiry: dynamicExpiry } = result as CacheResult; - await this.setData(key, data, dynamicExpiry ?? expiry); - return data; - } - - await this.setData(key, result as T, expiry); - return result as T; + if (result === undefined) { + return undefined; } - return undefined; + + // Check if result is a CacheResult with dynamic expiry + const isCacheResult = + result !== null && + typeof result === "object" && + "data" in result && + Object.keys(result).every((k) => k === "data" || k === "expiry"); + + if (isCacheResult) { + const { data, expiry: dynamicExpiry } = result as CacheResult; + await this.setData(key, data, dynamicExpiry ?? expiry); + return data; + } + + await this.setData(key, result as T, expiry); + return result as T; } finally { if (lock) { await MutexLock.release(lock); diff --git a/server/utils/MutexLock.ts b/server/utils/MutexLock.ts index ae2fd012e6..3bae3aab86 100644 --- a/server/utils/MutexLock.ts +++ b/server/utils/MutexLock.ts @@ -3,6 +3,7 @@ import Redlock, { ResourceLockedError, type Lock, type RedlockAbortSignal, + type Settings, } from "redlock"; import Redis from "@server/storage/redis"; import Logger from "@server/logging/Logger"; @@ -11,6 +12,8 @@ import ShutdownHelper, { ShutdownOrder } from "./ShutdownHelper"; type AcquireOptions = { /** Whether a lock should be automatically released on server shutdown */ releaseOnShutdown?: boolean; + /** Overrides the default retry settings for this acquisition. */ + retry?: Partial; }; /** @@ -21,6 +24,16 @@ export class MutexLock { /** Default expiry time for acquiring lock in milliseconds. */ public static defaultLockTimeout = 4000; + /** + * Retry settings for short-lived cache locks, bounded to roughly the lock + * TTL. Contenders re-check the cache after acquiring, so a longer window only + * adds latency and retains memory during cache-miss storms. + */ + public static cacheRetrySettings: Partial = { + retryCount: 15, + retryDelay: 250, + }; + /** * Returns the redlock instance */ @@ -60,7 +73,7 @@ export class MutexLock { timeout: number, options?: AcquireOptions ) { - const lock = await this.lock.acquire([resource], timeout); + const lock = await this.lock.acquire([resource], timeout, options?.retry); if (options?.releaseOnShutdown) { const key = `lock:${resource}`; // @ts-expect-error Attach resource for use in shutdown