Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(messages): bound cold reachouts separately from overall send volume

Yudhi Armyndharis00e0c4945015
diff --git a/.env.example b/.env.example
index c5f6ca531..d1fffce8e 100644
--- a/.env.example
+++ b/.env.example
@@ -195,6 +195,13 @@ BAILEYS_MARK_ONLINE_ON_CONNECT=true
# than you asked for. Counts come from the messages table, so they survive a restart.
# SEND_PACING_ENABLED=true
# SEND_PACING_WARMUP_SCHEDULE=20,40,80,160,320,640,1000
+#
+# SEND_PACING_COLD_DAILY_CAP bounds COLD REACHOUTS specifically — the first message to a chat this
+# account has no history with in either direction. Starting conversations with strangers is what
+# WhatsApp actually punishes (its own "reachout timelock" restriction targets exactly that), while
+# answering someone who wrote to you first is not a risk at all and is never counted here. Same
+# by-age shape as the schedule above; a single number is a flat cap; empty disables the rule.
+# SEND_PACING_COLD_DAILY_CAP=5,10,20,40,60,80,100
# SEND_PACING_BREAKER_THRESHOLD=5
# SEND_PACING_BREAKER_COOLDOWN_MS=900000
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 620988251..815f20889 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Send pacing now bounds cold reachouts separately** (`SEND_PACING_COLD_DAILY_CAP`). A send counts
+ as a cold reachout when the account has no history with that chat **in either direction**; a reply
+ to someone who wrote first is never counted and never refused by this rule, and status posts, which
+ address no chat, are exempt.
+
+ This is the rule that matches what WhatsApp actually punishes — its own reachout timelock exists
+ precisely for accounts that start conversations with strangers — so it ramps far more tightly than
+ the overall daily allowance and is checked after it. Refusals carry the same `429` +
+ `SEND_PACING_LIMITED`, distinguished in the metric and audit trail by `rule: cold_daily_cap`.
+
- **The dashboard shows account restrictions on the session card**, in all 12 locales. The row is
deliberately not gated on status, unlike the error row beside it: a reachout timelock applies to a
session that is perfectly `ready`, and hiding it behind a failure status would make it invisible in
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index c0537c1d2..48132143c 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1177,6 +1177,7 @@ When enabled, two rules can refuse a send:
| Rule | What it means |
|---|---|
| Warm-up daily cap | The session has used its allowance for the current **UTC** day. The allowance grows with the session's age (`SEND_PACING_WARMUP_SCHEDULE`), because a brand-new WhatsApp account that immediately sends at volume is the pattern that gets numbers banned. The count comes from the messages table, so it survives restarts. |
+| Cold-reachout cap | The session has used its allowance of **new conversations** for the UTC day (`SEND_PACING_COLD_DAILY_CAP`). A send is a cold reachout when the account has no history with that chat in **either** direction — replying to someone who wrote to you first is never counted, and never refused by this rule. Status posts address no chat and are exempt. |
| Failure breaker | Consecutive send failures reached `SEND_PACING_BREAKER_THRESHOLD`, which usually means WhatsApp has already started refusing this account. Sends resume after `SEND_PACING_BREAKER_COOLDOWN_MS`, or immediately after any send succeeds. |
A refusal is `429` with a body carrying **`code: "SEND_PACING_LIMITED"`** and `retryAfterSeconds`:
@@ -1185,7 +1186,7 @@ A refusal is `429` with a body carrying **`code: "SEND_PACING_LIMITED"`** and `r
{
"statusCode": 429,
"error": "Too Many Requests",
- "message": "Daily send allowance of 20 reached for a session 0 day(s) old",
+ "message": "Daily allowance of 5 new conversation(s) reached for a session 0 day(s) old",
"code": "SEND_PACING_LIMITED",
"retryAfterSeconds": 34521
}
diff --git a/src/common/metrics/send-pacing-metrics.ts b/src/common/metrics/send-pacing-metrics.ts
index 3ee94089a..616103cea 100644
--- a/src/common/metrics/send-pacing-metrics.ts
+++ b/src/common/metrics/send-pacing-metrics.ts
@@ -6,7 +6,7 @@
* series. Kept in process rather than derived from a table because no row is written for a send that
* never happened, and because a retention prune would read as a counter reset.
*/
-export type SendPacingRefusalReason = 'daily_cap' | 'breaker_open';
+export type SendPacingRefusalReason = 'daily_cap' | 'cold_daily_cap' | 'breaker_open';
const refusals = new Map<SendPacingRefusalReason, number>();
diff --git a/src/modules/catalog/catalog.service.ts b/src/modules/catalog/catalog.service.ts
index 398b82f80..4dd2864c4 100644
--- a/src/modules/catalog/catalog.service.ts
+++ b/src/modules/catalog/catalog.service.ts
@@ -46,7 +46,7 @@ export class CatalogService {
* change, but worth knowing when reading the counts.
*/
async sendProduct(sessionId: string, chatId: string, productId: string, body?: string): Promise<MessageResult> {
- await this.pacing.assertSendAllowed(sessionId);
+ await this.pacing.assertSendAllowed(sessionId, chatId);
const engine = this.engines.require(
sessionId,
() => new NotFoundException(`Session ${sessionId} not found or not connected`),
@@ -60,7 +60,7 @@ export class CatalogService {
* gains support does not silently open an unpaced send path.
*/
async sendCatalog(sessionId: string, chatId: string, body?: string): Promise<MessageResult> {
- await this.pacing.assertSendAllowed(sessionId);
+ await this.pacing.assertSendAllowed(sessionId, chatId);
const engine = this.engines.require(
sessionId,
() => new NotFoundException(`Session ${sessionId} not found or not connected`),
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index 6f22a5987..89028a20d 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -382,7 +382,7 @@ export class BulkMessageService implements OnApplicationBootstrap {
// Pacing runs BEFORE the moderation gate, matching MessageService: a send policy forbids is not
// offered to plugins at all. A refusal is a 429 that fails THIS item (honouring stopOnError),
// not the batch — the allowance may free up, and a batch killed outright could not resume.
- await this.pacing.assertSendAllowed(batch.sessionId);
+ await this.pacing.assertSendAllowed(batch.sessionId, msg.chatId);
// Per-message moderation gate — the SAME message:sending hook single sends use, so a
// compliance/moderation plugin sees bulk traffic too (bulk previously bypassed it entirely).
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 19ec95abe..b92ff3270 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -155,7 +155,9 @@ export class MessageService {
// not going to be sent. The consequence is deliberate and documented in the hook contract: a
// paced-out send fires no `message:sending`, so a plugin cannot observe it. Refusals are a 429
// carrying `code: SEND_PACING_LIMITED`; a plugin veto stays a 400.
- await this.pacing.assertSendAllowed(sessionId);
+ // Every gated sender's DTO carries `chatId` except `edit`, which addresses a message rather than
+ // a chat — and editing is never a reachout, so having no chatId there is exactly right.
+ await this.pacing.assertSendAllowed(sessionId, (input as { chatId?: string }).chatId);
return applySendingGate(this.hookManager, sessionId, type, input, 'MessageService');
}
diff --git a/src/modules/message/send-pacing-cold-query.spec.ts b/src/modules/message/send-pacing-cold-query.spec.ts
new file mode 100644
index 000000000..63038c268
--- /dev/null
+++ b/src/modules/message/send-pacing-cold-query.spec.ts
@@ -0,0 +1,129 @@
+import { DataSource } from 'typeorm';
+import { SendPacingService } from './send-pacing.service';
+import { Message, MessageDirection } from './entities/message.entity';
+import { Session } from '../session/entities/session.entity';
+import { computeSendPacingConfig } from './send-pacing.config';
+import type { ConfigService } from '@nestjs/config';
+
+/**
+ * The cold-reachout count is the one piece of this feature that cannot be proven with a mocked
+ * repository: it is a hand-written `NOT EXISTS` subquery, so a wrong column name, a wrong join
+ * predicate or an unquoted identifier compiles, passes every mocked test, and then throws on the
+ * first cold send in production.
+ *
+ * (It did: the subquery was first written against `session_id` / `chat_id` / `created_at`. Those
+ * columns do not exist — this connection has no snake_case naming strategy and the real columns are
+ * quoted camelCase — and nothing but a real database was ever going to say so.)
+ *
+ * So this spec drives an actual SQLite schema and asserts on rows, not on calls.
+ */
+describe('cold-reachout counting against a real database', () => {
+ let ds: DataSource;
+ let service: SendPacingService;
+
+ const DAY_MS = 86_400_000;
+ const NOW = new Date('2026-08-03T12:00:00.000Z');
+ const TODAY = '2026-08-03T09:00:00.000Z';
+ const YESTERDAY = '2026-08-02T09:00:00.000Z';
+
+ const config = (over: Record<string, unknown> = {}): ConfigService =>
+ ({
+ get: (key: string) =>
+ key === 'sendPacing'
+ ? { ...computeSendPacingConfig({}), enabled: true, warmupSchedule: [10_000], coldSchedule: [3], ...over }
+ : undefined,
+ }) as unknown as ConfigService;
+
+ const addMessage = (chatId: string, at: string, direction = MessageDirection.OUTGOING): Promise<unknown> =>
+ ds.query(
+ `INSERT INTO "messages" ("id","sessionId","chatId","from","to","type","direction","createdAt")
+ VALUES (?,?,?,'a','b','text',?,?)`,
+ [`${chatId}-${at}-${direction}`, 's1', chatId, direction, at],
+ );
+
+ beforeEach(async () => {
+ jest.useFakeTimers().setSystemTime(NOW);
+ ds = new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [Message, Session],
+ synchronize: true,
+ });
+ await ds.initialize();
+ // The session is old enough that only the cold rule can refuse anything.
+ await ds.getRepository(Session).save({ name: 'bot', id: 's1', createdAt: new Date(NOW.getTime() - 30 * DAY_MS) });
+ service = new SendPacingService(ds.getRepository(Message), ds.getRepository(Session), config());
+ });
+
+ afterEach(async () => {
+ jest.useRealTimers();
+ await ds.destroy();
+ });
+
+ it('counts a chat first written to today, and stops counting it once it has history', async () => {
+ await addMessage('[email protected]', TODAY);
+ await addMessage('[email protected]', TODAY);
+ // Written to today but known since yesterday — an ongoing conversation, not a reachout.
+ await addMessage('[email protected]', YESTERDAY);
+ await addMessage('[email protected]', TODAY);
+
+ // Two cold reachouts used of three: a third stranger is still allowed.
+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
+
+ await addMessage('[email protected]', TODAY);
+ await expect(service.assertSendAllowed('s1', '[email protected]')).rejects.toMatchObject({ status: 429 });
+ });
+
+ // The direction asymmetry is the whole point: someone writing to us first makes the chat warm,
+ // but their inbound message is not itself a reachout we made.
+ it('treats an inbound-first chat as warm without counting it as a reachout', async () => {
+ await addMessage('[email protected]', TODAY, MessageDirection.INCOMING);
+ await addMessage('[email protected]', TODAY, MessageDirection.INCOMING);
+ await addMessage('[email protected]', TODAY, MessageDirection.INCOMING);
+ await addMessage('[email protected]', TODAY, MessageDirection.INCOMING);
+
+ // Replying to any of them is never refused, however many there are…
+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
+ // …and none of them consumed the cold budget, so a stranger is still allowed.
+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
+ });
+
+ it("does not count another session's reachouts", async () => {
+ await ds.query(
+ `INSERT INTO "messages" ("id","sessionId","chatId","from","to","type","direction","createdAt")
+ VALUES ('other-1','s2','[email protected]','a','b','text','outgoing',?),
+ ('other-2','s2','[email protected]','a','b','text','outgoing',?),
+ ('other-3','s2','[email protected]','a','b','text','outgoing',?)`,
+ [TODAY, TODAY, TODAY],
+ );
+
+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
+ });
+
+ // Whether a chat is new is a question about THIS account, not the deployment: another session
+ // knowing the number says nothing about this one's relationship with it. If the history lookup
+ // were not scoped per session, a second session's older message would make this session's very
+ // first approach look like an ongoing conversation and free up budget it never earned.
+ it("does not let another session's older history make a chat look warm", async () => {
+ await addMessage('[email protected]', TODAY);
+ await addMessage('[email protected]', TODAY);
+ await addMessage('[email protected]', TODAY);
+ await ds.query(
+ `INSERT INTO "messages" ("id","sessionId","chatId","from","to","type","direction","createdAt")
+ VALUES ('s2-older','s2','[email protected]','a','b','text','outgoing',?)`,
+ [YESTERDAY],
+ );
+
+ // Three cold reachouts today, `[email protected]` among them — the budget of three is spent.
+ await expect(service.assertSendAllowed('s1', '[email protected]')).rejects.toMatchObject({ status: 429 });
+ });
+
+ it("forgets yesterday's reachouts when the UTC day rolls over", async () => {
+ await addMessage('[email protected]', YESTERDAY);
+ await addMessage('[email protected]', YESTERDAY);
+ await addMessage('[email protected]', YESTERDAY);
+ await addMessage('[email protected]', YESTERDAY);
+
+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
+ });
+});
diff --git a/src/modules/message/send-pacing.config.ts b/src/modules/message/send-pacing.config.ts
index a10f811f8..b806b6b3d 100644
--- a/src/modules/message/send-pacing.config.ts
+++ b/src/modules/message/send-pacing.config.ts
@@ -16,6 +16,16 @@ export interface SendPacingConfig {
* immediately sends at volume is the classic ban pattern, so the allowance starts small and grows.
*/
warmupSchedule: number[];
+ /**
+ * Daily allowance for **cold reachouts** — the first message to a chat this account has no history
+ * with in either direction. Same by-age shape as `warmupSchedule`, and a single number is a flat
+ * cap. Empty disables the rule.
+ *
+ * Separate from the overall cap because the two bound different risks. Answering people who
+ * already wrote to you is not what gets numbers banned; starting conversations with strangers is,
+ * and WhatsApp's own restriction for it (the reachout timelock) targets exactly that.
+ */
+ coldSchedule: number[];
/** Consecutive send failures that trip the breaker. */
breakerThreshold: number;
/** How long the breaker stays open before it lets traffic through again. */
@@ -24,6 +34,8 @@ export interface SendPacingConfig {
/** A cautious two-week ramp: ~1 message every 3 minutes on day one, ~2/minute by the second week. */
const DEFAULT_WARMUP_SCHEDULE = [20, 40, 80, 160, 320, 640, 1000];
+/** Deliberately far below the overall ramp: a stranger costs more standing than a reply does. */
+const DEFAULT_COLD_SCHEDULE = [5, 10, 20, 40, 60, 80, 100];
const DEFAULT_BREAKER_THRESHOLD = 5;
const DEFAULT_BREAKER_COOLDOWN_MS = 15 * 60_000;
@@ -41,11 +53,14 @@ const MIN_BREAKER_COOLDOWN_MS = 1000;
* silently different ramp than the operator wrote, and quietly sending more than intended is the one
* failure this feature exists to prevent.
*/
-function parseSchedule(raw: string | undefined): number[] {
- if (!raw?.trim()) return DEFAULT_WARMUP_SCHEDULE;
+function parseSchedule(raw: string | undefined, fallback: number[]): number[] {
+ // An explicit empty value is a deliberate "no rule", distinct from an unset one. Only the cold cap
+ // uses it; the overall cap has no off switch short of disabling pacing.
+ if (raw !== undefined && raw.trim() === '') return fallback === DEFAULT_COLD_SCHEDULE ? [] : fallback;
+ if (!raw) return fallback;
const parts = raw.split(',').map(part => Number(part.trim()));
if (parts.length === 0 || parts.some(n => !Number.isFinite(n) || n < MIN_DAILY_CAP || n > MAX_DAILY_CAP)) {
- return DEFAULT_WARMUP_SCHEDULE;
+ return fallback;
}
return parts.map(n => Math.floor(n));
}
@@ -60,7 +75,8 @@ function parsePositiveInt(raw: string | undefined, fallback: number, min: number
export function computeSendPacingConfig(env: NodeJS.ProcessEnv = process.env): SendPacingConfig {
return {
enabled: env.SEND_PACING_ENABLED === 'true',
- warmupSchedule: parseSchedule(env.SEND_PACING_WARMUP_SCHEDULE),
+ warmupSchedule: parseSchedule(env.SEND_PACING_WARMUP_SCHEDULE, DEFAULT_WARMUP_SCHEDULE),
+ coldSchedule: parseSchedule(env.SEND_PACING_COLD_DAILY_CAP, DEFAULT_COLD_SCHEDULE),
breakerThreshold: parsePositiveInt(
env.SEND_PACING_BREAKER_THRESHOLD,
DEFAULT_BREAKER_THRESHOLD,
diff --git a/src/modules/message/send-pacing.service.spec.ts b/src/modules/message/send-pacing.service.spec.ts
index d6294f77a..87fefa807 100644
--- a/src/modules/message/send-pacing.service.spec.ts
+++ b/src/modules/message/send-pacing.service.spec.ts
@@ -21,6 +21,7 @@ interface Harness {
service: SendPacingService;
count: jest.Mock;
findOne: jest.Mock;
+ exists: jest.Mock;
audit: { logWarn: jest.Mock; logInfo: jest.Mock };
}
@@ -28,21 +29,31 @@ const build = (
config: Partial<SendPacingConfig> = {},
sentToday = 0,
session: Session | null = sessionAged(0),
+ chat: { hasHistory?: boolean; coldToday?: number } = {},
): Harness => {
const count = jest.fn().mockResolvedValue(sentToday);
const findOne = jest.fn().mockResolvedValue(session);
+ // Default to a chat with history: most tests are about the overall cap, and a warm chat keeps the
+ // cold rule out of their way.
+ const exists = jest.fn().mockResolvedValue(chat.hasHistory ?? true);
+ const createQueryBuilder = jest.fn(() => {
+ const qb: Record<string, unknown> = {};
+ for (const method of ['select', 'where', 'andWhere']) qb[method] = jest.fn(() => qb);
+ qb.getRawOne = jest.fn().mockResolvedValue({ count: chat.coldToday ?? 0 });
+ return qb;
+ });
const configService = {
get: (key: string) =>
key === 'sendPacing' ? { ...computeSendPacingConfig({}), enabled: true, ...config } : undefined,
} as unknown as ConfigService;
const audit = { logWarn: jest.fn().mockResolvedValue(null), logInfo: jest.fn().mockResolvedValue(null) };
const service = new SendPacingService(
- { count } as unknown as Repository<Message>,
+ { count, exists, createQueryBuilder } as unknown as Repository<Message>,
{ findOne } as unknown as Repository<Session>,
configService,
audit as unknown as ConstructorParameters<typeof SendPacingService>[3],
);
- return { service, count, findOne, audit };
+ return { service, count, findOne, audit, exists };
};
/** The (action, context) pair of one audit call, typed so assertions do not fall back to `any`. */
@@ -295,7 +306,9 @@ describe('send paths consult the governor', () => {
await expect(service.sendText('s1', { chatId: '[email protected]', text: 'hi' })).rejects.toBeInstanceOf(HttpException);
- expect(pacing.assertSendAllowed).toHaveBeenCalledWith('s1');
+ // The recipient must reach the governor too: without it the cold-reachout rule has nothing to
+ // classify and silently degrades to the overall cap.
+ expect(pacing.assertSendAllowed).toHaveBeenCalledWith('s1', '[email protected]');
// The ordering decision, pinned: a paced-out send is never offered to plugins, so no
// `message:sending` fires and nothing is persisted or sent.
expect(hookManager.execute).not.toHaveBeenCalled();
@@ -367,7 +380,7 @@ describe('send paths consult the governor', () => {
await (service as unknown as { processBatch: (id: string) => Promise<void> }).processBatch('b1');
- expect(pacing.assertSendAllowed).toHaveBeenCalledWith('s1');
+ expect(pacing.assertSendAllowed).toHaveBeenCalledWith('s1', '[email protected]');
expect(hookManager.execute).not.toHaveBeenCalledWith('message:sending', expect.anything(), expect.anything());
expect(engine.sendTextMessage).not.toHaveBeenCalled();
});
@@ -443,3 +456,91 @@ describe('SendPacingService audit trail', () => {
expect(a.audit.logWarn).toHaveBeenCalledTimes(2);
});
});
+
+// Starting conversations with strangers is the behaviour WhatsApp actually punishes — its own
+// reachout timelock exists for exactly this — so cold reachouts get their own, far tighter budget
+// than replies do.
+describe('SendPacingService cold-reachout cap', () => {
+ beforeEach(() => resetSendPacingRefusals());
+
+ const cold = (over: Partial<SendPacingConfig> = {}): Partial<SendPacingConfig> => ({
+ warmupSchedule: [1000],
+ coldSchedule: [3],
+ ...over,
+ });
+
+ // The distinction the whole rule rests on: replying to someone who wrote to you first is not a
+ // reachout, and throttling it would suppress exactly the traffic WhatsApp wants to see.
+ it('does not count a chat this account already has history with', async () => {
+ const { service, exists } = build(cold(), 0, sessionAged(0), { hasHistory: true, coldToday: 99 });
+
+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
+
+ expect(exists).toHaveBeenCalledWith({ where: { sessionId: 's1', chatId: '[email protected]' } });
+ });
+
+ it("allows a cold reachout while the day's allowance remains", async () => {
+ const { service } = build(cold(), 0, sessionAged(0), { hasHistory: false, coldToday: 2 });
+
+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
+ });
+
+ it('refuses the cold reachout that would exceed the allowance', async () => {
+ const { service } = build(cold(), 0, sessionAged(0), { hasHistory: false, coldToday: 3 });
+
+ const body = await expectPacingRefusal(service.assertSendAllowed('s1', '[email protected]'));
+
+ expect(body.code).toBe(SEND_PACING_LIMITED);
+ expect(body.message).toContain('new conversation');
+ });
+
+ // The cold budget ramps with account age on the same principle as the overall one.
+ it('grows the cold allowance with the session age', async () => {
+ const young = build(cold({ coldSchedule: [3, 30] }), 0, sessionAged(0), { hasHistory: false, coldToday: 5 });
+ await expectPacingRefusal(young.service.assertSendAllowed('s1', '[email protected]'));
+
+ const older = build(cold({ coldSchedule: [3, 30] }), 0, sessionAged(1), { hasHistory: false, coldToday: 5 });
+ await expect(older.service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
+ });
+
+ // A status post addresses no one in particular, so it is not a reachout and must never consume the
+ // budget meant for first contacts.
+ it('does not apply to a send with no recipient, and does not probe for one', async () => {
+ const { service, exists } = build(cold(), 0, sessionAged(0), { hasHistory: false, coldToday: 999 });
+
+ await expect(service.assertSendAllowed('s1')).resolves.toBeUndefined();
+
+ expect(exists).not.toHaveBeenCalled();
+ });
+
+ it('is disabled by an empty cold schedule, without probing the chat', async () => {
+ const { service, exists } = build(cold({ coldSchedule: [] }), 0, sessionAged(0), {
+ hasHistory: false,
+ coldToday: 999,
+ });
+
+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
+
+ expect(exists).not.toHaveBeenCalled();
+ });
+
+ // The overall cap is the cheaper check and bounds everything, so it must settle first — a session
+ // over its total budget should not also pay for the cold probe.
+ it('lets the overall cap refuse first, without probing the chat', async () => {
+ const { service, exists } = build(cold({ warmupSchedule: [1] }), 5, sessionAged(0), { hasHistory: false });
+
+ const body = await expectPacingRefusal(service.assertSendAllowed('s1', '[email protected]'));
+
+ expect(body.message).toContain('Daily send allowance');
+ expect(exists).not.toHaveBeenCalled();
+ });
+
+ it('counts the refusal under its own rule', async () => {
+ const { service, audit } = build(cold(), 0, sessionAged(0), { hasHistory: false, coldToday: 3 });
+
+ await expectPacingRefusal(service.assertSendAllowed('s1', '[email protected]'));
+
+ expect(getSendPacingRefusals().get('cold_daily_cap')).toBe(1);
+ expect(auditCall(audit.logWarn)[1].metadata).toMatchObject({ rule: 'cold_daily_cap' });
+ });
+});
diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.ts
index b3adfb2dc..8e0c157f0 100644
--- a/src/modules/message/send-pacing.service.ts
+++ b/src/modules/message/send-pacing.service.ts
@@ -83,12 +83,13 @@ export class SendPacingService {
* When the feature is off this returns before doing anything at all — no query, no map lookup — so
* a deployment that has not opted in behaves exactly as it did before the governor existed.
*/
- async assertSendAllowed(sessionId: string): Promise<void> {
+ async assertSendAllowed(sessionId: string, chatId?: string): Promise<void> {
const config = resolveSendPacingConfig(this.configService);
if (!config.enabled) return;
this.assertBreakerClosed(sessionId, config);
await this.assertUnderDailyCap(sessionId, config);
+ await this.assertUnderColdCap(sessionId, chatId, config);
}
/**
@@ -134,9 +135,9 @@ export class SendPacingService {
}
/** The allowance for a session this many whole days old, saturating at the schedule's last entry. */
- private allowanceForAge(config: SendPacingConfig, ageDays: number): number {
- const index = Math.min(Math.max(ageDays, 0), config.warmupSchedule.length - 1);
- return config.warmupSchedule[index];
+ private allowanceForAge(schedule: number[], ageDays: number): number {
+ const index = Math.min(Math.max(ageDays, 0), schedule.length - 1);
+ return schedule[index];
}
private breakerFor(sessionId: string): BreakerState {
@@ -173,7 +174,7 @@ export class SendPacingService {
// Age from createdAt, NOT connectedAt: connectedAt is overwritten on every connect, so a session
// that reconnects would look one day old forever and never leave the first rung of the ramp.
const ageDays = Math.floor((dayStart.getTime() - startOfUtcDay(session.createdAt).getTime()) / DAY_MS);
- const allowance = this.allowanceForAge(config, ageDays);
+ const allowance = this.allowanceForAge(config.warmupSchedule, ageDays);
const sentToday = await this.messageRepository.count({
where: { sessionId, direction: MessageDirection.OUTGOING, createdAt: MoreThanOrEqual(dayStart) },
@@ -221,6 +222,70 @@ export class SendPacingService {
});
}
+ /**
+ * Refuse a cold reachout once the day's allowance for them is spent.
+ *
+ * "Cold" means this account has no history with the chat in EITHER direction: answering someone
+ * who wrote to you first is not a reachout, and counting it as one would throttle exactly the
+ * traffic WhatsApp wants to see. A chat with no `chatId` (a status post) is not addressed to
+ * anyone, so the rule does not apply to it.
+ *
+ * The cheap probe runs first and settles most sends in one indexed lookup; the aggregate that
+ * counts the day's cold reachouts only runs when this send is itself cold.
+ */
+ private async assertUnderColdCap(
+ sessionId: string,
+ chatId: string | undefined,
+ config: SendPacingConfig,
+ ): Promise<void> {
+ if (!chatId || config.coldSchedule.length === 0) return;
+
+ // Any row at all, either direction, any time: one message from them, or one from us last month,
+ // and this is an existing relationship rather than a reachout. The send being checked has not
+ // persisted its own row yet — the gate runs before saveOutgoingMessage — so this cannot see it.
+ const hasHistory = await this.messageRepository.exists({ where: { sessionId, chatId } });
+ if (hasHistory) return;
+
+ const session = await this.sessionRepository.findOne({ where: { id: sessionId } });
+ if (!session) return;
+
+ const dayStart = startOfUtcDay(new Date());
+ const ageDays = Math.floor((dayStart.getTime() - startOfUtcDay(session.createdAt).getTime()) / DAY_MS);
+ const allowance = this.allowanceForAge(config.coldSchedule, ageDays);
+ const coldToday = await this.countColdReachoutsToday(sessionId, dayStart);
+ if (coldToday < allowance) return;
+
+ this.refuse('cold_daily_cap', sessionId, secondsUntilNextUtcDay(), {
+ reason: `Daily allowance of ${allowance} new conversation(s) reached for a session ${ageDays} day(s) old`,
+ allowance,
+ coldToday,
+ });
+ }
+
+ /**
+ * Distinct chats this session started today: it sent to them today, and nothing in the chat
+ * predates today. Expressed as a NOT EXISTS rather than a `MIN(createdAt)` group-by so it stays on
+ * the `(sessionId, createdAt)` and `chatId` indexes instead of grouping the whole table.
+ */
+ private countColdReachoutsToday(sessionId: string, dayStart: Date): Promise<number> {
+ return (
+ this.messageRepository
+ .createQueryBuilder('m')
+ .select('COUNT(DISTINCT m.chatId)', 'count')
+ .where('m.sessionId = :sessionId', { sessionId })
+ .andWhere('m.direction = :direction', { direction: MessageDirection.OUTGOING })
+ .andWhere('m.createdAt >= :dayStart', { dayStart })
+ // Identifiers are quoted because the columns really are camelCase (`"chatId"`, not `chat_id`)
+ // — there is no snake_case naming strategy on this connection. Unquoted, Postgres would fold
+ // them to lowercase and the query would fail at runtime on the very first cold send.
+ .andWhere(
+ 'NOT EXISTS (SELECT 1 FROM "messages" p WHERE p."sessionId" = :sessionId AND p."chatId" = m."chatId" AND p."createdAt" < :dayStart)',
+ )
+ .getRawOne<{ count: string | number }>()
+ .then(row => Number(row?.count ?? 0))
+ );
+ }
+
private refuse(
reason: SendPacingRefusalReason,
sessionId: string,