From d377bde171c20d1d5b58f1d64131487ea197d40e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kau=C3=AA=20Costa?= Date: Wed, 14 Oct 2026 20:34:54 -0300 Subject: [PATCH 1/4] fix(chatwoot): find existing conversation by contact and inbox The contact conversations endpoint returns at most 20 conversations across all inboxes. When the same contact is present in more than 20 inboxes of an account (a WhatsApp group shared by many instances, or a person who talks to many of them), the conversation for the current inbox is often missing from that list, so createConversation opens a new one every time the cache expires. One group reached 14k open conversations, and contact updates that render all contact_inboxes started timing out in Chatwoot. Query the conversation filter by contact_id and inbox_id instead, in both createConversation and getOpenConversationByContact. Chatwoot versions whose filter does not accept contact_id answer 400/422; for those, fall back to the previous endpoint and remember it per Chatwoot URL. Co-Authored-By: Claude Opus 5.5 --- .../chatwoot/services/chatwoot.service.ts | 72 ++++++++++++++++--- 1 file changed, 63 insertions(+), 9 deletions(-) diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index c7a9753aa6..a92ef42981 100644 --- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -57,6 +57,9 @@ export class ChatwootService { private lidToPhoneMap: Map = new Map(); private readonly LID_CACHE_TTL_MS = 3600000; // 1 hora + // Chatwoot URLs whose conversation filter does not accept contact_id (versions before 2026-06) + private readonly contactFilterUnsupported = new Set(); + constructor( private readonly waMonitor: WAMonitoringService, private readonly configService: ConfigService, @@ -839,10 +842,7 @@ export class ChatwootService { const contactId = contact?.payload?.id || contact?.payload?.contact?.id || contact?.id; this.logger.verbose(`Contact ID: ${contactId}`); - const contactConversations = (await client.contacts.listConversations({ - accountId: this.provider.accountId, - id: contactId, - })) as any; + const contactConversations = await this.listContactConversationsInInbox(client, contactId, filterInbox.id); if (!contactConversations || !contactConversations.payload) { this.logger.error(`No conversations found or payload is undefined`); @@ -1013,6 +1013,63 @@ export class ChatwootService { return message; } + /** + * Lists the contact's conversations in a single inbox, most recent activity first. + * + * The contact conversations endpoint returns at most 20 conversations across all inboxes, + * so a contact present in more than 20 inboxes (e.g. a group shared by many instances) + * may not have its conversation for this inbox in the list, and a duplicate gets created. + * Filtering by contact_id and inbox_id avoids that. Chatwoot versions without the + * contact_id filter fall back to the old endpoint. + */ + private async listContactConversationsInInbox( + client: ChatwootClient, + contactId: number | string, + inboxId: number | string, + ): Promise<{ payload: any[] } | null> { + const providerUrl = this.provider.url; + + if (!this.contactFilterUnsupported.has(providerUrl)) { + try { + const filtered = (await client.conversations.filter({ + accountId: this.provider.accountId, + payload: [ + { + attribute_key: 'contact_id', + filter_operator: 'equal_to', + values: [Number(contactId)], + query_operator: 'and', + }, + { + attribute_key: 'inbox_id', + filter_operator: 'equal_to', + values: [Number(inboxId)], + }, + ] as any, + })) as any; + + if (filtered?.payload) { + return filtered; + } + } catch (error) { + const status = error?.status; + if (status === 400 || status === 422) { + this.logger.warn( + `Chatwoot at ${providerUrl} does not support filtering conversations by contact_id, using contact conversations endpoint`, + ); + this.contactFilterUnsupported.add(providerUrl); + } else { + this.logger.error(`Error filtering conversations by contact and inbox: ${error}`); + } + } + } + + return (await client.contacts.listConversations({ + accountId: this.provider.accountId, + id: Number(contactId), + })) as any; + } + public async getOpenConversationByContact( instance: InstanceDto, inbox: inbox, @@ -1025,13 +1082,10 @@ export class ChatwootService { return null; } - const conversations = (await client.contacts.listConversations({ - accountId: this.provider.accountId, - id: contact.id, - })) as any; + const conversations = await this.listContactConversationsInInbox(client, contact.id, inbox.id); return ( - conversations.payload.find( + conversations?.payload?.find( (conversation) => conversation.inbox_id === inbox.id && conversation.status === 'open', ) || undefined ); From e462ae41b21b87e1a710a217d166da37be26071e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kau=C3=AA=20Costa?= Date: Mon, 16 Nov 2026 19:28:46 -0300 Subject: [PATCH 2/4] perf(prisma): index Message by instanceId and chatwootMessageId The Chatwoot integration looks up messages by chatwootMessageId and instanceId on every outgoing message, reply, edit and delete. With only an instanceId index, each lookup scanned every message of the instance. On a 2.4M-row table this ran as parallel scans that exhausted Docker's default 64 MB /dev/shm ("could not resize shared memory segment"), failing the lookup. The migration holds a single statement so CONCURRENTLY works (Postgres only rejects it inside the implicit transaction of a multi-statement query), and IF NOT EXISTS makes it a no-op where the index was already created by hand. Co-Authored-By: Claude Opus 5.5 --- .../migration.sql | 3 +++ prisma/postgresql-schema.prisma | 1 + 2 files changed, 4 insertions(+) create mode 100644 prisma/postgresql-migrations/20261116230000_add_message_instance_chatwoot_message_index/migration.sql diff --git a/prisma/postgresql-migrations/20261116230000_add_message_instance_chatwoot_message_index/migration.sql b/prisma/postgresql-migrations/20261116230000_add_message_instance_chatwoot_message_index/migration.sql new file mode 100644 index 0000000000..234d60a247 --- /dev/null +++ b/prisma/postgresql-migrations/20261116230000_add_message_instance_chatwoot_message_index/migration.sql @@ -0,0 +1,3 @@ +-- Single statement on purpose: CREATE INDEX CONCURRENTLY cannot run inside the +-- implicit transaction Postgres opens for a multi-statement query. +CREATE INDEX CONCURRENTLY IF NOT EXISTS "Message_instanceId_chatwootMessageId_idx" ON "Message"("instanceId", "chatwootMessageId"); diff --git a/prisma/postgresql-schema.prisma b/prisma/postgresql-schema.prisma index 661a564c04..d4142c8d41 100644 --- a/prisma/postgresql-schema.prisma +++ b/prisma/postgresql-schema.prisma @@ -179,6 +179,7 @@ model Message { session IntegrationSession? @relation(fields: [sessionId], references: [id]) @@index([instanceId]) + @@index([instanceId, chatwootMessageId]) } model MessageUpdate { From 85a0fddda3bb11d48a3c606b5b758612c3555c2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kau=C3=AA=20Costa?= Date: Mon, 16 Nov 2026 20:38:48 -0300 Subject: [PATCH 3/4] perf(prisma): index Message by instanceId and key id Looking up a received message by its WhatsApp id (key->>'id') scanned every message of the instance. We need this lookup to mark messages as read with their real remoteJid, which is now usually an @lid address rather than the phone JID. The migration holds a single statement so CONCURRENTLY works, and IF NOT EXISTS makes it a no-op where the index was already created by hand. Prisma cannot express an index on a JSON expression, so the schema has no @@index for it: if `prisma migrate dev` ever proposes dropping "Message_instanceId_keyId_idx", remove that statement from the generated migration. Co-Authored-By: Claude Opus 5.5 --- .../migration.sql | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 prisma/postgresql-migrations/20261116233000_add_message_instance_key_id_index/migration.sql diff --git a/prisma/postgresql-migrations/20261116233000_add_message_instance_key_id_index/migration.sql b/prisma/postgresql-migrations/20261116233000_add_message_instance_key_id_index/migration.sql new file mode 100644 index 0000000000..bfe2979304 --- /dev/null +++ b/prisma/postgresql-migrations/20261116233000_add_message_instance_key_id_index/migration.sql @@ -0,0 +1,4 @@ +-- Single statement on purpose: CREATE INDEX CONCURRENTLY cannot run inside the +-- implicit transaction Postgres opens for a multi-statement query. +-- Expression index, not representable in the Prisma schema. +CREATE INDEX CONCURRENTLY IF NOT EXISTS "Message_instanceId_keyId_idx" ON "Message"("instanceId", (("key"->>'id'))); From f071e87a0bac7c982260ac6804b0d0e5cbcdd5a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kau=C3=AA=20Costa?= Date: Tue, 1 Dec 2026 16:41:33 -0300 Subject: [PATCH 4/4] perf(prisma): index Message by instanceId and remoteJid The unread count and the read-status update per chat filter Message by instanceId and key->>'remoteJid'. Without an index they scanned the whole table (2.8M rows, 4.8 GB) and kept the database CPU at 160%, slowing Chatwoot down. Already created in production on 2026-12-01. Co-Authored-By: Claude Opus 5.5 --- .../migration.sql | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 prisma/postgresql-migrations/20261201190000_add_message_instance_remote_jid_index/migration.sql diff --git a/prisma/postgresql-migrations/20261201190000_add_message_instance_remote_jid_index/migration.sql b/prisma/postgresql-migrations/20261201190000_add_message_instance_remote_jid_index/migration.sql new file mode 100644 index 0000000000..024f8e562d --- /dev/null +++ b/prisma/postgresql-migrations/20261201190000_add_message_instance_remote_jid_index/migration.sql @@ -0,0 +1,6 @@ +-- Single statement on purpose: CREATE INDEX CONCURRENTLY cannot run inside the +-- implicit transaction Postgres opens for a multi-statement query. +-- Expression index, not representable in the Prisma schema. +-- Serves the unread count and the read-status update per chat, which filter by +-- instanceId and key->>'remoteJid' and were scanning the whole table. +CREATE INDEX CONCURRENTLY IF NOT EXISTS "Message_instanceId_remoteJid_idx" ON "Message"("instanceId", (("key"->>'remoteJid')));