Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(queue): make webhook enqueue idempotent and pin Redis to noeviction

Yudhi Armyndharis00df0c5e4607
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 72a182626..85b846809 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **A crash mid-enqueue can no longer deliver a webhook twice.** The webhook producer passed a job
+ name but no job id, so BullMQ treated every `add()` as a new job: a process that died between the
+ enqueue and its bookkeeping could re-enqueue the same delivery on the next attempt, and nothing
+ downstream would notice — deduplication rested entirely on the receiver honouring
+ `X-OpenWA-Delivery-Id`. The job id is now that same delivery id, which gives BullMQ exactly-once
+ enqueue semantics and puts both dedupe boundaries on one identifier. The id is minted per webhook
+ per dispatch, so an event fanning out to several subscriptions still produces one job each.
+- **The bundled Redis no longer risks silently dropping queued jobs.** BullMQ requires the
+ `noeviction` maxmemory policy; both Redis launch paths — `docker-compose.yml` and the
+ dashboard-orchestrated container — started `redis-server` with `--appendonly yes` alone, leaving
+ the policy at whatever the image defaults to. Under any evicting policy Redis may discard queue
+ keys once `maxmemory` is reached, losing jobs with no error raised anywhere. Both paths (and the
+ scaling guide's compose sample) now pass `--maxmemory-policy noeviction`.
+
- **A media storage root the app cannot write to is now caught at boot, with an error that says what
to change.** The check ran on the wrong question: `StorageService` created the root only when it did
not already exist, so a root that existed but belonged to another user sailed through startup and
diff --git a/docker-compose.yml b/docker-compose.yml
index 2e544bb0d..9c1093464 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -281,7 +281,9 @@ services:
- openwa-network
security_opt:
- 'no-new-privileges:true'
- command: redis-server --appendonly yes
+ # noeviction is required by BullMQ: under any other policy Redis may evict queue keys once
+ # maxmemory is reached, silently dropping queued jobs.
+ command: redis-server --appendonly yes --maxmemory-policy noeviction
volumes:
- redis-data:/data
healthcheck:
diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.md
index cbd3dc7f7..49b494f68 100644
--- a/docs/13-horizontal-scaling.md
+++ b/docs/13-horizontal-scaling.md
@@ -161,7 +161,7 @@ services:
image: redis:7-alpine
deploy:
replicas: 1
- command: redis-server --appendonly yes
+ command: redis-server --appendonly yes --maxmemory-policy noeviction
volumes:
- redis-data:/data
networks:
diff --git a/src/modules/docker/compose-parity.spec.ts b/src/modules/docker/compose-parity.spec.ts
index 50621e250..2c9ddc9aa 100644
--- a/src/modules/docker/compose-parity.spec.ts
+++ b/src/modules/docker/compose-parity.spec.ts
@@ -235,6 +235,15 @@ describe('DockerService managed specs ↔ docker-compose.yml parity', () => {
expect(cfg.Env).toBeUndefined();
});
+ it('redis: sets the noeviction maxmemory policy BullMQ requires, on both launch paths', async () => {
+ const cfg = await capture('redis');
+ // The parity assertion above only proves the two launch paths AGREE — dropping the flag from
+ // both would keep it green. BullMQ needs noeviction: under any other policy Redis may evict
+ // queue keys once maxmemory is reached, losing queued jobs with no error surfaced anywhere.
+ expect(compose.services.redis.command).toContain('--maxmemory-policy noeviction');
+ expect(cfg.Cmd).toEqual(expect.arrayContaining(['--maxmemory-policy', 'noeviction']));
+ });
+
it('redis: publishes no host ports, like compose', async () => {
const cfg = await capture('redis');
expect(compose.services.redis.ports).toBeUndefined();
diff --git a/src/modules/docker/docker.service.ts b/src/modules/docker/docker.service.ts
index e4d1f739f..725b5057c 100644
--- a/src/modules/docker/docker.service.ts
+++ b/src/modules/docker/docker.service.ts
@@ -240,7 +240,9 @@ export class DockerService implements OnModuleInit {
image: 'redis:7-alpine',
name: 'openwa-redis',
alias: 'redis', // DNS alias for resolution
- cmd: ['redis-server', '--appendonly', 'yes'],
+ // noeviction mirrors docker-compose.yml: BullMQ requires it, or Redis may evict queue keys
+ // once maxmemory is reached and silently drop queued jobs.
+ cmd: ['redis-server', '--appendonly', 'yes', '--maxmemory-policy', 'noeviction'],
volumes: [{ name: 'openwa_redis-data', path: '/data' }],
healthcheck: {
test: ['CMD', 'redis-cli', 'ping'],
diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.ts
index 0f3602512..80b24db34 100644
--- a/src/modules/webhook/webhook.service.spec.ts
+++ b/src/modules/webhook/webhook.service.spec.ts
@@ -1419,6 +1419,52 @@ describe('WebhookService', () => {
expect(JSON.stringify(jobData).length).toBeLessThan(2048);
});
+ it('keys the queue job by the delivery id, so a retried enqueue cannot double-deliver', async () => {
+ const queueService = await buildQueueService((key: string, def?: unknown) => {
+ if (key === 'queue.enabled') return true;
+ if (key === 'webhook.retryDelay') return 5000;
+ return def;
+ });
+ (repository.find as jest.Mock).mockResolvedValue([createMockWebhook({ events: ['message.received'] })]);
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+
+ await queueService.dispatch('sess-1', 'message.received', {});
+
+ const [, jobData, opts] = (webhookQueue.add as jest.Mock).mock.calls[0] as [
+ string,
+ WebhookJobData,
+ { jobId?: string },
+ ];
+ // BullMQ's dedupe boundary and the receiver's must key off the SAME identifier, or a job
+ // that BullMQ accepts twice still looks like one delivery to the receiver (and vice versa).
+ expect(opts.jobId).toBe(jobData.headers['X-OpenWA-Delivery-Id']);
+ expect(opts.jobId).toBe(jobData.payload.deliveryId);
+ });
+
+ it('gives sibling webhooks distinct job ids, so one event fanning out is not collapsed into one job', async () => {
+ const queueService = await buildQueueService((key: string, def?: unknown) => {
+ if (key === 'queue.enabled') return true;
+ if (key === 'webhook.retryDelay') return 5000;
+ return def;
+ });
+ (repository.find as jest.Mock).mockResolvedValue([
+ createMockWebhook({ id: 'wh-uuid-1', events: ['message.received'] }),
+ createMockWebhook({ id: 'wh-uuid-2', events: ['message.received'], url: 'https://example.com/other' }),
+ ]);
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+
+ await queueService.dispatch('sess-1', 'message.received', {});
+
+ // Guards the invariant that makes jobId = deliveryId safe: deliveryId is minted per webhook
+ // per dispatch. Were it ever hoisted to per-event, BullMQ would silently drop every
+ // subscription after the first — a data-loss bug with no error anywhere.
+ expect(webhookQueue.add).toHaveBeenCalledTimes(2);
+ const jobIds = (webhookQueue.add as jest.Mock).mock.calls.map(
+ (call: [string, WebhookJobData, { jobId?: string }]) => call[2].jobId,
+ );
+ expect(new Set(jobIds).size).toBe(2);
+ });
+
it('should add job to queue when queue is enabled', async () => {
// Create a new service with queue enabled
const queueModule: TestingModule = await Test.createTestingModule({
diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.ts
index b180e0452..aa7f29daf 100644
--- a/src/modules/webhook/webhook.service.ts
+++ b/src/modules/webhook/webhook.service.ts
@@ -657,6 +657,11 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {
};
await this.webhookQueue!.add(`webhook-${webhook.id}`, jobData, {
+ // jobId = deliveryId gives BullMQ exactly-once enqueue semantics (same precedent as the
+ // ingress producer), so a crash between add() and the bookkeeping below cannot re-enqueue
+ // the same delivery. Safe for fan-out: deliveryId is minted per webhook per dispatch in
+ // dispatchWithLimit, so sibling subscriptions to one event never share a job id.
+ jobId: deliveryId,
attempts: webhook.retryCount,
backoff: {
type: 'exponential',