Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(stats): share one aggregate computation between concurrent callers

Yudhi Armyndharis3c4a4d6d374f
diff --git a/src/modules/stats/stats.service.spec.ts b/src/modules/stats/stats.service.spec.ts
index c5693518a..86b414345 100644
--- a/src/modules/stats/stats.service.spec.ts
+++ b/src/modules/stats/stats.service.spec.ts
@@ -364,6 +364,54 @@ describe('StatsService aggregate memo (in-process TTL)', () => {
expect(spy.mock.calls.length).toBeGreaterThan(afterS1);
});
+ // The private loaders, reached through a cast so the spies count computations rather than queries.
+ type Loaders = { loadOverview: () => Promise<unknown>; loadSessionStats: (id: string) => Promise<unknown> };
+
+ it('runs one aggregate for concurrent callers on a cold memo', async () => {
+ const service = makeService(30000);
+ const loadOverview = jest.spyOn(service as unknown as Loaders, 'loadOverview');
+ const loadSession = jest.spyOn(service as unknown as Loaders, 'loadSessionStats');
+
+ const [a, b] = await Promise.all([service.getOverview(), service.getOverview()]);
+ await Promise.all([service.getSessionStats('s1'), service.getSessionStats('s1')]);
+
+ expect(loadOverview).toHaveBeenCalledTimes(1);
+ expect(b).toEqual(a);
+ expect(loadSession).toHaveBeenCalledTimes(1);
+ });
+
+ it('shares a rejection with the concurrent callers and does not memoize it', async () => {
+ const service = makeService(30000);
+ const loadOverview = jest
+ .spyOn(service as unknown as Loaders, 'loadOverview')
+ .mockRejectedValueOnce(new Error('boom'));
+
+ const results = await Promise.allSettled([service.getOverview(), service.getOverview()]);
+ expect(results.map(r => r.status)).toEqual(['rejected', 'rejected']);
+ expect(loadOverview).toHaveBeenCalledTimes(1);
+
+ await expect(service.getOverview()).resolves.toBeDefined();
+ expect(loadOverview).toHaveBeenCalledTimes(2);
+ });
+
+ it('starts the TTL when the aggregate completes, not when it starts', async () => {
+ const service = makeService(30000);
+ const loadOverview = jest.spyOn(service as unknown as Loaders, 'loadOverview');
+ const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1_000_000);
+ try {
+ // A scan that outlives the TTL: stamping the entry at the start would store it already expired.
+ loadOverview.mockImplementationOnce(() => {
+ nowSpy.mockReturnValue(1_000_000 + 40_000);
+ return Promise.resolve({} as never);
+ });
+ await service.getOverview();
+ await service.getOverview();
+ expect(loadOverview).toHaveBeenCalledTimes(1);
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
it('a 0 TTL disables the memo (every call hits the DB)', async () => {
const service = makeService(0);
const spy = jest.spyOn(ds.getRepository(Message), 'createQueryBuilder');
diff --git a/src/modules/stats/stats.service.ts b/src/modules/stats/stats.service.ts
index 996d1e9a8..ac6a294ec 100644
--- a/src/modules/stats/stats.service.ts
+++ b/src/modules/stats/stats.service.ts
@@ -93,9 +93,12 @@ export class StatsService {
* entries expire after stats.cacheTtlMs; there is no write-path hook. Session-scoped entries
* are additionally re-validated on serve (getSessionStats), so a deleted session is not
* resurrected from the memo. Key cardinality is
- * bounded (4 global shapes + one per session), so no size eviction is needed.
+ * bounded (4 global shapes + one per session), so no size eviction is needed. Concurrent misses
+ * on one key share a single computation (`inflight`), so an expired entry costs one scan, not one
+ * per waiting request; a rejection is handed to every waiter and never stored.
*/
private readonly memo = new Map<string, { expiresAt: number; value: unknown }>();
+ private readonly inflight = new Map<string, Promise<unknown>>();
constructor(
@InjectRepository(Session, 'data')
@@ -116,16 +119,34 @@ export class StatsService {
return this.configService.get<number>('stats.cacheTtlMs', 30000);
}
- /** Returns the memoized value for `key` while fresh; otherwise computes, stores, returns it. */
- private async memoized<T>(key: string, compute: () => Promise<T>): Promise<T> {
+ /**
+ * Returns the memoized value for `key` while fresh; otherwise joins the computation already
+ * running for it, or starts one. The TTL runs from completion, so a scan slower than the TTL does
+ * not store an entry that is already stale. The identity check keeps a flight that was dropped
+ * (getSessionStats on a deleted session) from writing its result back.
+ */
+ private memoized<T>(key: string, compute: () => Promise<T>): Promise<T> {
const ttl = this.memoTtlMs;
if (ttl <= 0) return compute();
- const now = Date.now();
const hit = this.memo.get(key);
- if (hit && hit.expiresAt > now) return hit.value as T;
- const value = await compute();
- this.memo.set(key, { expiresAt: now + ttl, value });
- return value;
+ if (hit && hit.expiresAt > Date.now()) return Promise.resolve(hit.value as T);
+ const pending = this.inflight.get(key);
+ if (pending) return pending as Promise<T>;
+ const flight: Promise<T> = compute().then(
+ value => {
+ if (this.inflight.get(key) === flight) {
+ this.inflight.delete(key);
+ this.memo.set(key, { expiresAt: Date.now() + ttl, value });
+ }
+ return value;
+ },
+ (err: unknown) => {
+ if (this.inflight.get(key) === flight) this.inflight.delete(key);
+ throw err;
+ },
+ );
+ this.inflight.set(key, flight);
+ return flight;
}
async getOverview(): Promise<OverviewStats> {
@@ -287,6 +308,7 @@ export class StatsService {
const key = `session:${sessionId}`;
if ((await this.sessionRepo.count({ where: { id: sessionId } })) === 0) {
this.memo.delete(key);
+ this.inflight.delete(key);
throw new NotFoundException('Session not found');
}
return this.memoized(key, () => this.loadSessionStats(sessionId));