Fix Chatwoot DB Connection Instability and Implement Stale Conversation Cache Handling by Vitordotpy · Pull Request #2017 · EvolutionAPI/evolution-api · GitHub
Skip to content

Fix Chatwoot DB Connection Instability and Implement Stale Conversation Cache Handling#2017

Merged
DavidsonGomes merged 4 commits intoEvolutionAPI:developfrom
Vitordotpy:fix/enhanced-chatwoot-database-connection
Sep 26, 2025
Merged

Fix Chatwoot DB Connection Instability and Implement Stale Conversation Cache Handling#2017
DavidsonGomes merged 4 commits intoEvolutionAPI:developfrom
Vitordotpy:fix/enhanced-chatwoot-database-connection

Conversation

@Vitordotpy
Copy link
Copy Markdown
Contributor

@Vitordotpy Vitordotpy commented Sep 25, 2025

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:

  • Prevent Intermittent DB Connection Errors: Refactored the ChatwootService to 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 sporadic database does not exist errors.
  • Handle Stale Conversation Cache: Implemented a try-catch mechanism within the createMessage and sendData methods. When a 404 Not Found error is received from the Chatwoot API (indicating a stale conversation ID in the Redis cache), the system now automatically:
    1. Deletes the invalid conversation entry from Redis.
    2. Creates a new conversation in Chatwoot.
    3. Retries the original message-sending operation with the new, valid conversation ID.

Enhancements:

  • Increased Resilience: The integration is now more robust against temporary inconsistencies between the Redis cache and the Chatwoot database state, preventing message delivery failures.
  • Improved Stability: Lazily initializing the database connection ensures that the correct, instance-specific credentials are used for every operation, eliminating a significant source of production errors.

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:

  • Prevent intermittent 'database does not exist' errors by initializing the PostgreSQL client on-demand.

Enhancements:

  • Automatically detect and recover from stale Chatwoot conversation IDs by evicting the Redis cache entry, creating a new conversation, and retrying message operations.

…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.
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Sep 25, 2025

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts Outdated
Comment thread src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts Outdated
Vitordotpy and others added 3 commits September 25, 2025 17:30
…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.
@andres99x
Copy link
Copy Markdown
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.

@Vitordotpy
Copy link
Copy Markdown
Contributor Author

@DavidsonGomes DavidsonGomes merged commit bd0c43f into EvolutionAPI:develop Sep 26, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants