Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

perf(message): index a chat's thread by session, chat and time

Yudhi Armyndharis6128214617fb
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index f0fba72a4..9f6848dbd 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -520,6 +520,7 @@ CREATE TABLE messages (
-- "sessionId", so it already serves session-only lookups (see DropRedundantMessagesSessionIdIndex).
CREATE INDEX "IDX_399833392126349ef0b04b9bed" ON messages("sessionId", "createdAt");
CREATE INDEX "IDX_36bc604c820bb9adc4c75cd411" ON messages("chatId");
+CREATE INDEX "IDX_messages_sessionId_chatId_createdAt" ON messages("sessionId", "chatId", "createdAt");
CREATE INDEX "IDX_befd307485dbf0559d17e4a4d2" ON messages(status);
CREATE INDEX "IDX_messages_createdAt" ON messages("createdAt"); -- createdAt-only stats aggregates
@@ -703,7 +704,9 @@ These indexes are the ones declared on the entities (see §5.3); the rows below
| Get session by ID | `sessions.id` (PK) | Very High |
| Get session by name | `sessions.name` (UNIQUE) | High |
| List messages by session (paged) | `("sessionId", "createdAt")` composite | Very High |
-| Look up message by chat | `"chatId"` | High |
+| List a chat's messages (paged) | `IDX_messages_sessionId_chatId_createdAt` | Very High |
+| Send-pacing chat history probes | `IDX_messages_sessionId_chatId_createdAt` | Very High |
+| Search / stats by chat | `"chatId"` | Medium |
| Ack/dedup a message | `UQ_messages_sessionId_waMessageId` (UNIQUE) | Very High |
| Message stats over a date range | `IDX_messages_createdAt` | Medium |
| Find a session's webhooks | `IDX_webhooks_sessionId` | Very High |
@@ -715,6 +718,7 @@ These indexes are the ones declared on the entities (see §5.3); the rows below
```sql
-- messages: paged listing per session + ack-driven status update / inbound dedup
CREATE INDEX "IDX_399833392126349ef0b04b9bed" ON messages("sessionId", "createdAt");
+CREATE INDEX "IDX_messages_sessionId_chatId_createdAt" ON messages("sessionId", "chatId", "createdAt");
CREATE UNIQUE INDEX "UQ_messages_sessionId_waMessageId" ON messages("sessionId", "waMessageId");
CREATE INDEX "IDX_messages_createdAt" ON messages("createdAt");
@@ -865,6 +869,13 @@ src/database/migrations/ # data connection (pluggable)
├── 1785900000000-AddAutomationRules.ts # 14th migration table; FKs sessions ON DELETE CASCADE
├── 1786000000000-AddSessionNodeUrl.ts
├── 1786100000000-AddMessageMediaPathIndex.ts # partial index on messages.mediaPath (orphan sweep)
+├── 1786200000000-AddWebhookOutboxEvents.ts
+├── 1786300000000-AddWebhookDeliveryFailureLookupIndex.ts
+├── 1786400000000-AddChatStates.ts
+├── 1786500000000-ReKeyChatStatesBySessionId.ts
+├── 1786600000000-AddChatStateObserved.ts
+├── 1786600000000-AddSessionDesiredState.ts
+├── 1786700000000-AddMessagesSessionChatCreatedAtIndex.ts # (sessionId, chatId, createdAt): chat thread pages
└── 1786800000000-AddBaileysStoredMessagesSessionCreatedIdIndex.ts # (sessionId, createdAt, id) index for the Baileys store cap trim
```
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 0544ea0e1..fed295e0a 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -1045,8 +1045,9 @@ curl -H "X-API-Key: $API_KEY" \
```sql
-- Indexes ship with the schema (migrations) — there is nothing to add by hand. `messages`
--- carries ("sessionId", "createdAt"), ("chatId"), ("status"), ("createdAt") and a unique
--- ("sessionId", "waMessageId").
+-- carries ("sessionId", "createdAt"), ("sessionId", "chatId", "createdAt"), ("chatId"),
+-- ("status"), ("createdAt"), a partial ("mediaPath") where it is not null, a unique
+-- ("sessionId", "waMessageId"), and on PostgreSQL a GIN index on the full-text "body_ts" column.
-- PostgreSQL: refresh planner statistics on the hot tables
ANALYZE sessions;
diff --git a/src/database/migrations/1786700000000-AddMessagesSessionChatCreatedAtIndex.ts b/src/database/migrations/1786700000000-AddMessagesSessionChatCreatedAtIndex.ts
new file mode 100644
index 000000000..23af2dd74
--- /dev/null
+++ b/src/database/migrations/1786700000000-AddMessagesSessionChatCreatedAtIndex.ts
@@ -0,0 +1,35 @@
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+/**
+ * Composite index on `messages (sessionId, chatId, createdAt)`, backing one chat's thread: the
+ * paged message list with a chatId filter and its total, and the send-pacing history probes that
+ * filter on the same prefix. Without it both dialects walked every row of the session through the
+ * (sessionId, createdAt) or unique (sessionId, waMessageId) index and filtered chatId row by row.
+ *
+ * Same reasoning as AddMessageMediaPathIndex: hand-authored because `synchronize` is off for the
+ * data connection on PostgreSQL (and optional on SQLite). The explicit name matches the entity's
+ * @Index, so the synchronize and migration schema paths converge on one index. Idempotent via
+ * IF NOT EXISTS (supported by both dialects for indexes).
+ *
+ * Not CONCURRENTLY: the migration runs inside a transaction. On PostgreSQL the build holds a SHARE
+ * lock on messages, so inserts and ack updates wait until it finishes (reads do not); on SQLite the
+ * build locks the database file. Both last as long as the build over the existing rows.
+ */
+export class AddMessagesSessionChatCreatedAtIndex1786700000000 implements MigrationInterface {
+ name = 'AddMessagesSessionChatCreatedAtIndex1786700000000';
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ // The data pool boots with a runtime statement_timeout (default 30s), which a build over a large
+ // messages table can outlast. Lift it for this transaction only, like AddMessageMediaPathIndex.
+ if (queryRunner.dataSource.options.type === 'postgres') {
+ await queryRunner.query('SET LOCAL statement_timeout = 0');
+ }
+ await queryRunner.query(
+ `CREATE INDEX IF NOT EXISTS "IDX_messages_sessionId_chatId_createdAt" ON "messages" ("sessionId", "chatId", "createdAt")`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_messages_sessionId_chatId_createdAt"`);
+ }
+}
diff --git a/src/database/migrations/__tests__/1786700000000-AddMessagesSessionChatCreatedAtIndex.spec.ts b/src/database/migrations/__tests__/1786700000000-AddMessagesSessionChatCreatedAtIndex.spec.ts
new file mode 100644
index 000000000..feeeddb5b
--- /dev/null
+++ b/src/database/migrations/__tests__/1786700000000-AddMessagesSessionChatCreatedAtIndex.spec.ts
@@ -0,0 +1,69 @@
+import { DataSource } from 'typeorm';
+import { AddMessagesSessionChatCreatedAtIndex1786700000000 } from '../1786700000000-AddMessagesSessionChatCreatedAtIndex';
+
+describe('AddMessagesSessionChatCreatedAtIndex migration', () => {
+ let ds: DataSource;
+
+ beforeEach(async () => {
+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:' });
+ await ds.initialize();
+ // The messages columns this index touches, with the indexes the table already carries, so the
+ // plan checks below choose among the real alternatives.
+ await ds.query(
+ `CREATE TABLE "messages" ("id" varchar PRIMARY KEY NOT NULL, "sessionId" varchar NOT NULL, ` +
+ `"chatId" varchar NOT NULL, "waMessageId" varchar, "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
+ );
+ await ds.query(`CREATE INDEX "IDX_sess_created" ON "messages" ("sessionId", "createdAt")`);
+ await ds.query(`CREATE INDEX "IDX_chat" ON "messages" ("chatId")`);
+ await ds.query(`CREATE UNIQUE INDEX "UQ_sess_wa" ON "messages" ("sessionId", "waMessageId")`);
+ });
+
+ 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();
+ };
+
+ const plan = async (sql: string): Promise<string> => {
+ const rows = await ds.query<{ detail: string }[]>(`EXPLAIN QUERY PLAN ${sql}`, [
+ 's1',
+ ]);
+ return rows.map(r => r.detail).join(' | ');
+ };
+
+ it('creates the composite index', async () => {
+ await new AddMessagesSessionChatCreatedAtIndex1786700000000().up(ds.createQueryRunner());
+
+ expect(await indexNames()).toContain('IDX_messages_sessionId_chatId_createdAt');
+ });
+
+ it('is idempotent (re-running up is a no-op) and down() drops the index', async () => {
+ const runner = ds.createQueryRunner();
+ const migration = new AddMessagesSessionChatCreatedAtIndex1786700000000();
+
+ await migration.up(runner);
+ await expect(migration.up(runner)).resolves.toBeUndefined();
+ expect(await indexNames()).toContain('IDX_messages_sessionId_chatId_createdAt');
+
+ await migration.down(runner);
+ expect(await indexNames()).not.toContain('IDX_messages_sessionId_chatId_createdAt');
+ });
+
+ it("serves a chat's total and its pacing-history probe from the index", async () => {
+ await new AddMessagesSessionChatCreatedAtIndex1786700000000().up(ds.createQueryRunner());
+
+ expect(await plan(`SELECT COUNT(1) FROM "messages" WHERE "sessionId" = ? AND "chatId" IN (?, ?)`)).toContain(
+ 'IDX_messages_sessionId_chatId_createdAt (sessionId=? AND chatId=?)',
+ );
+ expect(
+ await plan(
+ `SELECT 1 FROM "messages" WHERE "sessionId" = ? AND "chatId" IN (?, ?) AND "createdAt" < datetime('now') LIMIT 1`,
+ ),
+ ).toContain('IDX_messages_sessionId_chatId_createdAt (sessionId=? AND chatId=? AND createdAt<?)');
+ });
+});
diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.ts
index 2093bc480..53f6f6471 100644
--- a/src/modules/message/entities/message.entity.ts
+++ b/src/modules/message/entities/message.entity.ts
@@ -34,6 +34,11 @@ export enum MessageStatus {
@Entity('messages')
@Index(['sessionId', 'createdAt'])
@Index(['chatId'])
+// One chat's thread, paged newest-first, and its total; the send-pacing history probes filter on the
+// same (sessionId, chatId, createdAt) prefix. The standalone chatId index stays for the search and
+// stats reads that filter on chatId without a session. The explicit name matches the migration that
+// creates it on synchronize-disabled deployments, so both schema paths converge on one index.
+@Index('IDX_messages_sessionId_chatId_createdAt', ['sessionId', 'chatId', 'createdAt'])
// Composite index for the ack-driven status UPDATE (scoped by sessionId + waMessageId).
// Without it every ack does a full table scan of a hot table.
@Index('UQ_messages_sessionId_waMessageId', ['sessionId', 'waMessageId'], { unique: true })
@@ -42,7 +47,8 @@ export class Message {
id!: string;
// No standalone @Index here: sessionId-only lookups are already served by the composite indexes
- // that lead with sessionId — (sessionId, createdAt) above and the unique (sessionId, waMessageId).
+ // that lead with sessionId: (sessionId, createdAt), (sessionId, chatId, createdAt) and the unique
+ // (sessionId, waMessageId).
@Column()
sessionId!: string;
diff --git a/src/modules/message/message-list-ordering.pg.spec.ts b/src/modules/message/message-list-ordering.pg.spec.ts
index a425e32dc..7958b2398 100644
--- a/src/modules/message/message-list-ordering.pg.spec.ts
+++ b/src/modules/message/message-list-ordering.pg.spec.ts
@@ -120,6 +120,26 @@ const POSTGRES_ENABLED = process.env.DATABASE_TYPE === 'postgres';
expect(distinct.size).toBe(ROWS); // no row repeated, and therefore none missed
});
+ /**
+ * A chat filter on a user id expands to several dialect candidates, which picks a SQLite-only sort
+ * key there. PostgreSQL must keep the plain one, so the chat-filtered walk runs on the real server.
+ */
+ it('walks one chat by its several dialect candidates in the same total order', async () => {
+ const served: string[] = [];
+ for (let offset = 0; offset < ROWS; offset += PAGE * 10) {
+ const { messages } = await service.getMessages(SESSION_ID, { chatId: '[email protected]', limit: PAGE, offset });
+ served.push(...messages.map(m => m.id));
+ }
+ const unfiltered: string[] = [];
+ for (let offset = 0; offset < ROWS; offset += PAGE * 10) {
+ const { messages } = await service.getMessages(SESSION_ID, { limit: PAGE, offset });
+ unfiltered.push(...messages.map(m => m.id));
+ }
+
+ expect(served).toHaveLength(ROWS / 10);
+ expect(served).toEqual(unfiltered);
+ });
+
/**
* The tiebreaker gives the list a total order; it does not stop the WINDOW drifting, because
* `offset` addresses a position by count. A message arriving mid-walk pushes every older row down
diff --git a/src/modules/message/message-list-plan.spec.ts b/src/modules/message/message-list-plan.spec.ts
new file mode 100644
index 000000000..8f6d9f683
--- /dev/null
+++ b/src/modules/message/message-list-plan.spec.ts
@@ -0,0 +1,133 @@
+import 'reflect-metadata';
+import { DataSource, Logger } from 'typeorm';
+import { MessageService } from './message.service';
+import { Message } from './entities/message.entity';
+import type { EngineRegistry } from '../../engine/engine-registry.service';
+import type { MessageProjector } from '../session/message-projector.service';
+import type { HookManager } from '../../core/hooks';
+import type { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import type { SendPacingService } from './send-pacing.service';
+import type { MessageSendService } from './message-send.service';
+
+/**
+ * A chat thread is read with a chatId IN (...) filter, and SQLite here never has planner statistics.
+ * Without them it walked the whole session through (sessionId, createdAt) to fill one chat's page,
+ * so the plans of the statements getMessages actually issues are pinned against the entity schema.
+ */
+describe('message list query plans on SQLite', () => {
+ let ds: DataSource;
+ let service: MessageService;
+ const queries: Array<{ sql: string; params?: unknown[] }> = [];
+
+ const logger: Logger = {
+ logQuery: (sql, params) => {
+ queries.push({ sql, params: params as unknown[] | undefined });
+ },
+ logQueryError: () => undefined,
+ logQuerySlow: () => undefined,
+ logSchemaBuild: () => undefined,
+ logMigration: () => undefined,
+ log: () => undefined,
+ };
+
+ beforeEach(async () => {
+ ds = new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [Message],
+ synchronize: true,
+ logging: ['query'],
+ logger,
+ });
+ await ds.initialize();
+ service = new MessageService(
+ ds.getRepository(Message),
+ {} as EngineRegistry,
+ {} as MessageProjector,
+ {} as HookManager,
+ {
+ findLidsForPhone: () => Promise.resolve([]),
+ findPhoneForLid: () => Promise.resolve(null),
+ } as unknown as LidMappingStoreService,
+ {} as SendPacingService,
+ {} as MessageSendService,
+ );
+ queries.length = 0;
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ /** The ordered, limited statement that picks the page. */
+ const pageQuery = (): { sql: string; params?: unknown[] } => {
+ const page = queries.find(q => q.sql.includes('ORDER BY') && q.sql.includes('LIMIT'));
+ expect(page).toBeDefined();
+ return page!;
+ };
+
+ /** EXPLAIN QUERY PLAN of the page select getMessages issued. */
+ const pagePlan = async (): Promise<string> => {
+ const page = pageQuery();
+ const rows = await ds.query<{ detail: string }[]>(`EXPLAIN QUERY PLAN ${page.sql}`, page.params);
+ return rows.map(r => r.detail).join(' | ');
+ };
+
+ const countPlan = async (): Promise<string> => {
+ const count = queries.find(q => q.sql.includes('COUNT('));
+ expect(count).toBeDefined();
+ const rows = await ds.query<{ detail: string }[]>(`EXPLAIN QUERY PLAN ${count!.sql}`, count!.params);
+ return rows.map(r => r.detail).join(' | ');
+ };
+
+ it('seeks one user chat through the (sessionId, chatId, createdAt) index', async () => {
+ // A user chat expands to several dialect candidates (@c.us and @s.whatsapp.net at least).
+ await service.getMessages('s1', { chatId: '[email protected]', limit: 50 });
+
+ expect(await pagePlan()).toContain('IDX_messages_sessionId_chatId_createdAt (sessionId=? AND chatId=?)');
+ expect(await countPlan()).toContain('IDX_messages_sessionId_chatId_createdAt (sessionId=? AND chatId=?)');
+ });
+
+ it('reads a single-candidate chat from the same index in order, with no sort', async () => {
+ await service.getMessages('s1', { chatId: '[email protected]', limit: 50 });
+
+ const plan = await pagePlan();
+ expect(plan).toContain('IDX_messages_sessionId_chatId_createdAt (sessionId=? AND chatId=?)');
+ expect(plan).not.toContain('TEMP B-TREE');
+ });
+
+ it('keeps the unfiltered list on the (sessionId, createdAt) index with no sort', async () => {
+ await service.getMessages('s1', { limit: 50 });
+
+ const plan = await pagePlan();
+ expect(plan).toContain('(sessionId=?)');
+ expect(plan).not.toContain('chatId');
+ expect(plan).not.toContain('TEMP B-TREE');
+ });
+
+ /**
+ * A sort evaluates its result columns for every matching row before the limit applies, so a size
+ * computed in the ordered statement read the stored payload of every row in the chat. The size is
+ * read by id for the page rows only, and as a byte count, which neither dialect has to load the
+ * payload for.
+ */
+ it('reads metadata sizes for the page rows only, outside the ordered statement', async () => {
+ const repo = ds.getRepository(Message);
+ await repo.save(
+ ['a', 'b', 'c'].map(n =>
+ repo.create({ sessionId: 's1', chatId: '[email protected]', waMessageId: n, from: 'x', to: 'y', body: n }),
+ ),
+ );
+ queries.length = 0;
+
+ const { messages } = await service.getMessages('s1', { chatId: '[email protected]', limit: 2 });
+
+ expect(messages).toHaveLength(2);
+ expect(pageQuery().sql).not.toMatch(/metadata/i);
+ const sizes = queries.filter(q => /LENGTH\(/i.test(q.sql));
+ expect(sizes).toHaveLength(1);
+ expect(sizes[0].sql).toMatch(/OCTET_LENGTH\(/);
+ expect(sizes[0].sql).not.toMatch(/(^|[^_])LENGTH\(/);
+ expect(sizes[0].sql).not.toContain('ORDER BY');
+ });
+});
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index 3ea933499..5e6fb2e25 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -277,6 +277,36 @@ describe('MessageService', () => {
delete (repository as unknown as { manager?: unknown }).manager;
});
+ /**
+ * The unary `+` sort key is SQLite-only. PostgreSQL has no unary `+` for timestamps, and TypeORM
+ * leaves the bare `message.createdAt` after it unquoted, so a chat page there would 500.
+ */
+ it('keeps the plain createdAt key for a multi-candidate chat on postgres', async () => {
+ const qb = makeCursorQb([{ id: 'm-2' } as Message]);
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+ (repository as unknown as { manager: unknown }).manager = {
+ connection: { options: { type: 'postgres' } },
+ };
+
+ await service.getMessages('sess-1', { chatId: '[email protected]' });
+
+ expect(qb.orderBy).toHaveBeenCalledWith('message.createdAt', 'DESC');
+ expect(qb.orderBy).not.toHaveBeenCalledWith('+message.createdAt', 'DESC');
+
+ delete (repository as unknown as { manager?: unknown }).manager;
+ });
+
+ it('takes createdAt out of index order for a multi-candidate chat on sqlite only', async () => {
+ const qb = makeCursorQb([{ id: 'm-2' } as Message]);
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+
+ await service.getMessages('sess-1', { chatId: '[email protected]' });
+ expect(qb.orderBy).toHaveBeenLastCalledWith('+message.createdAt', 'DESC');
+
+ await service.getMessages('sess-1', { chatId: '[email protected]' });
+ expect(qb.orderBy).toHaveBeenLastCalledWith('message.createdAt', 'DESC');
+ });
+
it('orders by rowid on sqlite, which is the arrival order and needs no sort', async () => {
const qb = makeCursorQb([{ id: 'm-2' } as Message]);
(repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index f3e5066b8..f0839bd81 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -298,11 +298,23 @@ export class MessageService implements PluginMessagePort {
const offset = typeof rawOffset === 'number' && Number.isFinite(rawOffset) ? Math.max(Math.trunc(rawOffset), 0) : 0;
const tiebreak = this.orderTiebreak;
+ // Match across dialects: a stored chatId may be `@s.whatsapp.net` (e.g. an outbound send addressed
+ // by a raw engine id) while the caller filters by the neutral `@c.us` from the chat list - same
+ // chat, different dialect. Resolving both sides through the table keeps them equal.
+ const chatIds = chatId ? await this.resolveJidCandidates(chatId) : undefined;
+ // SQLite has no planner statistics here (nothing runs ANALYZE), so with several chatId candidates
+ // it prefers the (sessionId, createdAt) index because it already yields the order, and walks the
+ // whole session filtering chatId row by row. The unary `+` takes createdAt out of index-order
+ // consideration, so it seeks (sessionId, chatId, createdAt) and sorts only that chat's rows, the
+ // plan ANALYZE would pick. A single candidate already uses that index in order, and PostgreSQL
+ // (no unary `+` on timestamps) has statistics, so both keep the plain key.
+ const createdAtKey =
+ tiebreak === 'rowid' && chatIds !== undefined && chatIds.length > 1 ? '+message.createdAt' : 'message.createdAt';
const query = this.messageRepository
.createQueryBuilder('message')
.where('message.sessionId = :sessionId', { sessionId })
- .orderBy('message.createdAt', 'DESC')
+ .orderBy(createdAtKey, 'DESC')
// `createdAt` is not unique: SQLite stores whole seconds, Postgres NOW() is transaction-scoped
// so a bulk write ties every row, and a history backfill stamps WhatsApp's own second-resolution
// timestamp. Without a tiebreaker the tie group's order is whatever the plan produces, and
@@ -318,11 +330,8 @@ export class MessageService implements PluginMessagePort {
query.skip(offset);
}
- if (chatId) {
- // Match across dialects: a stored chatId may be `@s.whatsapp.net` (e.g. an outbound send addressed
- // by a raw engine id) while the caller filters by the neutral `@c.us` from the chat list - same
- // chat, different dialect. Resolving both sides through the table keeps them equal.
- query.andWhere('message.chatId IN (:...chatIds)', { chatIds: await this.resolveJidCandidates(chatId) });
+ if (chatIds) {
+ query.andWhere('message.chatId IN (:...chatIds)', { chatIds });
}
if (from) {
diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.ts
index 40f3e6a5f..62e1c4b22 100644
--- a/src/modules/message/send-pacing.service.ts
+++ b/src/modules/message/send-pacing.service.ts
@@ -446,8 +446,9 @@ export class SendPacingService {
* Distinct chats this session started today: it sent to them today, nothing in the chat predates
* today, and nobody wrote to it first — a chat whose counterpart messaged earlier the same day is
* an answered conversation, not a reachout (the "cold" rule above), however new the chat is.
- * Expressed as NOT EXISTS probes so the outer query stays on the `(sessionId, createdAt)` and
- * `chatId` indexes; the only aggregate is a per-chat MIN over today's outgoing rows.
+ * Expressed as NOT EXISTS probes so the outer query stays on the `(sessionId, createdAt)` index
+ * and each probe seeks `(sessionId, chatId, createdAt)`; the only aggregate is a per-chat MIN over
+ * today's outgoing rows.
*/
private countColdReachoutsToday(sessionId: string, dayStart: Date): Promise<number> {
return (