iachat/spec/services
Shivam Mishra 39243b9e71
fix: duplicate message_created webhooks for WhatsApp messages (#13523)
Some customers using WhatsApp inboxes with account-level webhooks were
reporting receiving duplicate `message_created` webhook deliveries for
every incoming message. Upon inspection, here's what we found

- Both payloads are identical.
- No errors appear in the application logs
- Webhook URL is only configured in one place. 

This meant, the system was sending the webhooks twice. For some context,
there's a know related issue... Meta's WhatsApp Business API can deliver
the same webhook notification multiple times for a single message. The
codebase already acknowledges this — there's a comment in
`IncomingMessageBaseService#process_messages` noting that "multiple
webhook events can be received against the same message due to
misconfigurations in the Meta business manager account." A deduplication
guard exists, but it doesn't actually work under concurrency.

### Rationale

The existing dedup was a three-step sequence: check Redis (`GET`), check
the database, then set a Redis flag (`SETEX`). Two Sidekiq workers
processing duplicate Meta webhooks simultaneously would both complete
the `GET` before either executed the `SETEX`, so both would proceed to
create a message. The `source_id` column has a non-unique index, so the
database wouldn't catch the duplicate either. Each message then
independently fires `after_create_commit`, dispatching two
`message_created` webhook events to the customer.

```
             Worker A                          Worker B
                │                                 │
                ▼                                 ▼
        Redis GET key ──► nil               Redis GET key ──► nil
                │                                 │
                │    ◄── both pass guard ──►      │
                │                                 │
                ▼                                 ▼
        Redis SETEX key                    Redis SETEX key
                │                                 │
                ▼                                 ▼
        BEGIN transaction               BEGIN transaction
        INSERT message                   INSERT message
        DELETE Redis key ◄─┐                      │
        COMMIT             │             DELETE Redis key
                           │             COMMIT
                           │                      │
                           └── key gone before ───┘
                              B's commit lands

                ▼                                 ▼
        after_create_commit              after_create_commit
        dispatch MESSAGE_CREATED         dispatch MESSAGE_CREATED
                │                                 │
                ▼                                 ▼
        WebhookJob ──► n8n               WebhookJob ──► n8n
                    (duplicate!)
```

There was a second, subtler problem visible in the diagram: the Redis
key was cleared *inside* the database transaction, before the
transaction committed. This opened a window where neither the Redis
check nor the database check would see the in-flight message.

The fix collapses the check-and-set into a single `SET NX EX` call,
which is atomic in Redis. The key is no longer eagerly cleared — it
expires naturally after 24 hours. The database lookup
(`find_message_by_source_id`) remains as a fallback for messages that
were created before the lock expired.

```
             Worker A                          Worker B
                │                                 │
                ▼                                 ▼
        Redis SET NX ──► OK              Redis SET NX ──► nil
                │                                 │
                ▼                                 ▼
        proceeds to create              returns early
        message normally                (lock already held)
```

### Implementation Notes

The lock logic is extracted into `Whatsapp::MessageDedupLock`, a small
class that wraps a single `Redis SET NX EX` call. This makes the
concurrency guarantee testable in isolation — the spec uses a
`CyclicBarrier` to race two threads against the same key and asserts
exactly one wins, without needing database writes,
`use_transactional_tests = false`, or monkey-patching.

Because the Redis lock now persists (instead of being cleared
mid-transaction), existing WhatsApp specs needed an `after` hook to
clean up `MESSAGE_SOURCE_KEY::*` keys between examples. Transactional
fixtures only roll back the database, not Redis.
2026-02-17 14:01:10 +05:30
..
account Revert "chore: Upgrade Rails to 7.2.2 and update Gemfile dependencies (#11037)" 2026-02-03 21:09:42 -08:00
auto_assignment fix: Enforce team boundaries to prevent cross-team assignments (#13353) 2026-02-16 14:39:20 +05:30
automation_rules fix: country_code should be checked against the contact (#13186) 2026-01-13 14:47:27 +05:30
contacts feat: Bulk delete for contacts (#12778) 2025-11-04 17:47:53 -08:00
conversations feat: APIs to assign agents_bots as assignee in conversations (#12836) 2025-11-18 18:20:58 -08:00
crm/leadsquared test(leadsquared): make ApiError specs reload-safe (#13098) 2025-12-17 13:30:34 -08:00
email chore: Migrate mailers from the worker to jobs (#12331) 2025-10-21 16:36:37 -07:00
facebook feat: Add message support for input_select type in Facebook (#11627) 2025-06-10 16:15:11 +05:30
google feat: add Google Email fetch and OAuth token refresh service (#9603) 2024-06-11 14:22:03 +05:30
imap feat: Add configurable interval for IMAP sync (#9302) 2024-04-25 18:58:20 -07:00
instagram feat: Handle instagram test service (#11244) 2025-04-11 19:11:29 +05:30
internal feat: add job to remove stale contacts and contact_inboxes (#11186) 2025-03-28 12:18:39 +05:30
labels fix: Update associations when a label is updated (#3046) 2021-09-21 10:16:32 +05:30
line fix: Ensure messages go to correct conversation when receive multi user in 1 LINE webhook (#12322) 2025-09-22 17:05:25 +05:30
linear feat: Whatsapp embedded signup (#11612) 2025-07-14 21:37:06 -07:00
liquid feat: Add liquid processing for SMS campaigns (#10981) 2025-06-11 13:16:44 -04:00
llm_formatter feat: Differentiate bot and user in the summary (#12801) 2025-11-05 11:42:21 -08:00
macros feat: Add webhook event support for macros (#11235) 2025-04-02 20:26:55 -07:00
mailbox refactor: strategy pattern for mailbox conversation finding (#12766) 2025-11-10 20:47:18 +05:30
message_templates fix: Captain not responding to campaign conversations (#13489) 2026-02-12 10:07:56 +05:30
messages feat: add per-account daily rate limit for outbound emails (#13411) 2026-02-03 02:06:51 +05:30
mfa feat: MFA (#12290) 2025-09-18 20:19:24 +05:30
microsoft chore: Refactor RefreshOauthTokenService to improve readability (#8820) 2024-01-31 12:24:12 +04:00
notification chore: Disable email notifications for unconfirmed users (#10964) 2025-02-24 12:14:40 -08:00
sms fix: Error shouldn't halt the campaign for entire audience (#11980) 2025-08-11 12:03:48 +05:30
telegram Revert "chore: Upgrade Rails to 7.2.2 and update Gemfile dependencies (#11037)" 2026-02-03 21:09:42 -08:00
tiktok feat: TikTok channel (#12741) 2025-12-17 07:54:50 -08:00
twilio feat: Add support for sending CSAT surveys via templates (Whatsapp Twilio) (#13143) 2026-01-13 16:32:02 +04:00
twitter chore: Enable the new Rubocop rules (#7122) 2023-05-19 14:37:10 +05:30
whatsapp fix: duplicate message_created webhooks for WhatsApp messages (#13523) 2026-02-17 14:01:10 +05:30
widget feat: speed up circleci and github actions (#12849) 2025-11-19 15:32:48 +05:30
account_deletion_service_spec.rb fix(account-deletion): normalize deleted email suffix and handle collisions safely (#13472) 2026-02-07 17:29:27 -08:00
action_service_spec.rb chore: Add open conversation option (#11828) 2025-07-02 10:01:50 +05:30
base_token_service_spec.rb feat: MFA (#12290) 2025-09-18 20:19:24 +05:30
csat_survey_service_spec.rb fix: Respect survey label rules for WhatsApp CSAT template (#13285) 2026-01-15 22:16:00 -08:00
search_service_spec.rb feat: Advanced Search Backend (#12917) 2026-01-07 15:30:49 +05:30