Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): de-duplicate inbound messages so each WhatsApp message is delivered once (#466)

Yudhi Armyndharis85617e1a282c
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index ad95cafd9..ec3aeaf11 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1324,6 +1324,19 @@ GET /api/health/live
OpenWA provides an idempotency mechanism to prevent duplicate processing on the client side.
+#### Delivery Semantics
+
+Webhook delivery is **at-least-once**. WhatsApp engines can re-fire an event for a single message, and
+failed deliveries are retried, so a consumer can receive the same event more than once. **Design your
+handler to be idempotent**, keyed on the `X-OpenWA-Idempotency-Key` header (or the `idempotencyKey`
+field) — that key is content-based, so every duplicate of the same message carries the identical value;
+prefer it over hashing the payload yourself.
+
+As a safety net, OpenWA de-duplicates inbound `message.received` **server-side**: a re-fired event for a
+message already persisted is dropped before dispatch, so one registered webhook normally receives each
+inbound message once. This guard is best-effort defense-in-depth and does not remove the need for
+consumer-side idempotency on the key above.
+
#### Idempotency Headers & Fields
| Field/Header | Description |
diff --git a/src/common/utils/unique-constraint.util.spec.ts b/src/common/utils/unique-constraint.util.spec.ts
new file mode 100644
index 000000000..96b2e8eb2
--- /dev/null
+++ b/src/common/utils/unique-constraint.util.spec.ts
@@ -0,0 +1,32 @@
+import { isUniqueConstraintError } from './unique-constraint.util';
+
+describe('isUniqueConstraintError', () => {
+ it('recognizes a PostgreSQL unique_violation (code 23505)', () => {
+ expect(isUniqueConstraintError({ driverError: { code: '23505' } })).toBe(true);
+ });
+
+ it('recognizes a SQLite constraint error by code', () => {
+ expect(isUniqueConstraintError({ driverError: { code: 'SQLITE_CONSTRAINT_UNIQUE' } })).toBe(true);
+ });
+
+ it('recognizes a SQLite constraint error by message', () => {
+ expect(isUniqueConstraintError(new Error('SQLITE_CONSTRAINT: UNIQUE constraint failed: messages.sessionId'))).toBe(
+ true,
+ );
+ });
+
+ it('returns false for a non-unique DB error (e.g. FK violation 23503)', () => {
+ expect(isUniqueConstraintError({ driverError: { code: '23503' } })).toBe(false);
+ });
+
+ it('returns false for an unrelated error and for null', () => {
+ expect(isUniqueConstraintError(new Error('boom'))).toBe(false);
+ expect(isUniqueConstraintError(null)).toBe(false);
+ });
+
+ it('does not false-positive on a non-unique code whose message contains the unique phrase', () => {
+ expect(isUniqueConstraintError({ driverError: { code: '23503', message: 'UNIQUE constraint failed: x' } })).toBe(
+ false,
+ );
+ });
+});
diff --git a/src/common/utils/unique-constraint.util.ts b/src/common/utils/unique-constraint.util.ts
new file mode 100644
index 000000000..4e1b66853
--- /dev/null
+++ b/src/common/utils/unique-constraint.util.ts
@@ -0,0 +1,15 @@
+/**
+ * True when `err` is a unique-constraint violation, across SQLite and PostgreSQL. TypeORM wraps
+ * driver errors in QueryFailedError; the dialect-specific detail sits on `driverError`. Used to tell
+ * a duplicate-key insert (skip it) apart from a genuine persistence failure (must not be swallowed).
+ */
+export function isUniqueConstraintError(err: unknown): boolean {
+ if (err == null || typeof err !== 'object') return false;
+ const e = err as { code?: string; message?: string; driverError?: { code?: string; message?: string } };
+ const code = e.driverError?.code ?? e.code;
+ const message = e.driverError?.message ?? e.message ?? '';
+ if (code === '23505') return true; // PostgreSQL unique_violation
+ if (typeof code === 'string' && code.startsWith('SQLITE_CONSTRAINT')) return true; // SQLite
+ if (code != null) return false; // a decisive non-unique code wins over a misleading message
+ return /UNIQUE constraint failed/i.test(message); // SQLite fallback (message only)
+}
diff --git a/src/database/migrations/1781300000000-AddMessagesWaMessageIdUnique.ts b/src/database/migrations/1781300000000-AddMessagesWaMessageIdUnique.ts
new file mode 100644
index 000000000..72a7b8bb6
--- /dev/null
+++ b/src/database/migrations/1781300000000-AddMessagesWaMessageIdUnique.ts
@@ -0,0 +1,38 @@
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+/**
+ * Enforces one row per (sessionId, waMessageId) on `messages` (issue #464): the engine can re-fire
+ * the inbound `message` event, and the old blind insert persisted the same WhatsApp message twice.
+ *
+ * Pre-existing duplicates are removed losslessly — a duplicate (sessionId, waMessageId) IS the same
+ * message, so the earliest row (createdAt ASC, id ASC) is kept and the rest deleted. Rows with a NULL
+ * waMessageId are exempt (SQL treats NULLs as distinct), preserving transient outgoing PENDING rows.
+ *
+ * Hand-authored because `synchronize` is off for the `data` connection. Idempotent + cross-dialect.
+ */
+export class AddMessagesWaMessageIdUnique1781300000000 implements MigrationInterface {
+ name = 'AddMessagesWaMessageIdUnique1781300000000';
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ if (!(await queryRunner.hasTable('messages'))) return;
+
+ await queryRunner.query(
+ `DELETE FROM "messages" WHERE "waMessageId" IS NOT NULL AND "id" <> (` +
+ `SELECT m2."id" FROM "messages" m2 ` +
+ `WHERE m2."sessionId" = "messages"."sessionId" AND m2."waMessageId" = "messages"."waMessageId" ` +
+ `ORDER BY m2."createdAt" ASC, m2."id" ASC LIMIT 1)`,
+ );
+
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_messages_sessionId_waMessageId"`);
+ await queryRunner.query(
+ `CREATE UNIQUE INDEX IF NOT EXISTS "UQ_messages_sessionId_waMessageId" ON "messages" ("sessionId", "waMessageId")`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`DROP INDEX IF EXISTS "UQ_messages_sessionId_waMessageId"`);
+ await queryRunner.query(
+ `CREATE INDEX IF NOT EXISTS "IDX_messages_sessionId_waMessageId" ON "messages" ("sessionId", "waMessageId")`,
+ );
+ }
+}
diff --git a/src/database/migrations/__tests__/1781300000000-AddMessagesWaMessageIdUnique.spec.ts b/src/database/migrations/__tests__/1781300000000-AddMessagesWaMessageIdUnique.spec.ts
new file mode 100644
index 000000000..02ac67972
--- /dev/null
+++ b/src/database/migrations/__tests__/1781300000000-AddMessagesWaMessageIdUnique.spec.ts
@@ -0,0 +1,67 @@
+import { DataSource } from 'typeorm';
+import { AddMessagesWaMessageIdUnique1781300000000 } from '../1781300000000-AddMessagesWaMessageIdUnique';
+
+describe('AddMessagesWaMessageIdUnique migration', () => {
+ let ds: DataSource;
+
+ beforeEach(async () => {
+ ds = new DataSource({ type: 'sqlite', database: ':memory:' });
+ await ds.initialize();
+ await ds.query(
+ `CREATE TABLE "messages" ("id" varchar PRIMARY KEY NOT NULL, "sessionId" varchar NOT NULL, ` +
+ `"waMessageId" varchar, "chatId" varchar NOT NULL, "from" varchar NOT NULL, "to" varchar NOT NULL, ` +
+ `"body" text, "type" varchar NOT NULL DEFAULT ('text'), "direction" varchar NOT NULL DEFAULT ('outgoing'), ` +
+ `"timestamp" bigint, "metadata" text, "status" varchar NOT NULL DEFAULT ('sent'), ` +
+ `"createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
+ );
+ await ds.query(`CREATE INDEX "IDX_messages_sessionId_waMessageId" ON "messages" ("sessionId", "waMessageId")`);
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ const insert = (id: string, sessionId: string, waMessageId: string | null, createdAt: string): Promise<unknown> =>
+ ds.query(
+ `INSERT INTO "messages" ("id","sessionId","waMessageId","chatId","from","to","body","type","direction","timestamp","status","createdAt") ` +
+ `VALUES (?,?,?,'[email protected]','[email protected]','[email protected]','hi','text','incoming',1,'sent',?)`,
+ [id, sessionId, waMessageId, createdAt],
+ );
+
+ it('deletes duplicate (sessionId, waMessageId) rows keeping the earliest, then enforces uniqueness', async () => {
+ await insert('id-early', 'sess-1', 'wa-1', '2026-01-01T00:00:00.000Z');
+ await insert('id-late', 'sess-1', 'wa-1', '2026-02-01T00:00:00.000Z');
+ await insert('id-other', 'sess-1', 'wa-2', '2026-01-01T00:00:00.000Z');
+
+ const runner = ds.createQueryRunner();
+ await new AddMessagesWaMessageIdUnique1781300000000().up(runner);
+
+ const rows = (await runner.query(`SELECT id FROM "messages" ORDER BY id`)) as { id: string }[];
+ expect(rows.map(r => r.id).sort()).toEqual(['id-early', 'id-other']); // later dup deleted, earliest kept
+
+ await expect(insert('id-new', 'sess-1', 'wa-1', '2026-03-01T00:00:00.000Z')).rejects.toThrow();
+ await runner.release();
+ });
+
+ it('keeps multiple NULL-waMessageId rows (NULLs are distinct under the unique index)', async () => {
+ await insert('p1', 'sess-1', null, '2026-01-01T00:00:00.000Z');
+ await insert('p2', 'sess-1', null, '2026-01-01T00:00:01.000Z');
+
+ const runner = ds.createQueryRunner();
+ await new AddMessagesWaMessageIdUnique1781300000000().up(runner);
+
+ const rows = (await runner.query(`SELECT id FROM "messages" WHERE "waMessageId" IS NULL`)) as unknown[];
+ expect(rows).toHaveLength(2);
+ await runner.release();
+ });
+
+ it('is idempotent and a no-op when the table is absent', async () => {
+ const runner = ds.createQueryRunner();
+ const migration = new AddMessagesWaMessageIdUnique1781300000000();
+ await migration.up(runner);
+ await expect(migration.up(runner)).resolves.toBeUndefined(); // re-run: index already exists
+ await ds.query(`DROP TABLE "messages"`);
+ await expect(migration.up(runner)).resolves.toBeUndefined(); // absent table
+ await runner.release();
+ });
+});
diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.ts
index 000d392b1..de344b959 100644
--- a/src/modules/message/entities/message.entity.ts
+++ b/src/modules/message/entities/message.entity.ts
@@ -36,7 +36,7 @@ export enum MessageStatus {
@Index(['chatId'])
// Composite index for the ack-driven status UPDATE (scoped by sessionId + waMessageId).
// Without it every ack does a full table scan of a hot table.
-@Index(['sessionId', 'waMessageId'])
+@Index('UQ_messages_sessionId_waMessageId', ['sessionId', 'waMessageId'], { unique: true })
export class Message {
@PrimaryGeneratedColumn('uuid')
id: string;
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 7782f9b4f..bf089f647 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -57,6 +57,7 @@ describe('SessionService', () => {
findOne: jest.fn().mockResolvedValue(null),
create: jest.fn(),
save: jest.fn().mockResolvedValue(undefined),
+ insert: jest.fn().mockResolvedValue(undefined),
update: jest.fn().mockResolvedValue({ affected: 1 }),
};
@@ -607,7 +608,7 @@ describe('SessionService', () => {
it('ignores onMessage from a superseded engine (no persist, no webhook)', async () => {
const callbacks = await startAndCapture();
enginesOf().set('sess-uuid-1', { marker: 'engine-B' });
- (messageRepository.save as jest.Mock).mockClear();
+ (messageRepository.insert as jest.Mock).mockClear();
(webhookService.dispatch as jest.Mock).mockClear();
callbacks.onMessage?.({
@@ -623,7 +624,7 @@ describe('SessionService', () => {
});
await new Promise(resolve => setImmediate(resolve));
- expect(messageRepository.save).not.toHaveBeenCalled();
+ expect(messageRepository.insert).not.toHaveBeenCalled();
expect(webhookService.dispatch).not.toHaveBeenCalled();
});
});
@@ -1174,6 +1175,99 @@ describe('SessionService', () => {
);
expect(qrStatus).toHaveLength(1);
});
+
+ it('persists and dispatches message.received only once when the engine re-fires the same message', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ (messageRepository.insert as jest.Mock).mockReset();
+ (webhookService.dispatch as jest.Mock).mockClear();
+ (messageRepository.insert as jest.Mock)
+ .mockResolvedValueOnce(undefined) // first delivery: new row
+ .mockRejectedValueOnce({
+ driverError: { code: 'SQLITE_CONSTRAINT_UNIQUE', message: 'UNIQUE constraint failed' },
+ }); // re-fire
+
+ const msg = {
+ id: 'wa-1',
+ chatId: '[email protected]',
+ body: 'hi',
+ type: 'text',
+ timestamp: 1,
+ fromMe: false,
+ isGroup: false,
+ };
+ callbacks.onMessage?.(msg);
+ await flush();
+ callbacks.onMessage?.(msg); // re-fired engine event
+ await flush();
+
+ expect(messageRepository.insert).toHaveBeenCalledTimes(2);
+ expect(
+ ((webhookService.dispatch as jest.Mock).mock.calls as unknown[][]).filter(c => c[1] === 'message.received'),
+ ).toHaveLength(1);
+ });
+
+ it('still dispatches message.received when the insert fails with a non-constraint error (fail-open)', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ (messageRepository.insert as jest.Mock).mockReset();
+ (webhookService.dispatch as jest.Mock).mockClear();
+ (messageRepository.insert as jest.Mock).mockRejectedValueOnce(new Error('db down'));
+
+ callbacks.onMessage?.({
+ id: 'wa-2',
+ chatId: '[email protected]',
+ body: 'hi',
+ type: 'text',
+ timestamp: 1,
+ fromMe: false,
+ isGroup: false,
+ });
+ await flush();
+
+ expect(
+ ((webhookService.dispatch as jest.Mock).mock.calls as unknown[][]).filter(c => c[1] === 'message.received'),
+ ).toHaveLength(1);
+ });
+
+ // ── persistHistoryMessages collision tolerance ───────────────────
+ describe('persistHistoryMessages collision tolerance', () => {
+ it('uses an insert-or-ignore bulk insert so a colliding history row cannot abort the batch', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ const execute = jest.fn().mockResolvedValue({ identifiers: [] });
+ const qb = {
+ insert: jest.fn().mockReturnThis(),
+ values: jest.fn().mockReturnThis(),
+ orIgnore: jest.fn().mockReturnThis(),
+ execute,
+ };
+ (messageRepository.createQueryBuilder as jest.Mock) = jest.fn().mockReturnValue(qb);
+ (messageRepository.find as jest.Mock).mockResolvedValue([]); // nothing pre-seen
+ (messageRepository.create as jest.Mock).mockImplementation((data: Record<string, unknown>) => ({ ...data }));
+ (messageRepository.save as jest.Mock).mockClear();
+
+ callbacks.onHistoryMessages?.([
+ {
+ id: 'h1',
+ chatId: '[email protected]',
+ body: 'old',
+ type: 'text',
+ timestamp: 1,
+ fromMe: false,
+ isGroup: false,
+ },
+ ]);
+ await flush();
+
+ expect(qb.orIgnore).toHaveBeenCalled();
+ expect(execute).toHaveBeenCalled();
+ expect(messageRepository.save).not.toHaveBeenCalled(); // no longer the throwing path
+ });
+ });
});
// ── stop ──────────────────────────────────────────────────────────
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 31e6dcee0..e2dceda42 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -9,11 +9,13 @@ import {
} from '@nestjs/common';
import { InjectRepository, InjectDataSource } from '@nestjs/typeorm';
import { Repository, In, Not, IsNull, DataSource, FindManyOptions } from 'typeorm';
+import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { Session, SessionStatus } from './entities/session.entity';
import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';
import { CreateSessionDto } from './dto';
import { EngineFactory } from '../../engine/engine.factory';
import { paginate, ListOptions } from '../../common/utils/paginate';
+import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
import {
IWhatsAppEngine,
EngineStatus,
@@ -485,7 +487,15 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return row;
});
if (rows.length) {
- await this.messageRepository.save(rows);
+ // Insert-or-ignore: a live onMessage insert can land between the `seen` SELECT above and this
+ // write, colliding on UNIQUE(sessionId, waMessageId). orIgnore skips the collision instead of
+ // throwing and aborting the whole batch (history is best-effort, persist-never-dispatch).
+ await this.messageRepository
+ .createQueryBuilder()
+ .insert()
+ .values(rows as unknown as QueryDeepPartialEntity<Message>[])
+ .orIgnore()
+ .execute();
inserted += rows.length;
}
}
@@ -643,9 +653,24 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
});
- void this.messageRepository.save(dbMessage).catch(err => {
- this.logger.error(`Failed to save incoming message ${incoming.id} to database`, String(err));
- });
+ // De-duplicate at the source: the engine can re-fire `message` for one inbound message
+ // (#464). UNIQUE(sessionId, waMessageId) makes the insert the atomic dedup oracle — a
+ // near-simultaneous re-fire loses the race and is skipped here, so persist + webhook + WS
+ // happen exactly once. Fail-open: a non-conflict DB error still dispatches, so a real
+ // message is never dropped by a transient DB failure.
+ let isNewMessage = true;
+ try {
+ await this.messageRepository.insert(dbMessage as unknown as QueryDeepPartialEntity<Message>);
+ } catch (err) {
+ if (isUniqueConstraintError(err)) {
+ isNewMessage = false;
+ } else {
+ this.logger.error(`Failed to save incoming message ${incoming.id} to database`, String(err));
+ }
+ }
+ if (!isNewMessage) {
+ return; // duplicate re-fire — the original already persisted and dispatched
+ }
// Dispatch to webhooks with potentially modified message
void this.webhookService.dispatch(id, 'message.received', finalMessage);