Skip to content

Conversation

@andres99x
Copy link
Contributor

@andres99x andres99x commented Sep 3, 2025

Bug Fix: Prevent Duplicate Cron Jobs for Chatwoot Message Sync

Problem: Multiple instances of the same cron job were being created when the syncChatwootLostMessages() method was called repeatedly, leading to duplicate message syncing operations.

Solution: Implemented a unique identifier system using cuid() to ensure only one active cron job per instance:

  1. Generate unique ID: Each cron job gets a unique cronId when created
  2. Store in cache: The ID is stored in Redis cache with key chatwoot:syncLostMessages and instance name
  3. ID validation: Before executing sync, the cron job checks if its ID matches the stored ID
  4. Skip duplicates: If IDs don't match, the job skips execution, preventing duplicate syncing

This ensures that even if multiple cron jobs are accidentally created, only the most recent one will actually execute the sync operation.

Summary by Sourcery

Prevent duplicate cron jobs for Chatwoot message syncing by assigning each job a unique ID stored in Redis and validating it before execution.

Bug Fixes:

  • Generate a unique ID (cuid) for each cron task and store it in a Redis hash keyed by instance to track the latest job.
  • Check the stored ID against the job’s own ID on each run and skip execution if they don’t match to avoid duplicate sync operations.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Sep 3, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Enhances the Chatwoot message sync cron job by assigning a unique identifier via cuid(), caching it in Redis, and validating this identifier at execution time to ensure only the most recent job runs.

Sequence diagram for Chatwoot message sync cron job execution with duplicate prevention

sequenceDiagram
    participant BaileysStartupService
    participant RedisCache
    participant CronJob
    participant ChatwootService

    BaileysStartupService->>RedisCache: hSet(cronKey, instanceName, cronId)
    BaileysStartupService->>CronJob: schedule sync task
    loop On cron job trigger
        CronJob->>RedisCache: hGet(cronKey, instanceName)
        alt If storedId == cronId
            CronJob->>ChatwootService: syncLostMessages()
        else If storedId != cronId
            CronJob-->>CronJob: Skip execution
        end
    end
Loading

Class diagram for BaileysStartupService and ChatwootService changes

classDiagram
    class BaileysStartupService {
        +instance: Instance
        +chatwootService: ChatwootService
        +startChatwootSyncCron()
    }
    class ChatwootService {
        +getCache()
        +syncLostMessages(options, config, prepare)
    }
    class RedisCache {
        +hSet(key, field, value)
        +hGet(key, field)
    }
    BaileysStartupService --> ChatwootService
    ChatwootService --> RedisCache
Loading

File-Level Changes

Change Details Files
Unique cron job identification
  • Generate a unique cronId using cuid() for each job
  • Store cronId in Redis hash under key chatwoot:syncLostMessages with instance name
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Cron execution guarded by ID validation
  • Retrieve Redis cache instance before job runs
  • Fetch storedId from cache and compare with cronId
  • Skip execution if storedId does not match cronId
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
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 setting an expiration/TTL on the Redis hash entries to avoid stale cronIds accumulating if instances are removed or renamed.
  • It may be more robust to explicitly stop or destroy existing cron tasks on startup rather than only relying on the Redis ID check to prevent overlapping jobs.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider setting an expiration/TTL on the Redis hash entries to avoid stale cronIds accumulating if instances are removed or renamed.
- It may be more robust to explicitly stop or destroy existing cron tasks on startup rather than only relying on the Redis ID check to prevent overlapping jobs.

## Individual Comments

### Comment 1
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:4368` </location>
<code_context>
       const task = cron.schedule('0,30 * * * *', async () => {
+        // Check ID before executing (only if cache is available)
+        const cache = this.chatwootService.getCache();
+        if (cache) {
+          const storedId = await cache.hGet(cronKey, this.instance.name);
+          if (storedId && storedId !== cronId) return;
+        }
         this.chatwootService.syncLostMessages({ instanceName: this.instance.name }, chatwootConfig, prepare);
</code_context>

<issue_to_address>
Returning early in the cron task may mask underlying issues.

Adding a log statement when the task is skipped due to ID mismatch will help with future debugging and monitoring.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        if (cache) {
          const storedId = await cache.hGet(cronKey, this.instance.name);
          if (storedId && storedId !== cronId) return;
        }
=======
        if (cache) {
          const storedId = await cache.hGet(cronKey, this.instance.name);
          if (storedId && storedId !== cronId) {
            this.logger?.info?.(
              `[ChatwootSyncLostMessages] Skipping cron task for instance "${this.instance.name}" due to ID mismatch (storedId: ${storedId}, cronId: ${cronId})`
            );
            return;
          }
        }
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:4362` </location>
<code_context>

+      // Generate ID for this cron task and store in cache
+      const cronId = cuid();
+      const cronKey = `chatwoot:syncLostMessages`;
+      await this.chatwootService.getCache()?.hSet(cronKey, this.instance.name, cronId);
+
</code_context>

<issue_to_address>
Cron key does not include instance name, which may cause collisions.

Since cronKey is a static value, using the same cache across multiple environments or services could result in key collisions. To prevent this, add environment or service-specific identifiers to cronKey.

Suggested implementation:

```typescript
      const env = process.env.NODE_ENV || 'development';
      const cronKey = `chatwoot:syncLostMessages:${env}:${this.instance.name}`;
      await this.chatwootService.getCache()?.hSet(cronKey, this.instance.name, cronId);

```

```typescript
        if (cache) {
          const env = process.env.NODE_ENV || 'development';
          const cronKey = `chatwoot:syncLostMessages:${env}:${this.instance.name}`;
          const storedId = await cache.hGet(cronKey, this.instance.name);

```
</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 on lines 4368 to 4371
if (cache) {
const storedId = await cache.hGet(cronKey, this.instance.name);
if (storedId && storedId !== cronId) return;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion: Returning early in the cron task may mask underlying issues.

Adding a log statement when the task is skipped due to ID mismatch will help with future debugging and monitoring.

Suggested change
if (cache) {
const storedId = await cache.hGet(cronKey, this.instance.name);
if (storedId && storedId !== cronId) return;
}
if (cache) {
const storedId = await cache.hGet(cronKey, this.instance.name);
if (storedId && storedId !== cronId) {
this.logger?.info?.(
`[ChatwootSyncLostMessages] Skipping cron task for instance "${this.instance.name}" due to ID mismatch (storedId: ${storedId}, cronId: ${cronId})`
);
return;
}
}

@andres99x andres99x changed the title Prevent Duplicate Cron Jobs for Chatwoot Message Sync fix: Prevent Duplicate Cron Jobs for Chatwoot Message Sync Sep 3, 2025
@DavidsonGomes DavidsonGomes changed the base branch from main to develop September 3, 2025 21:28
@andres99x andres99x force-pushed the enhancmenet/check-chatwoot-cron-id branch from 7c9f4f9 to 613d486 Compare September 4, 2025 12:04
@DavidsonGomes DavidsonGomes merged commit d9c04fc into EvolutionAPI:develop Sep 9, 2025
1 check 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.

2 participants