Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(webhook): bound per-event fan-out (WEBHOOK_DISPATCH_CONCURRENCY) (#721)

Yudhi Armyndhariscf048e0c5dd9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 106fa3844..39dba60fe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -105,6 +105,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`getChannelMessages` remains unsupported — `newsletterFetchMessages` returns a raw BinaryNode with
no library parser, so it stays a documented gap rather than an unverified walk.
+- **Bounded webhook fan-out.** An event matching N webhooks now delivers at most
+ `WEBHOOK_DISPATCH_CONCURRENCY` (default 16) concurrently instead of opening N outbound sockets at
+ once; the rest queue and run as slots free. Per-webhook isolation (`Promise.allSettled`) is
+ unchanged. The shared `ConcurrencyLimiter` was also promoted from `engine/adapters` to
+ `common/utils` (it has no engine-specific logic), so the webhook module no longer imports across the
+ engine boundary.
+
### Fixed
- **Diagnosable failure for a stale browser profile after a binary-changing upgrade.** Upgrading
diff --git a/src/engine/adapters/concurrency-limiter.spec.ts b/src/common/utils/concurrency-limiter.spec.ts
similarity index 100%
rename from src/engine/adapters/concurrency-limiter.spec.ts
rename to src/common/utils/concurrency-limiter.spec.ts
diff --git a/src/engine/adapters/concurrency-limiter.ts b/src/common/utils/concurrency-limiter.ts
similarity index 100%
rename from src/engine/adapters/concurrency-limiter.ts
rename to src/common/utils/concurrency-limiter.ts
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index c8ebfd6b8..8292d477f 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -133,6 +133,9 @@ export default () => ({
timeout: parseInt(process.env.WEBHOOK_TIMEOUT || '10000', 10),
maxRetries: parseInt(process.env.WEBHOOK_MAX_RETRIES || '3', 10),
retryDelay: parseInt(process.env.WEBHOOK_RETRY_DELAY || '5000', 10),
+ // Cap on how many matching webhooks are delivered CONCURRENTLY for one event. Without it, an event
+ // matching N webhooks opens N outbound sockets at once (no per-event bound). Default 16.
+ dispatchConcurrency: parseInt(process.env.WEBHOOK_DISPATCH_CONCURRENCY || '16', 10),
},
// API configuration
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index 8025350e6..2cab759af 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -151,6 +151,7 @@ export function validateEnv(config: EnvConfig): EnvConfig {
'REQUEST_TIMEOUT_MS',
'HEADERS_TIMEOUT_MS',
'KEEPALIVE_TIMEOUT_MS',
+ 'WEBHOOK_DISPATCH_CONCURRENCY',
]) {
checkPositiveInt(key);
}
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 28d0ed426..6991c6853 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -53,7 +53,7 @@ import {
isMediaDownloadEnabled,
withInboundDownloadTimeout,
} from './inbound-media-cap';
-import { ConcurrencyLimiter } from './concurrency-limiter';
+import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
/** Linked-device identity shown in WhatsApp (Settings → Linked Devices). */
const BAILEYS_BROWSER: [string, string, string] = ['OpenWA', 'Chrome', '120.0.0'];
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 77136fc5d..358e42a24 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -64,7 +64,7 @@ import {
isMediaDownloadEnabled,
withInboundDownloadTimeout,
} from './inbound-media-cap';
-import { ConcurrencyLimiter } from './concurrency-limiter';
+import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
/**
* Map a whatsapp-web.js MessageAck integer to the neutral DeliveryStatus.
diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.ts
index 51ee1a1f2..ba0faf937 100644
--- a/src/modules/webhook/webhook.service.spec.ts
+++ b/src/modules/webhook/webhook.service.spec.ts
@@ -78,6 +78,8 @@ describe('WebhookService', () => {
if (key === 'webhook.retryDelay') return 100;
// Distinct from the hardcoded 10000 fallback so a regression to a literal timeout is caught.
if (key === 'webhook.timeout') return 25000;
+ // A small, non-default cap so the fan-out-bound test (5 webhooks) can assert the limiter holds.
+ if (key === 'webhook.dispatchConcurrency') return 2;
return def as T;
}),
};
@@ -384,6 +386,49 @@ describe('WebhookService', () => {
await dispatchP;
});
+ it('bounds concurrent delivery to WEBHOOK_DISPATCH_CONCURRENCY (cap=2, 5 webhooks → peak ≤ 2)', async () => {
+ const hooks = Array.from({ length: 5 }, (_, i) =>
+ createMockWebhook({ id: `wh-${i}`, url: `https://h${i}.example/hook`, events: ['message.received'] }),
+ );
+ (repository.find as jest.Mock).mockResolvedValue(hooks);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+
+ let inFlight = 0;
+ let peak = 0;
+ let resolved = 0;
+ const releasers: Array<() => void> = [];
+ mockFetch.mockImplementation(
+ () =>
+ new Promise(resolve => {
+ inFlight += 1;
+ peak = Math.max(peak, inFlight);
+ releasers.push(() => {
+ inFlight -= 1;
+ resolved += 1;
+ resolve({ ok: true, status: 200 });
+ });
+ }),
+ );
+
+ const dispatchP = service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
+ // Let the limiter admit up to the cap (2) and each reach fetch. The other 3 stay parked.
+ for (let i = 0; i < 20 && releasers.length < 2; i++) {
+ await new Promise(r => setImmediate(r));
+ }
+ expect(inFlight).toBeLessThanOrEqual(2);
+ // Release in a macrotask loop: freeing a slot lets the limiter admit the next webhook, whose fetch
+ // pushes a fresh releaser on the NEXT tick — a single synchronous drain would miss it and hang.
+ for (let i = 0; i < 50 && resolved < 5; i++) {
+ while (releasers.length) (releasers.shift() as () => void)();
+ await new Promise(r => setImmediate(r));
+ }
+ await dispatchP;
+ // Peak across the whole run never exceeded the cap. (An unbounded fan-out would reach 5.)
+ expect(peak).toBeLessThanOrEqual(2);
+ expect(mockFetch).toHaveBeenCalledTimes(5);
+ });
+
it('salts each sibling webhook with a distinct idempotency key so one receiver cannot dedupe out another', async () => {
const wA = createMockWebhook({ id: 'wh-a', url: 'https://a.example/hook', events: ['message.received'] });
const wB = createMockWebhook({ id: 'wh-b', url: 'https://b.example/hook', events: ['message.received'] });
diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.ts
index 4b6dfd15a..d0835d034 100644
--- a/src/modules/webhook/webhook.service.ts
+++ b/src/modules/webhook/webhook.service.ts
@@ -33,6 +33,7 @@ import {
redactSsrfError,
} from '../../common/security/ssrf-guard';
import { HookManager } from '../../core/hooks';
+import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
export interface WebhookPayload {
event: string;
@@ -57,6 +58,7 @@ export interface WebhookJobData {
export class WebhookService implements OnModuleInit, OnModuleDestroy {
private readonly logger = createLogger('WebhookService');
private readonly queueEnabled: boolean;
+ private readonly dispatchLimiter: ConcurrencyLimiter;
private cleanupTimer?: ReturnType<typeof setInterval>;
constructor(
@@ -73,6 +75,10 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {
private readonly webhookQueue?: Queue<WebhookJobData>,
) {
this.queueEnabled = configService.get<boolean>('queue.enabled', false);
+ // Bound fan-out: cap how many matching webhooks are delivered CONCURRENTLY for one event. Without
+ // it, an event matching N webhooks opens N outbound sockets at once. Default 16
+ // (WEBHOOK_DISPATCH_CONCURRENCY).
+ this.dispatchLimiter = new ConcurrencyLimiter(this.configService.get<number>('webhook.dispatchConcurrency', 16));
}
/**
@@ -304,7 +310,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {
// Dispatch to all matching webhooks concurrently — one slow/hanging receiver must not head-of-line-
// block delivery to the sibling webhooks of the same event (the direct/fallback paths await a
// recursive retry with backoff sleeps).
- const tasks = matchingWebhooks.map(async webhook => {
+ const deliverOne = async (webhook: Webhook): Promise<void> => {
// Generate unique delivery ID for each webhook
const deliveryId = generateDeliveryId();
@@ -488,7 +494,11 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {
});
}
}
- });
+ };
+ // Bound fan-out: deliver to all matching webhooks concurrently, but cap in-flight deliveries at
+ // WEBHOOK_DISPATCH_CONCURRENCY so an event matching many webhooks (or slow receivers) can't open an
+ // unbounded number of outbound sockets at once. allSettled preserves the per-webhook isolation.
+ const tasks = matchingWebhooks.map(webhook => this.dispatchLimiter.run(() => deliverOne(webhook)));
await Promise.allSettled(tasks);
}