{{ message }}
Fix Chatwoot DB Connection Instability and Implement Stale Conversation Cache Handling#2017
Merged
DavidsonGomes merged 4 commits intoEvolutionAPI:developfrom Sep 26, 2025
Conversation
…ento de mensagens - Alterado método de obtenção da conexão PostgreSQL para ser assíncrono, melhorando a gestão de conexões. - Implementada lógica de retry para criação de mensagens e conversas, garantindo maior robustez em caso de falhas. - Ajustadas chamadas de consulta ao banco de dados para utilizar a nova abordagem de conexão. - Adicionada nova propriedade `messageBodyForRetry` para facilitar o reenvio de mensagens em caso de erro.
Contributor
Contributor
There was a problem hiding this comment.
Hey there - I've reviewed your changes - here's some feedback:
- Consider abstracting the retry logic for stale-conversation handling into a shared helper to reduce duplication between createMessage and sendData.
- Instead of calling getPgClient() for every query, acquire the client once per operation and reuse it to minimize overhead and simplify the code paths.
- Relying on error.toString().toLowerCase() to detect 404s can be brittle—use AxiosError.response.status or error.isAxiosError to more reliably handle HTTP status codes.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider abstracting the retry logic for stale-conversation handling into a shared helper to reduce duplication between createMessage and sendData.
- Instead of calling getPgClient() for every query, acquire the client once per operation and reuse it to minimize overhead and simplify the code paths.
- Relying on error.toString().toLowerCase() to detect 404s can be brittle—use AxiosError.response.status or error.isAxiosError to more reliably handle HTTP status codes.
## Individual Comments
### Comment 1
<location> `src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts:919` </location>
<code_context>
const remoteJid = bodyForRetry.key.remoteJid;
</code_context>
<issue_to_address>
**suggestion (code-quality):** Prefer object destructuring when accessing and using properties. ([`use-object-destructuring`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/TypeScript/Default-Rules/use-object-destructuring))
```suggestion
const {remoteJid} = bodyForRetry.key;
```
<br/><details><summary>Explanation</summary>Object destructuring can often remove an unnecessary temporary reference, as well as making your code more succinct.
From the [Airbnb Javascript Style Guide](https://airbnb.io/javascript/#destructuring--object)
</details>
</issue_to_address>
### Comment 2
<location> `src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts:1101` </location>
<code_context>
const remoteJid = bodyForRetry.key.remoteJid;
</code_context>
<issue_to_address>
**suggestion (code-quality):** Prefer object destructuring when accessing and using properties. ([`use-object-destructuring`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/TypeScript/Default-Rules/use-object-destructuring))
```suggestion
const {remoteJid} = bodyForRetry.key;
```
<br/><details><summary>Explanation</summary>Object destructuring can often remove an unnecessary temporary reference, as well as making your code more succinct.
From the [Airbnb Javascript Style Guide](https://airbnb.io/javascript/#destructuring--object)
</details>
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
…e.ts aplicação de desestruturação de objetos que é uma boa prática do ts Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
…e.ts aplicação de desestruturação de objetos que é uma boa prática do ts Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
- Implementada a função `handleStaleConversationError` para centralizar a lógica de tratamento de erros relacionados a conversas não encontradas. - A lógica de retry foi aprimorada para as funções `createMessage` e `sendData`, garantindo que as operações sejam reprocessadas corretamente em caso de falhas. - Removido código duplicado e melhorada a legibilidade do serviço Chatwoot.
Contributor
|
@Vitordotpy what issues are you experiencing because of this bug? I'm having issue where certain instances won't send messages to Chatwoot, but Chatwoot can send messages to Whatsapp. Wondering if this is related to it and solves it. |
Contributor
Author
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

This pull request addresses two critical issues in the Chatwoot integration to improve its reliability and resilience. It introduces on-demand database connections to prevent intermittent connection failures and implements a retry mechanism to handle stale conversation data cached in Redis.
Fixes:
ChatwootServiceto initialize the PostgreSQL client on-demand (getPgClient) rather than at service instantiation. This resolves a race condition where the client could be created with an incorrect or default database connection string, causing sporadicdatabase does not existerrors.try-catchmechanism within thecreateMessageandsendDatamethods. When a404 Not Founderror is received from the Chatwoot API (indicating a stale conversation ID in the Redis cache), the system now automatically:Enhancements:
Summary
This PR resolves critical stability issues in the Chatwoot integration by implementing on-demand database connections to fix intermittent connection errors and adding a retry mechanism that automatically handles stale conversation IDs from the Redis cache, ensuring more reliable message delivery.
Summary by Sourcery
Fix intermittent database connection errors and add automatic retry handling for stale Chatwoot conversation IDs by lazily initializing the Postgres client and evicting and recreating conversations on 404 errors.
Bug Fixes:
Enhancements: