perf: Bound MutexLock retries and de-dupe same-key cache misses (#13110)

* perf: Bound MutexLock retries and de-dupe same-key cache misses

MutexLock configured redlock with retryCount: 120, retryDelay: 1000 — a
2-minute retry window for locks with a 4s default TTL. Under cache-miss
storms (e.g. websocket reconnects all missing user.collectionIds) N
contenders piled onto one lock key, retaining ~K²/2 error objects plus
pending timers/promises. Bound retries to ~the lock TTL (retryCount: 15,
retryDelay: 250) and add a per-process in-flight de-dupe in
CacheHelper.getDataOrSet so N same-key misses share one lock acquisition
and callback.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: Return falsy cached values instead of treating them as misses

getDataOrSet checked `if (cache)`, so a cached null/false/0/"" was treated
as a miss and re-populated on every read (e.g. Collection.getCachedDocument
Structure caches NavigationNode[] | null via the AfterSave hook). Check for
undefined — the only value getData returns on a genuine miss — so falsy
cached values are returned without an extra lock and DB query.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* deslop

* fix: Scope bounded lock retries to cache locks only

The tightened retry window (15×250ms) was set on the shared Redlock
instance, so it also affected long-lived callers — notably the 10-minute
"migrations" lock in checkMigrations, which fatal-exits on acquire failure
and would crash concurrent boots. Restore the generous default on the
shared instance and pass a bounded retry override (MutexLock.cacheRetry
Settings) only from the cache path via a new per-acquire retry option.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: Cache falsy callback results in getDataOrSet

populate only cached truthy callback results, so a valid null (e.g. from
Collection.getCachedDocumentStructure) was never stored and every miss
re-ran the lock + DB query. Skip caching only when the result is undefined,
and guard the CacheResult detection against null (typeof null === "object").

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Tom MoorandClaude Opus 4.8 authored and GitHub committed 2026-07-23 20:00:54 -04:00
1 parent a232f8c702
commit c8d4e8c0e7
3 files changed
+172 -22

No files matched your search

+93
View File
@@ -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<string[] | null>(
"test:null",
callback,
60
)
).toBeNull();
expect(await CacheHelper.getData("test:null")).toBeNull();
expect(
await CacheHelper.getDataOrSet<string[] | null>(
"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);
+65 -21
View File
@@ -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<string, Promise<unknown>>();
/**
* 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<T | undefined> {
let cache = await this.getData<T>(key);
const cache = await this.getData<T>(key);
if (cache) {
if (cache !== undefined) {
return cache;
}
// Coalesce concurrent same-key misses in this process
const existing = this.inflight.get(key) as
| Promise<T | undefined>
| undefined;
if (existing) {
return existing;
}
const promise = this.populate<T>(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<T>(
key: string,
callback: () => Promise<T | CacheResult<T> | undefined>,
expiry: number,
lockTimeout: number
): Promise<T | undefined> {
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<T>(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<T>;
await this.setData<T>(key, data, dynamicExpiry ?? expiry);
return data;
}
await this.setData<T>(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<T>;
await this.setData<T>(key, data, dynamicExpiry ?? expiry);
return data;
}
await this.setData<T>(key, result as T, expiry);
return result as T;
} finally {
if (lock) {
await MutexLock.release(lock);
+14 -1
View File
@@ -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<Settings>;
};
/**
@@ -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<Settings> = {
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