Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(stats): index the messages timeline predicate and memoize dashboard aggregates (#935)

Yudhi Armyndharis04568c129e7d
diff --git a/.env.example b/.env.example
index 190cfc44c..892acdaf9 100644
--- a/.env.example
+++ b/.env.example
@@ -389,6 +389,13 @@ SEARCH_ENABLED=true # set to false to disable the /search route
SEARCH_PROVIDER=auto # auto | builtin-fts | none (plugin ids selectable once Spec 2 lands)
SEARCH_LIMIT_MAX=100 # hard cap on the `limit` query param
+# =============================================================================
+# DASHBOARD STATISTICS
+# =============================================================================
+# The /stats aggregates scan the messages table; responses are memoized in-process for this
+# TTL so dashboard polling doesn't re-run the scans on every request.
+# STATS_CACHE_TTL_MS=30000 # memo TTL in ms (default 30000 = 30s); 0 disables the memo
+
# =============================================================================
# PLUGINS
# =============================================================================
diff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.ts
index a6198cf33..4c7c6052d 100644
--- a/src/config/configuration.spec.ts
+++ b/src/config/configuration.spec.ts
@@ -183,3 +183,20 @@ describe('configuration search namespace', () => {
expect(cfg.search).toEqual({ enabled: true, provider: 'auto', limitMax: 100 });
});
});
+
+describe('configuration stats namespace', () => {
+ const orig = process.env.STATS_CACHE_TTL_MS;
+ afterEach(() => {
+ if (orig === undefined) delete process.env.STATS_CACHE_TTL_MS;
+ else process.env.STATS_CACHE_TTL_MS = orig;
+ });
+
+ it('exposes stats memo defaults and parses STATS_CACHE_TTL_MS (0 disables the memo)', () => {
+ delete process.env.STATS_CACHE_TTL_MS;
+ expect(configuration().stats.cacheTtlMs).toBe(30000);
+ process.env.STATS_CACHE_TTL_MS = '0';
+ expect(configuration().stats.cacheTtlMs).toBe(0);
+ process.env.STATS_CACHE_TTL_MS = '60000';
+ expect(configuration().stats.cacheTtlMs).toBe(60000);
+ });
+});
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index 412cf0fb5..5199dcccf 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -32,6 +32,14 @@ export default () => ({
limitMax: Number(process.env.SEARCH_LIMIT_MAX) || 100,
},
+ // Dashboard statistics. The /stats aggregates run GROUP BY scans over the whole messages
+ // table (synchronously on the event loop with the default SQLite backend), so responses are
+ // memoized in-process for this TTL to keep dashboard polling from re-running the scans on
+ // every request. 0 disables the memo.
+ stats: {
+ cacheTtlMs: parseInt(process.env.STATS_CACHE_TTL_MS || '30000', 10),
+ },
+
// Runtime feature flags. Single source of truth: src/config/feature-flags.ts. Exposed here so the
// full set is discoverable via ConfigService (`features.*`) instead of scattered process.env reads.
features: computeFeatureFlags(),
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index a355375d4..8efd69150 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -127,6 +127,7 @@ export function validateEnv(config: EnvConfig): EnvConfig {
'MAX_CONCURRENT_SESSIONS', // 0 = unlimited
'INGRESS_INSTANCE_TTL',
'WEBHOOK_DISPATCH_MAX_QUEUED',
+ 'STATS_CACHE_TTL_MS', // 0 = memo disabled
]) {
checkNonNegativeInt(key);
}
diff --git a/src/database/migrations/1785123853000-AddMessagesCreatedAtIndex.ts b/src/database/migrations/1785123853000-AddMessagesCreatedAtIndex.ts
new file mode 100644
index 000000000..9643228fa
--- /dev/null
+++ b/src/database/migrations/1785123853000-AddMessagesCreatedAtIndex.ts
@@ -0,0 +1,36 @@
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+/**
+ * Standalone index on messages(createdAt) for the dashboard stats aggregates. Their timeline
+ * predicates are createdAt-only range scans (`WHERE m.createdAt >= :since`, no sessionId), which
+ * the existing composite (sessionId, createdAt) cannot serve — sessionId leads it, so without
+ * ANALYZE stats SQLite full-scans the table, and PostgreSQL has no skip-scan at all. On the
+ * default SQLite backend that scan runs synchronously on the event loop.
+ *
+ * Runs on the `data` connection. `IF NOT EXISTS` is valid on both dialects (no branch needed,
+ * same as AddMessageSessionWaIndex) and keeps the migration idempotent + safe on a DB where
+ * `synchronize` already created the same-named index declared on the Message entity.
+ *
+ * The `messages` table is the hottest data table (every inbound/outbound row), so on Postgres a
+ * CREATE INDEX over a large table at boot can exceed the runtime pool's statement_timeout and abort
+ * the migration. Lift it for THIS transaction (SET LOCAL auto-reverts at COMMIT; SQLite rejects it
+ * syntactically, hence the guard) — the same discipline AddWebhooksSessionIdIndex and
+ * AddMessagesWaMessageIdUnique already use. `CONCURRENTLY` would avoid the ACCESS EXCLUSIVE lock
+ * but cannot run inside a transaction, so it is deliberately NOT used here (the boot-time blocking
+ * window is acceptable for a self-hosted gateway; consistency with the sibling index migrations
+ * outweighs it).
+ */
+export class AddMessagesCreatedAtIndex1785123853000 implements MigrationInterface {
+ name = 'AddMessagesCreatedAtIndex1785123853000';
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ if (queryRunner.dataSource.options.type === 'postgres') {
+ await queryRunner.query('SET LOCAL statement_timeout = 0');
+ }
+ await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_messages_createdAt" ON "messages" ("createdAt")`);
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_messages_createdAt"`);
+ }
+}
diff --git a/src/database/migrations/__tests__/1785123853000-AddMessagesCreatedAtIndex.spec.ts b/src/database/migrations/__tests__/1785123853000-AddMessagesCreatedAtIndex.spec.ts
new file mode 100644
index 000000000..ca93b63ec
--- /dev/null
+++ b/src/database/migrations/__tests__/1785123853000-AddMessagesCreatedAtIndex.spec.ts
@@ -0,0 +1,67 @@
+import { DataSource } from 'typeorm';
+import { AddMessagesCreatedAtIndex1785123853000 } from '../1785123853000-AddMessagesCreatedAtIndex';
+
+describe('AddMessagesCreatedAtIndex migration', () => {
+ let ds: DataSource;
+
+ beforeEach(async () => {
+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:' });
+ await ds.initialize();
+ // Pre-migration shape: the messages table with only the composite (sessionId, createdAt).
+ await ds.query(
+ `CREATE TABLE "messages" ("id" varchar PRIMARY KEY NOT NULL, "sessionId" varchar NOT NULL, ` +
+ `"direction" varchar NOT NULL DEFAULT ('outgoing'), "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
+ );
+ await ds.query(`CREATE INDEX "IDX_399833392126349ef0b04b9bed" ON "messages" ("sessionId", "createdAt")`);
+ // A few hundred rows spread over 60 days so the planner sees a real range predicate.
+ const rows: string[] = [];
+ for (let i = 0; i < 200; i++) {
+ const d = new Date(Date.now() - (i % 60) * 86400000).toISOString().replace('T', ' ').slice(0, 23);
+ rows.push(`('id${i}', 's${i % 5}', '${i % 2 ? 'incoming' : 'outgoing'}', '${d}')`);
+ }
+ await ds.query(`INSERT INTO "messages" ("id","sessionId","direction","createdAt") VALUES ${rows.join(',')}`);
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ const indexNames = async (): Promise<string[]> => {
+ const rows = await ds.query<{ name: string }[]>(`PRAGMA index_list("messages")`);
+ return rows.map(r => r.name).sort();
+ };
+
+ it('creates the standalone createdAt index and keeps the composite', async () => {
+ const runner = ds.createQueryRunner();
+ await new AddMessagesCreatedAtIndex1785123853000().up(runner);
+
+ const idx = await indexNames();
+ expect(idx).toContain('IDX_messages_createdAt');
+ expect(idx).toContain('IDX_399833392126349ef0b04b9bed');
+ });
+
+ it('is idempotent (re-running up is a no-op) and down() drops the index', async () => {
+ const runner = ds.createQueryRunner();
+ const migration = new AddMessagesCreatedAtIndex1785123853000();
+
+ await migration.up(runner);
+ await expect(migration.up(runner)).resolves.toBeUndefined(); // IF NOT EXISTS — safe to re-run
+ expect(await indexNames()).toContain('IDX_messages_createdAt');
+
+ await migration.down(runner);
+ expect(await indexNames()).not.toContain('IDX_messages_createdAt');
+ });
+
+ it('the createdAt-only range predicate used by the stats aggregates is served by the index', async () => {
+ const runner = ds.createQueryRunner();
+ await new AddMessagesCreatedAtIndex1785123853000().up(runner);
+
+ const since = new Date(Date.now() - 86400000).toISOString().replace('T', ' ').slice(0, 23);
+ const plan = await ds.query<{ detail: string }[]>(
+ `EXPLAIN QUERY PLAN SELECT "direction", COUNT(*) FROM "messages" WHERE "createdAt" >= '${since}' GROUP BY "direction"`,
+ );
+ expect(plan.map(p => p.detail).join(' | ')).toMatch(
+ /SEARCH messages USING (COVERING )?INDEX IDX_messages_createdAt/,
+ );
+ });
+});
diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.ts
index dbddb3943..f5c84a4b3 100644
--- a/src/modules/message/entities/message.entity.ts
+++ b/src/modules/message/entities/message.entity.ts
@@ -95,6 +95,11 @@ export class Message {
@Index()
status: MessageStatus;
+ // Standalone index for the createdAt-only range predicates of the stats aggregates — the
+ // composite above leads with sessionId, so it can't serve them (SQLite needs ANALYZE stats for
+ // a skip-scan; Postgres has none). The explicit name matches the migration that creates it on
+ // synchronize-disabled deployments, so both schema paths converge on one index.
@CreateDateColumn()
+ @Index('IDX_messages_createdAt')
createdAt: Date;
}
diff --git a/src/modules/stats/stats.service.spec.ts b/src/modules/stats/stats.service.spec.ts
index 6d956e93a..faa3bf222 100644
--- a/src/modules/stats/stats.service.spec.ts
+++ b/src/modules/stats/stats.service.spec.ts
@@ -42,7 +42,8 @@ describe('StatsService time-series + hourly activity on SQLite (end-to-end regre
});
await ds.initialize();
const cache = { setSessionsStats: jest.fn() };
- service = new StatsService(ds.getRepository(Session), ds.getRepository(Message), cache as never);
+ const config = { get: () => 30000 };
+ service = new StatsService(ds.getRepository(Session), ds.getRepository(Message), cache as never, config as never);
});
afterEach(async () => {
@@ -241,3 +242,126 @@ describe('StatsService time-series + hourly activity on SQLite (end-to-end regre
expect(totals.received).toBe(1);
});
});
+
+describe('StatsService aggregate memo (in-process TTL)', () => {
+ let ds: DataSource;
+
+ beforeEach(async () => {
+ ds = new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [Session, Message],
+ synchronize: true,
+ });
+ await ds.initialize();
+ const sessions = ds.getRepository(Session);
+ await sessions.save(sessions.create({ id: 's1', name: 'n1', status: SessionStatus.READY, config: {} }));
+ await sessions.save(sessions.create({ id: 's2', name: 'n2', status: SessionStatus.READY, config: {} }));
+ const messages = ds.getRepository(Message);
+ const base = {
+ chatId: 'c1',
+ from: 'a',
+ to: 'b',
+ type: 'text',
+ direction: MessageDirection.OUTGOING,
+ status: MessageStatus.SENT,
+ };
+ await messages.save(messages.create({ ...base, sessionId: 's1' }));
+ await messages.save(messages.create({ ...base, sessionId: 's2' }));
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ const makeService = (ttlMs: number) =>
+ new StatsService(
+ ds.getRepository(Session),
+ ds.getRepository(Message),
+ { setSessionsStats: jest.fn() } as never,
+ { get: () => ttlMs } as never,
+ );
+
+ it('serves a repeated identical call from the memo within the TTL (no second DB hit)', async () => {
+ const service = makeService(30000);
+ const spy = jest.spyOn(ds.getRepository(Message), 'createQueryBuilder');
+
+ await service.getMessageStats('24h');
+ const afterFirst = spy.mock.calls.length;
+ expect(afterFirst).toBeGreaterThan(0);
+
+ await service.getMessageStats('24h');
+ expect(spy.mock.calls.length).toBe(afterFirst);
+ });
+
+ it('re-runs the aggregate once the TTL has expired', async () => {
+ const service = makeService(30000);
+ const spy = jest.spyOn(ds.getRepository(Message), 'createQueryBuilder');
+ const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1_000_000);
+ try {
+ await service.getMessageStats('24h');
+ const afterFirst = spy.mock.calls.length;
+
+ nowSpy.mockReturnValue(1_000_000 + 30_001);
+ await service.getMessageStats('24h');
+ expect(spy.mock.calls.length).toBeGreaterThan(afterFirst);
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
+ it('keys the memo by query shape and by session id', async () => {
+ const service = makeService(30000);
+ const spy = jest.spyOn(ds.getRepository(Message), 'createQueryBuilder');
+
+ await service.getMessageStats('24h');
+ let n = spy.mock.calls.length;
+ await service.getMessageStats('7d'); // different period → different key → DB hit
+ expect(spy.mock.calls.length).toBeGreaterThan(n);
+
+ n = spy.mock.calls.length;
+ await service.getSessionStats('s1');
+ await service.getSessionStats('s1'); // memo hit — no new queries
+ const afterS1 = spy.mock.calls.length;
+ expect(afterS1).toBeGreaterThan(n);
+
+ await service.getSessionStats('s2'); // different session → different key → DB hit
+ expect(spy.mock.calls.length).toBeGreaterThan(afterS1);
+ });
+
+ 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');
+
+ await service.getMessageStats('24h');
+ const n = spy.mock.calls.length;
+ await service.getMessageStats('24h');
+ expect(spy.mock.calls.length).toBeGreaterThan(n);
+ });
+
+ it('bounds every cross-session aggregate with a createdAt range predicate the standalone index serves', async () => {
+ const service = makeService(30000);
+ // Capture the generated SQL the same way the reserved-word regression tests above do.
+ const captured: string[] = [];
+ const repo = ds.getRepository(Message);
+ const origCreate = repo.createQueryBuilder.bind(repo);
+ jest.spyOn(repo, 'createQueryBuilder').mockImplementation((alias?: string) => {
+ const qb = origCreate(alias);
+ const origGetRawMany = qb.getRawMany.bind(qb);
+ jest.spyOn(qb, 'getRawMany').mockImplementation((async () => {
+ captured.push(qb.getQuery());
+ return origGetRawMany();
+ }) as never);
+ return qb;
+ });
+
+ await service.getMessageStats('24h'); // time-series + byType + bySession + topChats
+
+ expect(captured.length).toBeGreaterThan(0);
+ // IDX_messages_createdAt serves `createdAt >= ?`; an unbounded GROUP BY here would be the
+ // full-history scan this service must no longer run.
+ for (const sql of captured) {
+ expect(sql).toMatch(/WHERE\s+.*"createdAt"\s*>=/i);
+ }
+ });
+});
diff --git a/src/modules/stats/stats.service.ts b/src/modules/stats/stats.service.ts
index 07ccbd048..b5a85e878 100644
--- a/src/modules/stats/stats.service.ts
+++ b/src/modules/stats/stats.service.ts
@@ -1,5 +1,6 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
+import { ConfigService } from '@nestjs/config';
import { Repository } from 'typeorm';
import { Session, SessionStatus } from '../session/entities/session.entity';
import { Message, MessageStatus } from '../message/entities/message.entity';
@@ -77,12 +78,23 @@ export interface SessionStats {
@Injectable()
export class StatsService {
+ /**
+ * In-process TTL memo for the aggregate responses, keyed by query shape ('overview',
+ * 'messages:<period>', 'session:<id>'). The aggregates run GROUP BY scans over the whole
+ * messages table — on the default SQLite backend synchronously on the event loop — so
+ * dashboard polling would otherwise re-run them on every request. TTL-only invalidation:
+ * entries expire after stats.cacheTtlMs; there is no write-path hook. Key cardinality is
+ * bounded (4 global shapes + one per session), so no size eviction is needed.
+ */
+ private readonly memo = new Map<string, { expiresAt: number; value: unknown }>();
+
constructor(
@InjectRepository(Session, 'data')
private readonly sessionRepo: Repository<Session>,
@InjectRepository(Message, 'data')
private readonly messageRepo: Repository<Message>,
private readonly cacheService: CacheService,
+ private readonly configService: ConfigService,
) {}
/** The data-connection dialect ('sqlite' | 'postgres'), used to pick portable date SQL. */
@@ -90,7 +102,28 @@ export class StatsService {
return this.messageRepo.manager.dataSource.options.type;
}
+ /** Memo TTL in ms; 0 disables memoization (every request hits the DB). Read per call. */
+ private get memoTtlMs(): number {
+ 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> {
+ 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;
+ }
+
async getOverview(): Promise<OverviewStats> {
+ return this.memoized('overview', () => this.loadOverview());
+ }
+
+ private async loadOverview(): Promise<OverviewStats> {
// Get session stats
const sessions = await this.sessionRepo.find();
const byStatus: Record<string, number> = {};
@@ -153,6 +186,10 @@ export class StatsService {
}
async getMessageStats(period: '24h' | '7d' | '30d'): Promise<MessageStats> {
+ return this.memoized(`messages:${period}`, () => this.loadMessageStats(period));
+ }
+
+ private async loadMessageStats(period: '24h' | '7d' | '30d'): Promise<MessageStats> {
const since = this.getPeriodStart(period);
const interval = period === '24h' ? 'hour' : 'day';
@@ -233,6 +270,10 @@ export class StatsService {
}
async getSessionStats(sessionId: string): Promise<SessionStats> {
+ return this.memoized(`session:${sessionId}`, () => this.loadSessionStats(sessionId));
+ }
+
+ private async loadSessionStats(sessionId: string): Promise<SessionStats> {
const session = await this.sessionRepo.findOne({ where: { id: sessionId } });
if (!session) {
throw new NotFoundException('Session not found');