Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(messages): pace outbound sends to protect young and struggling accounts

Yudhi Armyndharis75d49d079cf3
diff --git a/.env.example b/.env.example
index edded5c24..c5f6ca531 100644
--- a/.env.example
+++ b/.env.example
@@ -183,6 +183,21 @@ BAILEYS_MARK_ONLINE_ON_CONNECT=true
# SIMULATE_TYPING=false
# SIMULATE_TYPING_MAX_MS=5000
+# Outbound send pacing (anti-ban). OFF by default — nothing is refused unless you opt in. When on,
+# a session may send at most its warm-up allowance per UTC day, and a run of consecutive send
+# failures pauses it. Refusals are HTTP 429 with `code: SEND_PACING_LIMITED` and `retryAfterSeconds`,
+# which is what tells them apart from the global rate limiter's own 429.
+#
+# SEND_PACING_WARMUP_SCHEDULE is the per-day allowance by session age in days: the first entry is the
+# session's first day, and the last entry applies to every day after that. It starts small because a
+# brand-new WhatsApp account that immediately sends at volume is the pattern that gets numbers
+# banned. Any malformed entry falls the WHOLE schedule back to the default rather than sending more
+# 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_BREAKER_THRESHOLD=5
+# SEND_PACING_BREAKER_COOLDOWN_MS=900000
+
# Inline @lid -> phone resolution (#263). When a sender is identified by a WhatsApp privacy id
# (@lid) instead of a phone number, attach a best-effort `senderPhone` (MSISDN digits, or null when
# the engine can't map it) to the message.received webhook + websocket payload. OFF by default —
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d6cc1181b..25b4df3d4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Opt-in send pacing, to keep a young or struggling account from sending its way into a ban:**
+ `SEND_PACING_ENABLED=false` by default, so nothing changes until you turn it on. When enabled, two
+ rules can refuse an outbound send:
+
+ - a **warm-up daily cap** whose allowance grows with the session's age
+ (`SEND_PACING_WARMUP_SCHEDULE`), because a brand-new account that immediately sends at volume is
+ the pattern that gets numbers banned;
+ - a **failure breaker** that pauses sending after `SEND_PACING_BREAKER_THRESHOLD` consecutive send
+ failures — usually the sign that WhatsApp has already started refusing the account — and releases
+ after a cooldown or on the first success.
+
+ Refusals are `429` carrying `code: "SEND_PACING_LIMITED"` and `retryAfterSeconds`. That code is what
+ separates them from the global rate limiter's own `429`, which carries none: the throttler's clears
+ in seconds, a daily cap does not. Refusals are counted per rule in the new
+ `openwa_send_pacing_refusals_total` Prometheus counter.
+
+ It covers every path that reaches WhatsApp with a message: all the `send-*` routes and `edit`, bulk
+ batches, status posts, and `send-product` — the last of which never went through the message
+ service and so had no moderation gate either. Inside a batch a refusal fails just that item, not
+ the batch, since the allowance may free up and a killed batch cannot be resumed. Reactions, poll
+ votes, pins and deletes are deliberately not paced: they act on conversations that already exist,
+ which is not the traffic that gets accounts banned.
+
+ **Plugin-visible behaviour change:** the pacing check runs *before* the `message:sending` hook, so a
+ paced-out send does not fire it. Plugins are not asked to moderate, and cannot rewrite, traffic that
+ policy already forbids — but a plugin treating that hook as a complete record of send *attempts*
+ will no longer see refused ones. It remains complete for sends actually attempted against WhatsApp.
+ A plugin veto is still `400`.
+
+ Daily counts are read from the messages table rather than a counter of their own, so they survive
+ restarts, cannot drift from what was really sent, and needed no new table or migration.
+
- **WhatsApp-imposed account restrictions are now surfaced, instead of being lost inside a generic
disconnect:** a new `restriction` field on every session response, a `session.restriction` webhook,
and an `openwa_sessions_restricted` Prometheus gauge. Modelled in the JavaScript, Python, Go and
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 5e9079393..c0537c1d2 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1166,6 +1166,42 @@ Get the processing status and progress of a bulk batch.
**Errors:** `401` missing/invalid API key · `404` batch not found for this session
+### Send pacing (opt-in, `429 SEND_PACING_LIMITED`)
+
+Every outbound send — the `messages/send-*` routes, `messages/edit`, bulk batches, status posts and
+`messages/send-product` — passes an optional pacing governor before it reaches WhatsApp. It is **off
+by default**: unless `SEND_PACING_ENABLED=true`, nothing is refused and no extra work is done.
+
+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. |
+| 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`:
+
+```json
+{
+ "statusCode": 429,
+ "error": "Too Many Requests",
+ "message": "Daily send allowance of 20 reached for a session 0 day(s) old",
+ "code": "SEND_PACING_LIMITED",
+ "retryAfterSeconds": 34521
+}
+```
+
+The `code` is what distinguishes it from the **global rate limiter's** own `429`, which carries no
+`code`. The difference matters to a client: the throttler's 429 clears in seconds, a daily cap does
+not. Do not retry a `SEND_PACING_LIMITED` response before `retryAfterSeconds`.
+
+Inside a bulk batch a refusal fails just that item (honouring `stopOnError`), not the batch — the
+allowance may free up, and a batch killed outright could not be resumed.
+
+Two consequences worth knowing: a paced-out send fires **no** `message:sending` plugin hook (see
+`docs/19-plugin-architecture.md`), and refusals are counted in the `openwa_send_pacing_refusals_total`
+Prometheus counter, labelled by rule.
+
#### POST /api/sessions/:sessionId/messages/send-text
Send a plain text message.
diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.md
index 6b52a249a..114da184f 100644
--- a/docs/19-plugin-architecture.md
+++ b/docs/19-plugin-architecture.md
@@ -410,6 +410,14 @@ On a **pre-action** event it is a veto, because the action has not been taken ye
`message:sending` blocks the send (the caller gets a `400`), and on `webhook:before` it cancels that one
delivery.
+> **`message:sending` does not see every attempted send.** With send pacing enabled
+> (`SEND_PACING_ENABLED`), the pacing governor runs *before* this hook, so a send it refuses never
+> fires `message:sending` — plugins are not asked to moderate, and cannot rewrite, traffic that
+> policy already forbids. Treat the hook as a complete record of sends **actually attempted against
+> WhatsApp**, not of send *requests*. A paced-out request surfaces to the caller as `429` with
+> `code: SEND_PACING_LIMITED`; a plugin veto stays `400`. Pacing is off by default, so a deployment
+> that has not opted in sees the hook fire exactly as before.
+
> Until 0.10.5, `continue: false` on the two notification events also skipped persistence, the webhook
> and the websocket emit. An auto-reply plugin returning it for its ordinary purpose therefore erased
> the triggering message from the dashboard's chat history and from every integration downstream. If you
diff --git a/src/common/metrics/send-pacing-metrics.ts b/src/common/metrics/send-pacing-metrics.ts
new file mode 100644
index 000000000..3ee94089a
--- /dev/null
+++ b/src/common/metrics/send-pacing-metrics.ts
@@ -0,0 +1,30 @@
+/**
+ * Sends the pacing governor refused, by the rule that refused them.
+ *
+ * A counter rather than a gauge: each refusal is a discrete event, and what an operator wants is the
+ * rate — "we started hitting the daily cap at 14:00" — which `rate()` only answers over a monotonic
+ * 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';
+
+const refusals = new Map<SendPacingRefusalReason, number>();
+
+/** Record one refused send. */
+export function incrementSendPacingRefusals(reason: SendPacingRefusalReason): void {
+ refusals.set(reason, (refusals.get(reason) ?? 0) + 1);
+}
+
+/**
+ * Refusal totals by reason since process start. Reasons that have never fired are absent rather than
+ * zero, matching the HTTP metrics' behaviour of emitting nothing until something is observed — a
+ * series that appears at its first occurrence is easier to alert on than one pinned at zero.
+ */
+export function getSendPacingRefusals(): ReadonlyMap<SendPacingRefusalReason, number> {
+ return refusals;
+}
+
+/** Test-only: the counters are module-global and never reset in production. */
+export function resetSendPacingRefusals(): void {
+ refusals.clear();
+}
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index d57fb1e51..a69622b2a 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -1,5 +1,6 @@
import * as path from 'path';
import { computeFeatureFlags } from './feature-flags';
+import { computeSendPacingConfig } from '../modules/message/send-pacing.config';
import { resolveInflightBodyBudgetBytes } from './inflight-body-budget';
import { readWsRateLimitConfig } from '../modules/events/ws-rate-limit';
@@ -114,6 +115,10 @@ export default () => ({
// full set is discoverable via ConfigService (`features.*`) instead of scattered process.env reads.
features: computeFeatureFlags(),
+ // Outbound send pacing. Its own object rather than a feature flag: every field needs clamping,
+ // because a bad value here decides whether messages are refused. See message/send-pacing.config.ts.
+ sendPacing: computeSendPacingConfig(),
+
// Redis configuration
redis: {
host: process.env.REDIS_HOST || 'localhost',
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index a3ba82765..5f2e45712 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -243,6 +243,9 @@ export function validateEnv(config: EnvConfig): EnvConfig {
// Read by the SSRF guard's redirect loop with `=== 'true'`: a typo silently keeps the secure
// default, but an accidental 'true'-ish string is not the flag the operator meant to audit.
'PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS',
+ // Read with `=== 'true'`, so a typo leaves sends unpaced — the silent failure this whole
+ // feature exists to avoid, and invisible without this check.
+ 'SEND_PACING_ENABLED',
]) {
checkBool(key);
}
diff --git a/src/core/hooks/sending-gate.ts b/src/core/hooks/sending-gate.ts
index 0e7203269..2a48c2fbd 100644
--- a/src/core/hooks/sending-gate.ts
+++ b/src/core/hooks/sending-gate.ts
@@ -14,6 +14,14 @@ import { HookManager } from './hook-manager.service';
* cannot express. If you change the gate's semantics here, change it there too
* (`bulk-message.service.ts`, the `blockedByPlugin` branch).
*
+ * CONTRACT NOTE — the gate does NOT see every attempted send. When send pacing is enabled
+ * (`SEND_PACING_ENABLED`), the pacing governor runs BEFORE this gate at every call site, so a send
+ * it refuses fires no `message:sending` at all: a plugin cannot observe, moderate or rewrite traffic
+ * that policy already forbids. A plugin treating this hook as a complete record of send ATTEMPTS
+ * will therefore miss paced-out ones; it remains a complete record of sends that were actually
+ * attempted against WhatsApp. Refusals surface to the client as `429` with `code:
+ * SEND_PACING_LIMITED`, distinct from a plugin veto's `400`.
+ *
* `source` names the caller in the hook context so a plugin can tell a chat send from a status
* post without inspecting the payload shape — which matters because the shapes differ: a
* MessageService `input` is a send DTO carrying `chatId`, a StatusService `input` is not.
diff --git a/src/modules/catalog/catalog.module.ts b/src/modules/catalog/catalog.module.ts
index 161cdd60b..6f74f05a9 100644
--- a/src/modules/catalog/catalog.module.ts
+++ b/src/modules/catalog/catalog.module.ts
@@ -1,8 +1,10 @@
import { Module } from '@nestjs/common';
+import { MessageModule } from '../message/message.module';
import { CatalogController } from './catalog.controller';
import { CatalogService } from './catalog.service';
@Module({
+ imports: [MessageModule],
controllers: [CatalogController],
providers: [CatalogService],
exports: [CatalogService],
diff --git a/src/modules/catalog/catalog.service.ts b/src/modules/catalog/catalog.service.ts
index 505dc880c..398b82f80 100644
--- a/src/modules/catalog/catalog.service.ts
+++ b/src/modules/catalog/catalog.service.ts
@@ -6,10 +6,14 @@ import type {
PaginatedProducts,
MessageResult,
} from '../../engine/interfaces/whatsapp-engine.interface';
+import { SendPacingService } from '../message/send-pacing.service';
@Injectable()
export class CatalogService {
- constructor(private readonly engines: EngineRegistry) {}
+ constructor(
+ private readonly engines: EngineRegistry,
+ private readonly pacing: SendPacingService,
+ ) {}
async getCatalog(sessionId: string): Promise<Catalog | null> {
const engine = this.engines.require(
@@ -35,7 +39,14 @@ export class CatalogService {
return engine.getProduct(productId);
}
+ /**
+ * Sending a product is a real outbound chat message, not a catalog read, so it is paced like every
+ * other send. It does NOT go through MessageService, which is why the pacing call has to be here:
+ * this path persists no row and fires no message hooks either — deliberately out of scope for this
+ * 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);
const engine = this.engines.require(
sessionId,
() => new NotFoundException(`Session ${sessionId} not found or not connected`),
@@ -43,7 +54,13 @@ export class CatalogService {
return engine.sendProduct(chatId, productId, body);
}
+ /**
+ * Paced for the same reason as sendProduct. Both engines answer 501 today, so the adapter refuses
+ * before any traffic leaves — but the route is live, and pacing it now means the day an engine
+ * 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);
const engine = this.engines.require(
sessionId,
() => new NotFoundException(`Session ${sessionId} not found or not connected`),
diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.ts
index 8d6afa23e..7010d470d 100644
--- a/src/modules/message/bulk-message.service.spec.ts
+++ b/src/modules/message/bulk-message.service.spec.ts
@@ -14,6 +14,7 @@ import { SendBulkMessageDto } from './dto/bulk-message.dto';
import { EngineRegistry } from '../../engine/engine-registry.service';
import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
import { MessageService } from './message.service';
+import { SendPacingService } from './send-pacing.service';
import { HookManager } from '../../core/hooks';
import { SsrfBlockedError } from '../../common/security/ssrf-guard';
@@ -70,6 +71,12 @@ describe('BulkMessageService.onApplicationBootstrap', () => {
{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },
EngineRegistry,
{ provide: MessageService, useValue: { saveOutgoingMessage: jest.fn() } },
+ {
+ // Pacing is off by default; its own spec covers the governor. Here it must simply not
+ // refuse, so the bulk assertions exercise the paths they were written for.
+ provide: SendPacingService,
+ useValue: { assertSendAllowed: jest.fn().mockResolvedValue(undefined) },
+ },
{
provide: HookManager,
useValue: {
@@ -167,6 +174,10 @@ describe('BulkMessageService.processBatch', () => {
{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },
{ provide: EngineRegistry, useValue: engines },
{ provide: MessageService, useValue: messageService },
+ {
+ provide: SendPacingService,
+ useValue: { assertSendAllowed: jest.fn().mockResolvedValue(undefined) },
+ },
{ provide: HookManager, useValue: hookManager },
],
}).compile();
@@ -579,6 +590,10 @@ describe('BulkMessageService.cancelBatch', () => {
{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },
EngineRegistry,
{ provide: MessageService, useValue: {} },
+ {
+ provide: SendPacingService,
+ useValue: { assertSendAllowed: jest.fn().mockResolvedValue(undefined) },
+ },
{ provide: HookManager, useValue: { execute: jest.fn() } },
],
}).compile();
@@ -654,6 +669,10 @@ describe('BulkMessageService.createBatch base64 media cap', () => {
{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },
{ provide: EngineRegistry, useValue: engines },
{ provide: MessageService, useValue: messageService },
+ {
+ provide: SendPacingService,
+ useValue: { assertSendAllowed: jest.fn().mockResolvedValue(undefined) },
+ },
{
provide: HookManager,
useValue: {
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index e1162f7db..6f22a5987 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -13,6 +13,7 @@ import { SendBulkMessageDto } from './dto/bulk-message.dto';
import { MessageStatus } from './entities/message.entity';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { MessageService } from './message.service';
+import { SendPacingService } from './send-pacing.service';
import { HookManager } from '../../core/hooks';
import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';
import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';
@@ -89,6 +90,7 @@ export class BulkMessageService implements OnApplicationBootstrap {
private readonly engines: EngineRegistry,
private readonly messageService: MessageService,
private readonly hookManager: HookManager,
+ private readonly pacing: SendPacingService,
) {}
/**
@@ -377,6 +379,11 @@ export class BulkMessageService implements OnApplicationBootstrap {
// Apply template variables
content = this.applyVariables(msg.content, msg.variables);
+ // 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);
+
// 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).
// A block fails just THIS message (honouring stopOnError below); a plugin may also rewrite it.
diff --git a/src/modules/message/message.module.ts b/src/modules/message/message.module.ts
index 4353019be..d9d145b3f 100644
--- a/src/modules/message/message.module.ts
+++ b/src/modules/message/message.module.ts
@@ -9,12 +9,25 @@ import { SessionModule } from '../session/session.module';
import { TemplateModule } from '../template/template.module';
import { ChatMediaModule } from '../chat-media/chat-media.module';
import { Message } from './entities/message.entity';
+import { Session } from '../session/entities/session.entity';
+import { SendPacingService } from './send-pacing.service';
import { MessageBatch } from './entities/message-batch.entity';
@Module({
- imports: [TypeOrmModule.forFeature([Message, MessageBatch], 'data'), SessionModule, TemplateModule, ChatMediaModule],
+ imports: [
+ TypeOrmModule.forFeature([Message, MessageBatch, Session], 'data'),
+ SessionModule,
+ TemplateModule,
+ ChatMediaModule,
+ ],
controllers: [MessageController],
- providers: [MessageService, BulkMessageService, MessageTypeBackfillService, PendingMessageReaperService],
- exports: [MessageService, BulkMessageService],
+ providers: [
+ MessageService,
+ BulkMessageService,
+ MessageTypeBackfillService,
+ PendingMessageReaperService,
+ SendPacingService,
+ ],
+ exports: [MessageService, BulkMessageService, SendPacingService],
})
export class MessageModule {}
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index 2694641e1..dc136efc0 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -13,6 +13,15 @@ import { TemplateService } from '../template/template.service';
import { Template } from '../template/entities/template.entity';
import { SsrfBlockedError } from '../../common/security/ssrf-guard';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import { SendPacingService } from './send-pacing.service';
+
+/** Pacing is off by default in these tests; the governor's own spec covers its behaviour. */
+const inertPacing = (): SendPacingService =>
+ ({
+ assertSendAllowed: jest.fn().mockResolvedValue(undefined),
+ recordSendFailure: jest.fn(),
+ recordSendSuccess: jest.fn(),
+ }) as unknown as SendPacingService;
const mockEngineResult = { id: 'wa-msg-1', timestamp: 1706868000 };
@@ -101,6 +110,14 @@ describe('MessageService', () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
MessageService,
+ {
+ provide: SendPacingService,
+ useValue: {
+ assertSendAllowed: jest.fn().mockResolvedValue(undefined),
+ recordSendFailure: jest.fn(),
+ recordSendSuccess: jest.fn(),
+ },
+ },
{ provide: getRepositoryToken(Message, 'data'), useValue: repository },
{ provide: SessionService, useValue: sessionService },
{ provide: EngineRegistry, useValue: engines },
@@ -404,7 +421,7 @@ describe('MessageService', () => {
it('honors a configured template.renderMaxChars override', async () => {
const configService = {
get: (key: string, fallback: unknown) => (key === 'template.renderMaxChars' ? 10 : fallback),
- } as unknown as ConstructorParameters<typeof MessageService>[7];
+ } as unknown as ConstructorParameters<typeof MessageService>[8];
const capped = new MessageService(
repository as Repository<Message>,
sessionService as unknown as SessionService,
@@ -413,6 +430,7 @@ describe('MessageService', () => {
hookManager as HookManager,
templateService as unknown as TemplateService,
lidMappingStore as unknown as LidMappingStoreService,
+ inertPacing(),
configService,
);
(templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hello {{customer}}' }));
@@ -1492,6 +1510,7 @@ describe('MessageService', () => {
hookManager as HookManager,
templateService as unknown as TemplateService,
lidMappingStore as unknown as LidMappingStoreService,
+ inertPacing(),
undefined,
archive as never,
store as never,
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index be3bcfb62..19ec95abe 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -12,6 +12,7 @@ import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util
import { MediaInput, IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp-engine.interface';
import { Message, MessageDirection, MessageStatus } from './entities/message.entity';
import { HookManager, applySendingGate } from '../../core/hooks';
+import { SendPacingService } from './send-pacing.service';
import { TemplateService } from '../template/template.service';
import { renderTemplate } from '../../common/utils/template-render';
import { createLogger } from '../../common/services/logger.service';
@@ -94,6 +95,9 @@ export class MessageService {
private readonly hookManager: HookManager,
private readonly templateService: TemplateService,
private readonly lidMappingStore: LidMappingStoreService,
+ // Required, not @Optional: a missing pacing service would silently mean "no pacing", which is
+ // the one failure mode this feature must not have. The service itself no-ops when disabled.
+ private readonly pacing: SendPacingService,
@Optional()
private readonly configService?: ConfigService,
// Optional so the existing standalone constructions keep working; absent means the archive
@@ -145,7 +149,13 @@ export class MessageService {
* reply/forward) and edit — passes through the same moderation chokepoint, instead of only
* `sendText`. The implementation is shared with StatusService via core/hooks/sending-gate.
*/
- private applySendingGate<T extends object>(sessionId: string, type: string, input: T): Promise<T> {
+ private async applySendingGate<T extends object>(sessionId: string, type: string, input: T): Promise<T> {
+ // Pacing runs BEFORE the plugin gate, so a send that policy forbids never reaches a plugin at
+ // all — plugins should not be asked to moderate, or given the chance to rewrite, traffic that is
+ // 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);
return applySendingGate(this.hookManager, sessionId, type, input, 'MessageService');
}
@@ -163,6 +173,10 @@ export class MessageService {
input: unknown,
error: unknown,
): Promise<never> {
+ // The engine was asked and refused, so this counts toward the breaker's streak. Validation
+ // errors thrown before the engine is reached never come through here, which is what keeps a
+ // client sending malformed requests from tripping the breaker on a healthy session.
+ this.pacing.recordSendFailure(sessionId);
await this.saveFailedMessage(message);
// Sanitize the hook payload: an SSRF block's raw .message names the resolved internal address
// (a recon/DNS-rebind oracle) — the client-facing throw below already maps it to a generic
@@ -669,6 +683,9 @@ export class MessageService {
// A send whose engine couldn't read the sent message's id back reports an empty id — a forward that
// can't recover the copy, or a WhatsApp Web build that renamed the id field out from under the
// engine. Leave waMessageId unset (NULL) so no ack mis-matches it.
+ // The engine accepted the message, so whatever streak the breaker was tracking is over. Recorded
+ // here rather than at each call site for the same reason failSend is: one funnel, twelve senders.
+ this.pacing.recordSendSuccess(message.sessionId);
if (result.id) message.waMessageId = result.id;
message.status = MessageStatus.SENT;
message.timestamp = result.timestamp;
diff --git a/src/modules/message/send-pacing.config.ts b/src/modules/message/send-pacing.config.ts
new file mode 100644
index 000000000..a10f811f8
--- /dev/null
+++ b/src/modules/message/send-pacing.config.ts
@@ -0,0 +1,84 @@
+import { ConfigService } from '@nestjs/config';
+
+/**
+ * Pacing policy for outbound sends, resolved from the environment.
+ *
+ * Kept out of `feature-flags.ts` because it is a policy object rather than a set of independent
+ * booleans, and because every numeric field needs the clamping below — a bad value here does not
+ * misconfigure a feature, it decides whether messages are refused.
+ */
+export interface SendPacingConfig {
+ /** Opt-in — default OFF, so an upgrade never starts refusing sends on its own. */
+ enabled: boolean;
+ /**
+ * Daily send allowance by session age in days: index 0 is the session's first day, and the last
+ * entry applies to every day beyond the schedule's length. A brand-new WhatsApp account that
+ * immediately sends at volume is the classic ban pattern, so the allowance starts small and grows.
+ */
+ warmupSchedule: number[];
+ /** Consecutive send failures that trip the breaker. */
+ breakerThreshold: number;
+ /** How long the breaker stays open before it lets traffic through again. */
+ breakerCooldownMs: number;
+}
+
+/** 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];
+const DEFAULT_BREAKER_THRESHOLD = 5;
+const DEFAULT_BREAKER_COOLDOWN_MS = 15 * 60_000;
+
+// A cap of 0 would refuse every send, which is never what a misconfigured value should mean, so the
+// floor is 1. The ceiling is a sanity bound, not a WhatsApp limit — nobody's real allowance is 100k,
+// and a fat-fingered value that large would silently disable the whole mechanism.
+const MIN_DAILY_CAP = 1;
+const MAX_DAILY_CAP = 100_000;
+const MIN_BREAKER_THRESHOLD = 1;
+const MIN_BREAKER_COOLDOWN_MS = 1000;
+
+/**
+ * Parse a comma-separated warm-up schedule (`"20,40,80"`). Any malformed entry falls the WHOLE
+ * schedule back to the default rather than being skipped: a schedule with a hole in it would apply a
+ * 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;
+ 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 parts.map(n => Math.floor(n));
+}
+
+function parsePositiveInt(raw: string | undefined, fallback: number, min: number): number {
+ const value = Number(raw);
+ if (!Number.isFinite(value) || value < min) return fallback;
+ return Math.floor(value);
+}
+
+/** Derive the policy from an environment map. Pure and parameterised for testability. */
+export function computeSendPacingConfig(env: NodeJS.ProcessEnv = process.env): SendPacingConfig {
+ return {
+ enabled: env.SEND_PACING_ENABLED === 'true',
+ warmupSchedule: parseSchedule(env.SEND_PACING_WARMUP_SCHEDULE),
+ breakerThreshold: parsePositiveInt(
+ env.SEND_PACING_BREAKER_THRESHOLD,
+ DEFAULT_BREAKER_THRESHOLD,
+ MIN_BREAKER_THRESHOLD,
+ ),
+ breakerCooldownMs: parsePositiveInt(
+ env.SEND_PACING_BREAKER_COOLDOWN_MS,
+ DEFAULT_BREAKER_COOLDOWN_MS,
+ MIN_BREAKER_COOLDOWN_MS,
+ ),
+ };
+}
+
+/**
+ * Resolve the policy, preferring the ConfigService snapshot and falling back to a live `process.env`
+ * read when ConfigService is absent — the same arrangement `resolveFeatureFlags` uses, and for the
+ * same reason: unit tests construct services without the global ConfigModule and mutate `process.env`.
+ */
+export function resolveSendPacingConfig(configService?: Pick<ConfigService, 'get'>): SendPacingConfig {
+ return configService?.get<SendPacingConfig>('sendPacing') ?? computeSendPacingConfig();
+}
diff --git a/src/modules/message/send-pacing.service.spec.ts b/src/modules/message/send-pacing.service.spec.ts
new file mode 100644
index 000000000..f5c966d77
--- /dev/null
+++ b/src/modules/message/send-pacing.service.spec.ts
@@ -0,0 +1,367 @@
+import { HttpException } from '@nestjs/common';
+import { SendPacingService, SEND_PACING_LIMITED } from './send-pacing.service';
+import { computeSendPacingConfig, type SendPacingConfig } from './send-pacing.config';
+import { getSendPacingRefusals, resetSendPacingRefusals } from '../../common/metrics/send-pacing-metrics';
+import { MessageDirection, type Message } from './entities/message.entity';
+import type { Session } from '../session/entities/session.entity';
+import type { Repository } from 'typeorm';
+import type { ConfigService } from '@nestjs/config';
+import { MessageService } from './message.service';
+import { BulkMessageService } from './bulk-message.service';
+import { StatusService } from '../status/status.service';
+import { CatalogService } from '../catalog/catalog.service';
+
+const DAY_MS = 86_400_000;
+
+/** A session that first existed `ageDays` whole UTC days ago. */
+const sessionAged = (ageDays: number): Session =>
+ ({ id: 's1', createdAt: new Date(Date.now() - ageDays * DAY_MS) }) as Session;
+
+interface Harness {
+ service: SendPacingService;
+ count: jest.Mock;
+ findOne: jest.Mock;
+}
+
+const build = (
+ config: Partial<SendPacingConfig> = {},
+ sentToday = 0,
+ session: Session | null = sessionAged(0),
+): Harness => {
+ const count = jest.fn().mockResolvedValue(sentToday);
+ const findOne = jest.fn().mockResolvedValue(session);
+ const configService = {
+ get: (key: string) =>
+ key === 'sendPacing' ? { ...computeSendPacingConfig({}), enabled: true, ...config } : undefined,
+ } as unknown as ConfigService;
+ const service = new SendPacingService(
+ { count } as unknown as Repository<Message>,
+ { findOne } as unknown as Repository<Session>,
+ configService,
+ );
+ return { service, count, findOne };
+};
+
+/** Assert the throw is the pacing 429 and hand back its body for further checks. */
+const expectPacingRefusal = async (promise: Promise<unknown>): Promise<Record<string, unknown>> => {
+ await expect(promise).rejects.toBeInstanceOf(HttpException);
+ const error = await promise.then(
+ () => null,
+ (e: HttpException) => e,
+ );
+ expect(error?.getStatus()).toBe(429);
+ return error?.getResponse() as Record<string, unknown>;
+};
+
+describe('SendPacingService', () => {
+ beforeEach(() => resetSendPacingRefusals());
+
+ describe('when disabled', () => {
+ // The disabled path must cost nothing and change nothing — a deployment that has not opted in
+ // has to behave exactly as it did before this feature existed, including doing no DB work.
+ it('allows the send without touching the database', async () => {
+ const { service, count, findOne } = build({ enabled: false }, 999_999);
+
+ await expect(service.assertSendAllowed('s1')).resolves.toBeUndefined();
+
+ expect(count).not.toHaveBeenCalled();
+ expect(findOne).not.toHaveBeenCalled();
+ });
+
+ it('ignores failures, so enabling it later does not start with a pre-tripped breaker', async () => {
+ const { service } = build({ enabled: false });
+ for (let i = 0; i < 50; i++) service.recordSendFailure('s1');
+
+ const enabled = build({ breakerThreshold: 1 });
+ await expect(enabled.service.assertSendAllowed('s1')).resolves.toBeUndefined();
+ });
+ });
+
+ describe('the warm-up daily cap', () => {
+ it('allows a send while the session is under its allowance', async () => {
+ const { service } = build({ warmupSchedule: [10] }, 9);
+
+ await expect(service.assertSendAllowed('s1')).resolves.toBeUndefined();
+ });
+
+ // The boundary is the whole point of a cap: at exactly the allowance the budget is spent.
+ it('refuses the send that would exceed the allowance', async () => {
+ const { service } = build({ warmupSchedule: [10] }, 10);
+
+ const body = await expectPacingRefusal(service.assertSendAllowed('s1'));
+
+ expect(body.code).toBe(SEND_PACING_LIMITED);
+ expect(body.message).toContain('10');
+ });
+
+ // The ramp is the anti-ban mechanism: a day-old account must not get a mature account's budget.
+ it('grows the allowance with the session age', async () => {
+ const young = build({ warmupSchedule: [10, 100] }, 20, sessionAged(0));
+ await expectPacingRefusal(young.service.assertSendAllowed('s1'));
+
+ const older = build({ warmupSchedule: [10, 100] }, 20, sessionAged(1));
+ await expect(older.service.assertSendAllowed('s1')).resolves.toBeUndefined();
+ });
+
+ // Beyond the schedule the last rung applies forever, rather than falling off the end into
+ // undefined (which would compare as NaN and let everything through).
+ it('saturates at the final rung for a session older than the schedule', async () => {
+ const { service } = build({ warmupSchedule: [10, 100] }, 99, sessionAged(365));
+
+ await expect(service.assertSendAllowed('s1')).resolves.toBeUndefined();
+ });
+
+ it("counts only this session's outgoing messages since the start of the UTC day", async () => {
+ const { service, count } = build({ warmupSchedule: [10] }, 0);
+
+ await service.assertSendAllowed('s1');
+
+ const [[options]] = count.mock.calls as [[{ where: Record<string, unknown> }]];
+ const where = options.where;
+ expect(where.sessionId).toBe('s1');
+ expect(where.direction).toBe(MessageDirection.OUTGOING);
+ expect(where.createdAt).toBeDefined();
+ });
+
+ // A send for a session with no row is about to fail for a better reason than pacing; the
+ // governor must not be the thing that reports it.
+ it('stays out of the way when the session row is missing', async () => {
+ const { service, count } = build({ warmupSchedule: [1] }, 99, null);
+
+ await expect(service.assertSendAllowed('s1')).resolves.toBeUndefined();
+ expect(count).not.toHaveBeenCalled();
+ });
+
+ it('tells the caller how long the refusal lasts', async () => {
+ const { service } = build({ warmupSchedule: [1] }, 5);
+
+ const body = await expectPacingRefusal(service.assertSendAllowed('s1'));
+
+ // Until the next UTC midnight — never zero, or a client would retry immediately in a loop.
+ expect(body.retryAfterSeconds).toBeGreaterThan(0);
+ expect(body.retryAfterSeconds).toBeLessThanOrEqual(86_400);
+ });
+ });
+
+ describe('the failure-streak breaker', () => {
+ it('stays closed below the threshold', async () => {
+ const { service } = build({ breakerThreshold: 3, warmupSchedule: [1000] });
+ service.recordSendFailure('s1');
+ service.recordSendFailure('s1');
+
+ await expect(service.assertSendAllowed('s1')).resolves.toBeUndefined();
+ });
+
+ it('opens on the threshold failure and refuses further sends', async () => {
+ const { service } = build({ breakerThreshold: 3, warmupSchedule: [1000] });
+ service.recordSendFailure('s1');
+ service.recordSendFailure('s1');
+ service.recordSendFailure('s1');
+
+ const body = await expectPacingRefusal(service.assertSendAllowed('s1'));
+ expect(body.code).toBe(SEND_PACING_LIMITED);
+ });
+
+ // A success proves WhatsApp is still serving this account, so a streak that never completed
+ // must not accumulate across unrelated failures hours apart.
+ it('a success resets the streak', async () => {
+ const { service } = build({ breakerThreshold: 3, warmupSchedule: [1000] });
+ service.recordSendFailure('s1');
+ service.recordSendFailure('s1');
+ service.recordSendSuccess('s1');
+ service.recordSendFailure('s1');
+
+ await expect(service.assertSendAllowed('s1')).resolves.toBeUndefined();
+ });
+
+ it('closes again once the cooldown has elapsed', async () => {
+ jest.useFakeTimers();
+ try {
+ const { service } = build({ breakerThreshold: 1, breakerCooldownMs: 60_000, warmupSchedule: [1000] });
+ service.recordSendFailure('s1');
+ await expectPacingRefusal(service.assertSendAllowed('s1'));
+
+ jest.advanceTimersByTime(60_001);
+
+ await expect(service.assertSendAllowed('s1')).resolves.toBeUndefined();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ // One session's trouble must not stop another's traffic — they are different WhatsApp accounts.
+ it('is per session', async () => {
+ const { service } = build({ breakerThreshold: 1, warmupSchedule: [1000] });
+ service.recordSendFailure('s1');
+
+ await expectPacingRefusal(service.assertSendAllowed('s1'));
+ await expect(service.assertSendAllowed('s2')).resolves.toBeUndefined();
+ });
+
+ // The breaker is checked before the cap so an account WhatsApp is already refusing does not pay
+ // for a DB count on every attempt.
+ it('refuses without querying the daily count', async () => {
+ const { service, count } = build({ breakerThreshold: 1, warmupSchedule: [1000] });
+ service.recordSendFailure('s1');
+
+ await expectPacingRefusal(service.assertSendAllowed('s1'));
+
+ expect(count).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('metrics', () => {
+ it('counts refusals by the rule that caused them', async () => {
+ const capped = build({ warmupSchedule: [1] }, 5);
+ await expectPacingRefusal(capped.service.assertSendAllowed('s1'));
+
+ const tripped = build({ breakerThreshold: 1, warmupSchedule: [1000] });
+ tripped.service.recordSendFailure('s1');
+ await expectPacingRefusal(tripped.service.assertSendAllowed('s1'));
+
+ expect(getSendPacingRefusals().get('daily_cap')).toBe(1);
+ expect(getSendPacingRefusals().get('breaker_open')).toBe(1);
+ });
+
+ it('records nothing when sends are allowed', async () => {
+ const { service } = build({ warmupSchedule: [10] }, 0);
+ await service.assertSendAllowed('s1');
+
+ expect(getSendPacingRefusals().size).toBe(0);
+ });
+ });
+});
+
+describe('computeSendPacingConfig', () => {
+ it('is off unless explicitly enabled', () => {
+ expect(computeSendPacingConfig({}).enabled).toBe(false);
+ expect(computeSendPacingConfig({ SEND_PACING_ENABLED: 'TRUE' }).enabled).toBe(false);
+ expect(computeSendPacingConfig({ SEND_PACING_ENABLED: 'true' }).enabled).toBe(true);
+ });
+
+ it('parses a warm-up schedule', () => {
+ expect(computeSendPacingConfig({ SEND_PACING_WARMUP_SCHEDULE: '5, 10,20' }).warmupSchedule).toEqual([5, 10, 20]);
+ });
+
+ // A schedule with one bad entry falls back WHOLESALE rather than skipping the entry: a ramp with a
+ // hole in it would apply a different policy than the operator wrote, and quietly sending more than
+ // intended is the one outcome this feature exists to prevent.
+ it.each(['5,abc,20', '5,0,20', '', ' ', '5,-1'])('falls back to the default schedule for %p', raw => {
+ const parsed = computeSendPacingConfig({ SEND_PACING_WARMUP_SCHEDULE: raw }).warmupSchedule;
+ expect(parsed).toEqual(computeSendPacingConfig({}).warmupSchedule);
+ });
+
+ it.each([
+ ['SEND_PACING_BREAKER_THRESHOLD', 'breakerThreshold'],
+ ['SEND_PACING_BREAKER_COOLDOWN_MS', 'breakerCooldownMs'],
+ ])('falls back on a nonsensical %s', (envKey, field) => {
+ const withGarbage = computeSendPacingConfig({ [envKey]: 'nonsense' });
+ const withZero = computeSendPacingConfig({ [envKey]: '0' });
+ const defaults = computeSendPacingConfig({});
+ expect(withGarbage[field as 'breakerThreshold']).toBe(defaults[field as 'breakerThreshold']);
+ expect(withZero[field as 'breakerThreshold']).toBe(defaults[field as 'breakerThreshold']);
+ });
+});
+
+// The governor is only as good as the number of send paths that consult it. These pin the
+// wiring itself rather than the policy: each is a path that reaches WhatsApp, and a refactor that
+// stops calling the governor from any of them reopens a hole silently.
+describe('send paths consult the governor', () => {
+ const refusing = (): { assertSendAllowed: jest.Mock } => ({
+ assertSendAllowed: jest.fn().mockRejectedValue(new HttpException({ code: SEND_PACING_LIMITED }, 429)),
+ });
+
+ it('MessageService refuses before the plugin gate runs and before the engine is asked', async () => {
+ const hookManager = { execute: jest.fn() };
+ const engine = { sendTextMessage: jest.fn() };
+ const pacing = refusing();
+ const service = new MessageService(
+ { save: jest.fn() } as never,
+ { isActive: () => true } as never,
+ { get: () => engine, require: () => engine } as never,
+ {} as never,
+ hookManager as never,
+ {} as never,
+ {} as never,
+ pacing as never,
+ );
+
+ await expect(service.sendText('s1', { chatId: '[email protected]', text: 'hi' })).rejects.toBeInstanceOf(HttpException);
+
+ expect(pacing.assertSendAllowed).toHaveBeenCalledWith('s1');
+ // 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();
+ expect(engine.sendTextMessage).not.toHaveBeenCalled();
+ });
+
+ it('StatusService refuses before the plugin gate runs and before the engine is asked', async () => {
+ const hookManager = { execute: jest.fn() };
+ const engine = { postTextStatus: jest.fn() };
+ const pacing = refusing();
+ const service = new StatusService(
+ { require: () => engine } as never,
+ hookManager as never,
+ {} as never,
+ {} as never,
+ pacing as never,
+ );
+
+ await expect(service.postTextStatus('s1', 'hi', {})).rejects.toBeInstanceOf(HttpException);
+
+ expect(pacing.assertSendAllowed).toHaveBeenCalledWith('s1');
+ expect(hookManager.execute).not.toHaveBeenCalled();
+ expect(engine.postTextStatus).not.toHaveBeenCalled();
+ });
+
+ // This path does NOT go through MessageService, which is exactly why it needs its own call —
+ // sending a product is a real outbound chat message, not a catalog read.
+ it('CatalogService.sendProduct refuses before the engine is asked', async () => {
+ const engine = { sendProduct: jest.fn(), sendCatalog: jest.fn() };
+ const pacing = refusing();
+ const service = new CatalogService({ require: () => engine } as never, pacing as never);
+
+ await expect(service.sendProduct('s1', '[email protected]', 'p1')).rejects.toBeInstanceOf(HttpException);
+ await expect(service.sendCatalog('s1', '[email protected]')).rejects.toBeInstanceOf(HttpException);
+
+ expect(pacing.assertSendAllowed).toHaveBeenCalledTimes(2);
+ expect(engine.sendProduct).not.toHaveBeenCalled();
+ expect(engine.sendCatalog).not.toHaveBeenCalled();
+ });
+
+ // Bulk keeps its own inlined copy of the moderation gate, so it is the classic place for the two
+ // to drift apart. A refusal fails just the item, leaving the batch to carry on.
+ it('BulkMessageService consults the governor per item, before its own gate copy', async () => {
+ const hookManager = { execute: jest.fn() };
+ const engine = { sendTextMessage: jest.fn() };
+ const pacing = refusing();
+ const batch = {
+ id: 'b1',
+ batchId: 'bx',
+ sessionId: 's1',
+ status: 'pending',
+ currentIndex: 0,
+ messages: [{ chatId: '[email protected]', type: 'text', content: { text: 'hi' } }],
+ options: { delayBetweenMessages: 0, randomizeDelay: false, stopOnError: false },
+ progress: { total: 1, sent: 0, failed: 0, pending: 1, cancelled: 0 },
+ results: [],
+ };
+ const service = new BulkMessageService(
+ {
+ findOne: jest.fn().mockResolvedValue(batch),
+ save: jest.fn((b: unknown) => Promise.resolve(b)),
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
+ } as never,
+ { get: () => engine } as never,
+ { saveOutgoingMessage: jest.fn() } as never,
+ hookManager as never,
+ pacing as never,
+ );
+
+ await (service as unknown as { processBatch: (id: string) => Promise<void> }).processBatch('b1');
+
+ expect(pacing.assertSendAllowed).toHaveBeenCalledWith('s1');
+ expect(hookManager.execute).not.toHaveBeenCalledWith('message:sending', expect.anything(), expect.anything());
+ expect(engine.sendTextMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.ts
new file mode 100644
index 000000000..500678197
--- /dev/null
+++ b/src/modules/message/send-pacing.service.ts
@@ -0,0 +1,204 @@
+import { HttpException, HttpStatus, Injectable, Optional } from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
+import { InjectRepository } from '@nestjs/typeorm';
+import { MoreThanOrEqual, Repository } from 'typeorm';
+import { Message, MessageDirection } from './entities/message.entity';
+import { Session } from '../session/entities/session.entity';
+import { resolveSendPacingConfig, type SendPacingConfig } from './send-pacing.config';
+import { incrementSendPacingRefusals, type SendPacingRefusalReason } from '../../common/metrics/send-pacing-metrics';
+import { createLogger } from '../../common/services/logger.service';
+
+/** Body code on a pacing refusal. The throttler's own 429 carries no `code`, which is what tells the two apart. */
+export const SEND_PACING_LIMITED = 'SEND_PACING_LIMITED';
+
+/** Per-session breaker state. Deliberately in memory — see the class doc. */
+interface BreakerState {
+ consecutiveFailures: number;
+ /** Epoch ms the breaker opened, or null while it is closed. */
+ openedAt: number | null;
+}
+
+/**
+ * Refuses outbound sends that a young or misbehaving session should not be making.
+ *
+ * Two rules, both aimed at the way WhatsApp actually bans automated accounts:
+ *
+ * - a **warm-up daily cap**, because a new account that immediately sends at volume is the pattern
+ * that gets numbers banned. The allowance grows with the session's age.
+ * - a **failure-streak breaker**, because a run of consecutive send failures usually means WhatsApp
+ * has already started refusing this account, and continuing to push makes its standing worse.
+ *
+ * It is plain code called from the send paths, NOT a `message:sending` hook subscriber. That is
+ * load-bearing: `runGuarded` (plugin-capability-context.ts) suppresses `message:sending` when a
+ * plugin sends from inside its own handler, so a hook-based governor would be silently bypassed on
+ * exactly the automated traffic it exists to pace.
+ *
+ * The daily count is read from the `messages` table rather than a counter of its own. That table is
+ * already the durable record of every send — bulk included, which persists through the same
+ * `saveOutgoingMessage` — and it already carries the `(sessionId, createdAt)` index the count needs.
+ * So the cap survives restarts with no table, no migration, and no way to drift from what was really
+ * sent. The breaker, by contrast, is in memory on purpose: it describes live conditions, and a
+ * restart clearing it is the correct behaviour.
+ */
+@Injectable()
+export class SendPacingService {
+ private readonly logger = createLogger('SendPacingService');
+ private readonly breakers = new Map<string, BreakerState>();
+
+ constructor(
+ @InjectRepository(Message, 'data')
+ private readonly messageRepository: Repository<Message>,
+ @InjectRepository(Session, 'data')
+ private readonly sessionRepository: Repository<Session>,
+ @Optional()
+ private readonly configService?: ConfigService,
+ ) {}
+
+ /**
+ * Throw unless this session may send right now. Called at the top of every outbound send path.
+ *
+ * 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> {
+ const config = resolveSendPacingConfig(this.configService);
+ if (!config.enabled) return;
+
+ this.assertBreakerClosed(sessionId, config);
+ await this.assertUnderDailyCap(sessionId, config);
+ }
+
+ /**
+ * Record a send that failed. A run of these trips the breaker.
+ *
+ * Only called on failures that reached WhatsApp and came back refused — a validation error thrown
+ * before the engine is asked says nothing about the account's standing and must not count, or a
+ * client sending malformed requests could trip the breaker on a perfectly healthy session.
+ */
+ recordSendFailure(sessionId: string): void {
+ const config = resolveSendPacingConfig(this.configService);
+ if (!config.enabled) return;
+
+ const breaker = this.breakerFor(sessionId);
+ breaker.consecutiveFailures += 1;
+ if (breaker.openedAt === null && breaker.consecutiveFailures >= config.breakerThreshold) {
+ breaker.openedAt = Date.now();
+ this.logger.warn(`Send breaker tripped after ${breaker.consecutiveFailures} consecutive failures`, {
+ sessionId,
+ consecutiveFailures: breaker.consecutiveFailures,
+ cooldownMs: config.breakerCooldownMs,
+ action: 'send_breaker_tripped',
+ });
+ }
+ }
+
+ /** Record a send that succeeded, which ends any streak in progress. */
+ recordSendSuccess(sessionId: string): void {
+ const config = resolveSendPacingConfig(this.configService);
+ if (!config.enabled) return;
+
+ const breaker = this.breakers.get(sessionId);
+ if (!breaker) return;
+ // A success proves the account is being served, so the streak resets AND an open breaker closes.
+ // Nothing else closes it early: the cooldown is what normally lets traffic back through.
+ this.breakers.delete(sessionId);
+ }
+
+ /** 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 breakerFor(sessionId: string): BreakerState {
+ const existing = this.breakers.get(sessionId);
+ if (existing) return existing;
+ const created: BreakerState = { consecutiveFailures: 0, openedAt: null };
+ this.breakers.set(sessionId, created);
+ return created;
+ }
+
+ private assertBreakerClosed(sessionId: string, config: SendPacingConfig): void {
+ const breaker = this.breakers.get(sessionId);
+ if (!breaker?.openedAt) return;
+
+ const elapsed = Date.now() - breaker.openedAt;
+ if (elapsed >= config.breakerCooldownMs) {
+ // Cooldown served. Dropping the entry rather than zeroing it is what keeps the map bounded by
+ // the number of sessions currently in trouble instead of every session that ever failed — and
+ // it is equivalent, since the next failure recreates it at a count of one either way.
+ this.breakers.delete(sessionId);
+ return;
+ }
+ this.refuse('breaker_open', sessionId, Math.ceil((config.breakerCooldownMs - elapsed) / 1000), {
+ reason: 'Sends are paused after a run of consecutive send failures',
+ });
+ }
+
+ private async assertUnderDailyCap(sessionId: string, config: SendPacingConfig): Promise<void> {
+ const session = await this.sessionRepository.findOne({ where: { id: sessionId } });
+ // No row means the send is about to fail on its own for a better reason than pacing; let it.
+ if (!session) return;
+
+ const dayStart = startOfUtcDay(new Date());
+ // 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 sentToday = await this.messageRepository.count({
+ where: { sessionId, direction: MessageDirection.OUTGOING, createdAt: MoreThanOrEqual(dayStart) },
+ });
+ if (sentToday < allowance) return;
+
+ this.refuse('daily_cap', sessionId, secondsUntilNextUtcDay(), {
+ reason: `Daily send allowance of ${allowance} reached for a session ${ageDays} day(s) old`,
+ allowance,
+ sentToday,
+ });
+ }
+
+ private refuse(
+ reason: SendPacingRefusalReason,
+ sessionId: string,
+ retryAfterSeconds: number,
+ detail: { reason: string } & Record<string, unknown>,
+ ): never {
+ incrementSendPacingRefusals(reason);
+ this.logger.warn(`Send refused by the pacing governor: ${detail.reason}`, {
+ ...detail,
+ sessionId,
+ rule: reason,
+ retryAfterSeconds,
+ action: 'send_paced',
+ });
+ // 429 with a body `code`, which is what distinguishes this from the global throttler's own 429 —
+ // a client that retries blindly on 429 would otherwise treat a day-long cap like a one-second
+ // rate limit. `retryAfterSeconds` says how long the refusal actually lasts.
+ throw new HttpException(
+ {
+ statusCode: HttpStatus.TOO_MANY_REQUESTS,
+ error: 'Too Many Requests',
+ message: detail.reason,
+ code: SEND_PACING_LIMITED,
+ retryAfterSeconds,
+ },
+ HttpStatus.TOO_MANY_REQUESTS,
+ );
+ }
+}
+
+const DAY_MS = 86_400_000;
+
+/**
+ * The cap's day boundary is UTC, not the server's local midnight: a deployment that moves timezone,
+ * or replicas in different ones, must not disagree about when the allowance resets.
+ */
+function startOfUtcDay(at: Date): Date {
+ return new Date(Date.UTC(at.getUTCFullYear(), at.getUTCMonth(), at.getUTCDate()));
+}
+
+function secondsUntilNextUtcDay(): number {
+ const now = Date.now();
+ return Math.max(1, Math.ceil((startOfUtcDay(new Date(now)).getTime() + DAY_MS - now) / 1000));
+}
diff --git a/src/modules/metrics/metrics.service.ts b/src/modules/metrics/metrics.service.ts
index 00f1aca24..2bd6ea687 100644
--- a/src/modules/metrics/metrics.service.ts
+++ b/src/modules/metrics/metrics.service.ts
@@ -8,6 +8,7 @@ import {
getSessionReconnectLoopAlertsTotal,
} from '../../common/metrics/session-reconnect-metrics';
import { getRestrictedSessionCount } from '../../common/metrics/session-restriction-metrics';
+import { getSendPacingRefusals } from '../../common/metrics/send-pacing-metrics';
import { renderHttpRequestMetrics } from '../../common/metrics/request-metrics';
/**
@@ -122,6 +123,17 @@ export class MetricsService {
lines.push('# TYPE openwa_sessions_restricted gauge');
lines.push(`openwa_sessions_restricted ${getRestrictedSessionCount()}`);
+ // Emitted only once a refusal has actually happened, like the HTTP series: a family that appears
+ // at its first occurrence is easier to alert on than one pinned at zero for every reason.
+ const refusals = getSendPacingRefusals();
+ if (refusals.size > 0) {
+ lines.push('# HELP openwa_send_pacing_refusals_total Sends refused by the pacing governor since process start.');
+ lines.push('# TYPE openwa_send_pacing_refusals_total counter');
+ for (const [reason, count] of refusals) {
+ lines.push(`openwa_send_pacing_refusals_total{reason="${this.escapeLabel(reason)}"} ${count}`);
+ }
+ }
+
// HTTP RED metrics (request rate + duration per route), recorded by RequestMetricsInterceptor.
// Included in the same cached render — a few seconds of staleness is fine for Prometheus.
lines.push(...renderHttpRequestMetrics());
diff --git a/src/modules/status/status.module.ts b/src/modules/status/status.module.ts
index 258ec8040..b1c45232c 100644
--- a/src/modules/status/status.module.ts
+++ b/src/modules/status/status.module.ts
@@ -1,10 +1,11 @@
import { Module } from '@nestjs/common';
+import { MessageModule } from '../message/message.module';
import { StatusController } from './status.controller';
import { StatusService } from './status.service';
import { StatusStoreModule } from '../status-store/status-store.module';
@Module({
- imports: [StatusStoreModule],
+ imports: [MessageModule, StatusStoreModule],
controllers: [StatusController],
providers: [StatusService],
exports: [StatusService],
diff --git a/src/modules/status/status.service.spec.ts b/src/modules/status/status.service.spec.ts
index 4f9f03f06..3cf999197 100644
--- a/src/modules/status/status.service.spec.ts
+++ b/src/modules/status/status.service.spec.ts
@@ -8,6 +8,7 @@ import { HookManager } from '../../core/hooks';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { SendImageStatusDto, SendVideoStatusDto } from './dto/send-media-status.dto';
+import { SendPacingService } from '../message/send-pacing.service';
describe('StatusService media validation and selection', () => {
const engine = {
@@ -32,6 +33,9 @@ describe('StatusService media validation and selection', () => {
hookManager as unknown as HookManager,
store as unknown as StatusStoreService,
storageService as unknown as StorageService,
+ {
+ assertSendAllowed: jest.fn().mockResolvedValue(undefined),
+ } as unknown as SendPacingService,
);
beforeEach(() => {
diff --git a/src/modules/status/status.service.ts b/src/modules/status/status.service.ts
index e5cec1b46..005470ef1 100644
--- a/src/modules/status/status.service.ts
+++ b/src/modules/status/status.service.ts
@@ -5,6 +5,7 @@ import { StorageService } from '../../common/storage/storage.service';
import type { Status, StatusResult, StatusPostOptions } from '../../engine/interfaces/whatsapp-engine.interface';
import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';
import { HookManager, applySendingGate } from '../../core/hooks';
+import { SendPacingService } from '../message/send-pacing.service';
/** Stored status media is only ever an image or video; a sender-declared mimetype outside that is
* served as inert octet-stream so the media endpoint can't be turned into active content (HTML/JS)
@@ -20,6 +21,7 @@ export class StatusService {
private readonly hookManager: HookManager,
private readonly store: StatusStoreService,
private readonly storageService: StorageService,
+ private readonly pacing: SendPacingService,
) {}
/**
@@ -30,7 +32,11 @@ export class StatusService {
* Note for plugin authors: `input` here is NOT a send DTO — it carries no `chatId`. Text posts
* receive `{ text, options }` and media posts `{ media: { mimetype, data }, options }`.
*/
- private gate<T extends object>(sessionId: string, type: string, input: T): Promise<T> {
+ private async gate<T extends object>(sessionId: string, type: string, input: T): Promise<T> {
+ // Pacing first, for the same reason as the chat path: a post the policy forbids is never offered
+ // to plugins. A status post is published to the account's contacts, so it counts as outbound
+ // traffic even though it addresses no single chat.
+ await this.pacing.assertSendAllowed(sessionId);
return applySendingGate(this.hookManager, sessionId, type, input, 'StatusService');
}