Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(webhook): bound the outbound delivery record

Yudhi Armyndharis9270a3e3fb5c
diff --git a/.env.example b/.env.example
index d2b896b14..fc68209ff 100644
--- a/.env.example
+++ b/.env.example
@@ -622,6 +622,8 @@ WEBHOOK_SSRF_PROTECT=true
# WEBHOOK_RECONCILE_GRACE_MS=60000 # age a 'pending' row must pass before it counts as stranded
# WEBHOOK_RECONCILE_BATCH_SIZE=50 # stranded rows replayed per sweep, oldest first
# WEBHOOK_RECONCILE_MAX_ATTEMPTS=5 # replays before the row goes terminal (min 1)
+# WEBHOOK_OUTBOX_RETENTION_DAYS=7 # prune settled records after N days; a non-positive value
+ # falls back to 7 rather than letting the table grow forever
# Concurrency of the BullMQ workers that process queued webhooks and ingress events. Only meaningful
# when QUEUE_ENABLED=true. Ordering within one conversation is preserved by a per-conversation lock,
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c8ddb85e1..6be08db98 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The dashboard CSP nonce is substituted at every occurrence in the served document, not only the first. One placeholder exists today, so a second would have been left reading the literal text and its script refused by the browser.
- Outbound webhook deliveries survive a hard crash. Fan-out is fire-and-forget, so a crash between persisting a message and completing its POST lost the delivery with no record in either mode, while the documented contract promises at-least-once. Each delivery is now recorded before it is attempted, retired once the queue or the inline send owns it, and a bounded sweep replays whatever is left stranded using the stored idempotency key so the retry stays deduplicable at the receiver.
+- Settled outbound delivery records are pruned after `WEBHOOK_OUTBOX_RETENTION_DAYS` (default 7). A record that can still be replayed is never pruned on age, and a non-positive window falls back to the default rather than letting the table grow without bound.
### Tests
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 84f636b9e..e4d65f8a7 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -213,6 +213,7 @@ services:
- WEBHOOK_RECONCILE_GRACE_MS=${WEBHOOK_RECONCILE_GRACE_MS:-}
- WEBHOOK_RECONCILE_BATCH_SIZE=${WEBHOOK_RECONCILE_BATCH_SIZE:-}
- WEBHOOK_RECONCILE_MAX_ATTEMPTS=${WEBHOOK_RECONCILE_MAX_ATTEMPTS:-}
+ - WEBHOOK_OUTBOX_RETENTION_DAYS=${WEBHOOK_OUTBOX_RETENTION_DAYS:-}
- INGRESS_WORKER_CONCURRENCY=${INGRESS_WORKER_CONCURRENCY:-}
# WebSocket gateway limits.
- WS_RATE_LIMIT_FRAME_PER_SECOND=${WS_RATE_LIMIT_FRAME_PER_SECOND:-}
diff --git a/docker-compose.yml b/docker-compose.yml
index c61f8fff4..f601d94d7 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -310,6 +310,7 @@ services:
- WEBHOOK_RECONCILE_GRACE_MS=${WEBHOOK_RECONCILE_GRACE_MS:-}
- WEBHOOK_RECONCILE_BATCH_SIZE=${WEBHOOK_RECONCILE_BATCH_SIZE:-}
- WEBHOOK_RECONCILE_MAX_ATTEMPTS=${WEBHOOK_RECONCILE_MAX_ATTEMPTS:-}
+ - WEBHOOK_OUTBOX_RETENTION_DAYS=${WEBHOOK_OUTBOX_RETENTION_DAYS:-}
- INGRESS_WORKER_CONCURRENCY=${INGRESS_WORKER_CONCURRENCY:-}
# WebSocket gateway limits (frames bypass the HTTP guard pipeline).
- WS_RATE_LIMIT_FRAME_PER_SECOND=${WS_RATE_LIMIT_FRAME_PER_SECOND:-}
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index a5da10226..41d036c0f 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -6776,7 +6776,7 @@ Webhook delivery is **at-least-once**. A consumer can legitimately receive the s
- The underlying WhatsApp engine can re-fire an event for a single message.
- A failed delivery (non-2xx response, timeout, or network error) is retried.
-**Crash boundary.** Every delivery is recorded before it is attempted, and the record is retired once something durable owns it: the queue job in queued mode, the completed send in direct mode. A hard crash (SIGKILL, OOM) therefore leaves the record behind, and a bounded sweep (`WEBHOOK_RECONCILE_INTERVAL_MS`, default 60s) replays whatever is still stranded, reusing the stored `X-OpenWA-Idempotency-Key` so the retry stays deduplicable at your receiver. A delivery that keeps failing exhausts `WEBHOOK_RECONCILE_MAX_ATTEMPTS` and goes terminal rather than replaying forever. One window remains open: a crash between persisting the message and writing that record loses the delivery, because the two are not yet one transaction. The failure table records exhausted retries, plus over-budget, dispatch-capacity-exceeded, and shutdown-rejected deliveries with attempts 0. Enabling the queue (`QUEUE_ENABLED=true`, needs Redis) makes the dispatch durable from the enqueue onward. In both modes, a graceful shutdown drains in-flight deliveries first: the queued path waits for each worker's current job, and the direct path waits up to `WEBHOOK_SHUTDOWN_DRAIN_MS` (default 5s; raise it to at least `WEBHOOK_TIMEOUT`, default 10s, if a slow receiver must finish).
+**Crash boundary.** Every delivery is recorded before it is attempted, and the record is retired once something durable owns it: the queue job in queued mode, the completed send in direct mode. A hard crash (SIGKILL, OOM) therefore leaves the record behind, and a bounded sweep (`WEBHOOK_RECONCILE_INTERVAL_MS`, default 60s) replays whatever is still stranded, reusing the stored `X-OpenWA-Idempotency-Key` so the retry stays deduplicable at your receiver. A delivery that keeps failing exhausts `WEBHOOK_RECONCILE_MAX_ATTEMPTS` and goes terminal rather than replaying forever. One window remains open: a crash between persisting the message and writing that record loses the delivery, because the two are not yet one transaction. The failure table records exhausted retries, plus over-budget, dispatch-capacity-exceeded, and shutdown-rejected deliveries with attempts 0. Read the last two as a report rather than a verdict: a delivery the dispatcher shed for capacity or refused during the drain keeps its record and is replayed by the same sweep, so a row there can belong to an event that was later delivered. Enabling the queue (`QUEUE_ENABLED=true`, needs Redis) makes the dispatch durable from the enqueue onward. In both modes, a graceful shutdown drains in-flight deliveries first: the queued path waits for each worker's current job, and the direct path waits up to `WEBHOOK_SHUTDOWN_DRAIN_MS` (default 5s; raise it to at least `WEBHOOK_TIMEOUT`, default 10s, if a slow receiver must finish).
**Design your handler to be idempotent**, keyed on the `X-OpenWA-Idempotency-Key` header (see below). As a server-side safety net, OpenWA de-duplicates inbound `message.received` before dispatch (a re-fired event for an already-persisted message is dropped), so one webhook normally sees each inbound message once — but this is best-effort defense-in-depth and does not remove the need for consumer-side idempotency.
diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.ts
index f198499ac..c52786bf0 100644
--- a/src/config/env-precedence.ts
+++ b/src/config/env-precedence.ts
@@ -177,6 +177,7 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = [
'WEBHOOK_RECONCILE_GRACE_MS',
'WEBHOOK_RECONCILE_BATCH_SIZE',
'WEBHOOK_RECONCILE_MAX_ATTEMPTS',
+ 'WEBHOOK_OUTBOX_RETENTION_DAYS',
'INGRESS_WORKER_CONCURRENCY',
'WS_RATE_LIMIT_FRAME_PER_SECOND',
'WS_RATE_LIMIT_FRAME_BURST',
diff --git a/src/modules/webhook/webhook-outbox.service.spec.ts b/src/modules/webhook/webhook-outbox.service.spec.ts
index 6fba5c060..01f0fb78b 100644
--- a/src/modules/webhook/webhook-outbox.service.spec.ts
+++ b/src/modules/webhook/webhook-outbox.service.spec.ts
@@ -80,3 +80,41 @@ describe('WebhookOutboxService', () => {
expect(repo.update).toHaveBeenCalledWith({ id: 'row-1' }, expect.objectContaining({ attempts: 3 }));
});
});
+
+describe('WebhookOutboxService retention', () => {
+ let repo: { delete: jest.Mock };
+ let service: WebhookOutboxService;
+
+ beforeEach(() => {
+ repo = { delete: jest.fn().mockResolvedValue({ affected: 3 }) };
+ service = new WebhookOutboxService(repo as never);
+ });
+
+ it('prunes settled rows only, never one that can still be replayed', async () => {
+ const removed = await service.pruneSettled(7);
+
+ expect(removed).toBe(3);
+ const [[where]] = repo.delete.mock.calls as unknown as [
+ [{ state: { type: string; value: unknown }; createdAt: { type: string } }],
+ ];
+ // Deleting a 'pending' row on age would discard the delivery this table exists to protect.
+ expect(where.state.type).toBe('not');
+ expect(where.state.value).toBe('pending');
+ expect(where.createdAt.type).toBe('lessThan');
+ });
+
+ it('refuses a retention window that would let the table grow without bound', () => {
+ const prev = process.env.WEBHOOK_OUTBOX_RETENTION_DAYS;
+ process.env.WEBHOOK_OUTBOX_RETENTION_DAYS = '0';
+ try {
+ service.onModuleInit();
+ // A settled row carries no payload and no audit value, so opting into unbounded growth buys
+ // nothing: the value falls back rather than disabling the prune.
+ expect(repo.delete).toHaveBeenCalled();
+ } finally {
+ service.onModuleDestroy();
+ if (prev === undefined) delete process.env.WEBHOOK_OUTBOX_RETENTION_DAYS;
+ else process.env.WEBHOOK_OUTBOX_RETENTION_DAYS = prev;
+ }
+ });
+});
diff --git a/src/modules/webhook/webhook-outbox.service.ts b/src/modules/webhook/webhook-outbox.service.ts
index 51c1dffdf..f1baf88d8 100644
--- a/src/modules/webhook/webhook-outbox.service.ts
+++ b/src/modules/webhook/webhook-outbox.service.ts
@@ -1,10 +1,12 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import { LessThan, Repository } from 'typeorm';
+import { LessThan, Not, Repository } from 'typeorm';
import { WebhookOutboxEvent, WebhookOutboxState } from './entities/webhook-outbox-event.entity';
import { createLogger } from '../../common/services/logger.service';
import { isUniqueViolation } from '../../common/utils/db-errors';
+const DEFAULT_OUTBOX_RETENTION_DAYS = 7;
+
/** What a replay needs to redispatch one delivery without deriving a new idempotency key. */
export interface ReplayableDelivery {
id: string;
@@ -24,14 +26,61 @@ export interface ReplayableDelivery {
* otherwise succeed. Losing the record degrades to the behaviour that existed before it.
*/
@Injectable()
-export class WebhookOutboxService {
+export class WebhookOutboxService implements OnModuleInit, OnModuleDestroy {
private readonly logger = createLogger('WebhookOutboxService');
+ private pruneTimer?: ReturnType<typeof setInterval>;
constructor(
@InjectRepository(WebhookOutboxEvent, 'data')
private readonly outbox: Repository<WebhookOutboxEvent>,
) {}
+ /**
+ * Prune settled rows daily, so the record of every delivery this gateway ever made does not
+ * become the largest table in the database.
+ *
+ * Deliberately NOT tied to the delivery-failure retention switch: a settled row carries no
+ * payload and no audit value (the failure table is the record that matters), so letting an
+ * operator opt into unbounded growth here buys nothing. A non-positive value falls back to the
+ * default with a warning, the same call the ingress dedup log makes.
+ *
+ * Only SETTLED rows are pruned. A 'pending' row is a delivery that can still be replayed, and
+ * deleting one on age would discard the very thing this table exists to protect.
+ */
+ onModuleInit(): void {
+ const parsed = Number.parseInt(process.env.WEBHOOK_OUTBOX_RETENTION_DAYS ?? '', 10);
+ let days = Number.isInteger(parsed) ? parsed : DEFAULT_OUTBOX_RETENTION_DAYS;
+ if (days <= 0) {
+ this.logger.warn(
+ `WEBHOOK_OUTBOX_RETENTION_DAYS=${String(process.env.WEBHOOK_OUTBOX_RETENTION_DAYS)} would let the ` +
+ `outbound delivery record grow without bound; falling back to ${DEFAULT_OUTBOX_RETENTION_DAYS} days`,
+ );
+ days = DEFAULT_OUTBOX_RETENTION_DAYS;
+ }
+ const run = (): void => {
+ this.pruneSettled(days)
+ .then(n => {
+ if (n > 0) this.logger.log(`Pruned ${n} settled outbound delivery record(s) older than ${days} day(s)`);
+ })
+ .catch(err => this.logger.error('Outbound delivery record prune failed', String(err)));
+ };
+ run();
+ this.pruneTimer = setInterval(run, 24 * 60 * 60 * 1000);
+ this.pruneTimer.unref?.();
+ }
+
+ onModuleDestroy(): void {
+ if (this.pruneTimer) clearInterval(this.pruneTimer);
+ }
+
+ /** Delete settled rows older than the window. Returns the number removed. */
+ async pruneSettled(olderThanDays: number): Promise<number> {
+ const cutoff = new Date();
+ cutoff.setDate(cutoff.getDate() - olderThanDays);
+ const result = await this.outbox.delete({ state: Not('pending'), createdAt: LessThan(cutoff) });
+ return result.affected || 0;
+ }
+
/**
* Record the delivery as pending, before anything durable owns it.
*
diff --git a/src/modules/webhook/webhook-reconciler.service.ts b/src/modules/webhook/webhook-reconciler.service.ts
index a0104e8e1..354fcec8e 100644
--- a/src/modules/webhook/webhook-reconciler.service.ts
+++ b/src/modules/webhook/webhook-reconciler.service.ts
@@ -48,6 +48,12 @@ export interface WebhookReconcileStats {
*
* Mirrors IngressReconcilerService on the inbound side: an unref'd interval started on module init,
* an overlap guard so a slow pass never stacks, a bounded batch, and a per-row replay budget.
+ *
+ * The sweep does NOT claim a row, so two nodes running against one database can both replay the
+ * same delivery. That is deliberate and matches the inbound reconciler: the replay carries the
+ * stored idempotency key, which is exactly the header a receiver dedups on, so the cost of the
+ * race is a duplicate the contract already tells consumers to expect. Claiming would trade that
+ * for a lock whose holder can die mid-flight.
*/
@Injectable()
export class WebhookReconcilerService implements OnModuleInit, OnModuleDestroy {