Skip to content

Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬

fix(whatsapp): recover stalled campaigns without repeating sends (#16281)

Muhsin Keloth9499b695380e
diff --git a/app/jobs/campaigns/send_whatsapp_batch_job.rb b/app/jobs/campaigns/send_whatsapp_batch_job.rb
index bbaf3ff7931..2dd8a081f40 100644
--- a/app/jobs/campaigns/send_whatsapp_batch_job.rb
+++ b/app/jobs/campaigns/send_whatsapp_batch_job.rb
@@ -1,7 +1,18 @@
class Campaigns::SendWhatsappBatchJob < ApplicationJob
queue_as :low
+ LOCK_TIMEOUT = 15.minutes
+
def perform(campaign, cursor = 0)
+ key = format(Redis::Alfred::WHATSAPP_CAMPAIGN_MUTEX, campaign_id: campaign.id)
+ Redis::LockManager.new.with_lock(key, LOCK_TIMEOUT) do
+ send_batch(campaign.reload, cursor)
+ end
+ end
+
+ private
+
+ def send_batch(campaign, cursor)
return if campaign.completed?
next_cursor = Whatsapp::OneoffCampaignService.new(campaign: campaign).perform_batch(cursor)
diff --git a/db/migrate/20261016080629_add_whatsapp_campaign_recovery.rb b/db/migrate/20261016080629_add_whatsapp_campaign_recovery.rb
new file mode 100644
index 00000000000..c4d70939cef
--- /dev/null
+++ b/db/migrate/20261016080629_add_whatsapp_campaign_recovery.rb
@@ -0,0 +1,6 @@
+class AddWhatsappCampaignRecovery < ActiveRecord::Migration[7.1]
+ def change
+ add_column :campaigns, :whatsapp_cursor, :bigint
+ add_column :campaign_recipients, :send_attempted_at, :datetime
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 6a3d3c0815f..0536acb1861 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -369,6 +369,7 @@ ActiveRecord::Schema[7.1].define(version: 2026_10_19_143116) do
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "contact_inbox_id"
+ t.datetime "send_attempted_at"
t.index ["account_id", "campaign_id"], name: "index_campaign_recipients_on_account_id_and_campaign_id"
t.index ["account_id"], name: "index_campaign_recipients_on_account_id"
t.index ["campaign_id", "contact_id"], name: "index_campaign_recipients_on_campaign_id_and_contact_id", unique: true
@@ -400,6 +401,7 @@ ActiveRecord::Schema[7.1].define(version: 2026_10_19_143116) do
t.jsonb "template_params"
t.datetime "started_at"
t.datetime "completed_at"
+ t.bigint "whatsapp_cursor"
t.index ["account_id"], name: "index_campaigns_on_account_id"
t.index ["campaign_status"], name: "index_campaigns_on_campaign_status"
t.index ["campaign_type"], name: "index_campaigns_on_campaign_type"
diff --git a/enterprise/app/jobs/campaigns/recover_whatsapp_campaigns_job.rb b/enterprise/app/jobs/campaigns/recover_whatsapp_campaigns_job.rb
new file mode 100644
index 00000000000..12630ac471e
--- /dev/null
+++ b/enterprise/app/jobs/campaigns/recover_whatsapp_campaigns_job.rb
@@ -0,0 +1,12 @@
+class Campaigns::RecoverWhatsappCampaignsJob < ApplicationJob
+ queue_as :scheduled_jobs
+
+ STALE_AFTER = 15.minutes
+
+ def perform
+ Campaign.processing.where(campaign_type: :one_off).where.not(whatsapp_cursor: nil)
+ .where(updated_at: ...STALE_AFTER.ago).find_each do |campaign|
+ Campaigns::SendWhatsappBatchJob.perform_later(campaign, campaign.whatsapp_cursor)
+ end
+ end
+end
diff --git a/enterprise/app/jobs/enterprise/trigger_scheduled_items_job.rb b/enterprise/app/jobs/enterprise/trigger_scheduled_items_job.rb
index 452a89a92ca..177a8f1db1b 100644
--- a/enterprise/app/jobs/enterprise/trigger_scheduled_items_job.rb
+++ b/enterprise/app/jobs/enterprise/trigger_scheduled_items_job.rb
@@ -5,6 +5,8 @@ module Enterprise::TriggerScheduledItemsJob
## Triggers Enterprise specific jobs
####################################
+ Campaigns::RecoverWhatsappCampaignsJob.perform_later
+
# Triggers Account Sla jobs
Sla::TriggerSlasForAccountsJob.perform_later
end
diff --git a/enterprise/app/models/enterprise/campaign.rb b/enterprise/app/models/enterprise/campaign.rb
index ab85d9931ba..aa09c3b5db6 100644
--- a/enterprise/app/models/enterprise/campaign.rb
+++ b/enterprise/app/models/enterprise/campaign.rb
@@ -3,5 +3,19 @@ module Enterprise::Campaign
included do
has_many :campaign_recipients, dependent: :delete_all
+ before_update :initialize_whatsapp_cursor, if: :starting_whatsapp_campaign?
+ end
+
+ private
+
+ def starting_whatsapp_campaign?
+ return false unless will_save_change_to_campaign_status? && processing? && one_off?
+
+ inbox.inbox_type == 'Whatsapp' && inbox.channel.provider == 'whatsapp_cloud'
+ end
+
+ def initialize_whatsapp_cursor
+ # Commit recovery eligibility in the same update as the transition to Processing.
+ self.whatsapp_cursor ||= 0
end
end
diff --git a/enterprise/app/services/enterprise/whatsapp/oneoff_campaign_service.rb b/enterprise/app/services/enterprise/whatsapp/oneoff_campaign_service.rb
index 5dddb0eb9bf..d58ecc6b6a4 100644
--- a/enterprise/app/services/enterprise/whatsapp/oneoff_campaign_service.rb
+++ b/enterprise/app/services/enterprise/whatsapp/oneoff_campaign_service.rb
@@ -1,10 +1,26 @@
module Enterprise::Whatsapp::OneoffCampaignService
+ def perform_batch(cursor)
+ next_cursor = super(campaign.whatsapp_cursor || cursor)
+ if next_cursor && campaign.whatsapp_cursor.present?
+ campaign.with_lock do
+ campaign.update!(whatsapp_cursor: next_cursor) if !campaign.completed? && next_cursor > campaign.whatsapp_cursor
+ end
+ end
+ next_cursor
+ end
+
private
def process_contacts(contacts)
contacts.each do |contact|
recipient = recipient_for(contact)
- process_recipient(recipient) if recipient.queued?
+ unless recipient.previously_new_record?
+ recipient.update!(error_message: 'Send outcome unknown after interruption; review before retrying') if recipient.queued?
+ next
+ end
+
+ campaign.update!(updated_at: Time.current) if campaign.whatsapp_cursor.present?
+ process_recipient(recipient)
end
end
@@ -12,6 +28,8 @@ module Enterprise::Whatsapp::OneoffCampaignService
campaign.campaign_recipients.find_or_create_by!(contact: contact) do |recipient|
recipient.account = campaign.account
recipient.inbox = campaign.inbox
+ # The unique recipient insert is the send claim, committed before contacting WhatsApp.
+ recipient.send_attempted_at = Time.current
end
end
diff --git a/lib/redis/redis_keys.rb b/lib/redis/redis_keys.rb
index 670f4fa94e4..7e0037e7b91 100644
--- a/lib/redis/redis_keys.rb
+++ b/lib/redis/redis_keys.rb
@@ -88,6 +88,7 @@ module Redis::RedisKeys
SLACK_MESSAGE_MUTEX = 'SLACK_MESSAGE_LOCK::%<conversation_id>s::%<reference_id>s'.freeze
EMAIL_MESSAGE_MUTEX = 'EMAIL_CHANNEL_LOCK::%<inbox_id>s'.freeze
WHATSAPP_MESSAGE_MUTEX = 'WHATSAPP_MESSAGE_CREATE_LOCK::%<inbox_id>s::%<sender_id>s'.freeze
+ WHATSAPP_CAMPAIGN_MUTEX = 'WHATSAPP_CAMPAIGN_LOCK::%<campaign_id>s'.freeze
CRM_PROCESS_MUTEX = 'CRM_PROCESS_MUTEX::%<hook_id>s'.freeze
CAPTAIN_DOCUMENT_SYNC_MUTEX = 'CAPTAIN_DOCUMENT_SYNC_LOCK::%<document_id>s'.freeze
CAPTAIN_CONVERSATION_FAQ_MUTEX = 'CAPTAIN_CONVERSATION_FAQ_LOCK::%<assistant_id>s::%<language>s'.freeze
diff --git a/spec/enterprise/jobs/campaigns/recover_whatsapp_campaigns_job_spec.rb b/spec/enterprise/jobs/campaigns/recover_whatsapp_campaigns_job_spec.rb
new file mode 100644
index 00000000000..2f2cad5d6f1
--- /dev/null
+++ b/spec/enterprise/jobs/campaigns/recover_whatsapp_campaigns_job_spec.rb
@@ -0,0 +1,53 @@
+require 'rails_helper'
+
+RSpec.describe Campaigns::RecoverWhatsappCampaignsJob do
+ let(:account) { create(:account) }
+ let(:channel) do
+ create(:channel_whatsapp, account: account, provider: 'whatsapp_cloud', validate_provider_config: false, sync_templates: false)
+ end
+ let(:campaign) { create(:campaign, account: account, inbox: channel.inbox) }
+
+ it 'recovers a stale processing campaign at its saved checkpoint' do
+ campaign.processing!
+ campaign.update!(whatsapp_cursor: 123, updated_at: 16.minutes.ago)
+
+ expect { described_class.perform_now }
+ .to have_enqueued_job(Campaigns::SendWhatsappBatchJob).with(campaign, 123)
+ end
+
+ it 'does not restart a campaign that is making progress' do
+ campaign.processing!
+
+ expect { described_class.perform_now }.not_to have_enqueued_job(Campaigns::SendWhatsappBatchJob)
+ end
+
+ it 'does not automatically restart historical campaigns without a checkpoint' do
+ campaign.processing!
+ campaign.update!(whatsapp_cursor: nil, updated_at: 16.minutes.ago)
+
+ expect { described_class.perform_now }.not_to have_enqueued_job(Campaigns::SendWhatsappBatchJob)
+ end
+
+ it 'does not restart completed campaigns' do
+ campaign.processing!
+ campaign.completed!
+ travel 16.minutes do
+ expect { described_class.perform_now }.not_to have_enqueued_job(Campaigns::SendWhatsappBatchJob)
+ end
+ end
+
+ it 'does not enable WhatsApp recovery for SMS campaigns' do
+ sms = create(:channel_sms, account: account)
+ campaign = create(:campaign, account: account, inbox: sms.inbox)
+ campaign.processing!
+
+ expect(campaign.reload.whatsapp_cursor).to be_nil
+ end
+
+ it 'does not enable recovery for unsupported WhatsApp providers' do
+ channel.update!(provider: 'default')
+ campaign.processing!
+
+ expect(campaign.reload.whatsapp_cursor).to be_nil
+ end
+end
diff --git a/spec/enterprise/services/enterprise/whatsapp/oneoff_campaign_service_spec.rb b/spec/enterprise/services/enterprise/whatsapp/oneoff_campaign_service_spec.rb
index f342b3300be..568bc066284 100644
--- a/spec/enterprise/services/enterprise/whatsapp/oneoff_campaign_service_spec.rb
+++ b/spec/enterprise/services/enterprise/whatsapp/oneoff_campaign_service_spec.rb
@@ -137,4 +137,142 @@ RSpec.describe Enterprise::Whatsapp::OneoffCampaignService do
expect(CampaignRecipient.find_by!(campaign: campaign, contact: contact)).to be_skipped
end
+
+ describe 'interrupted campaign recovery' do
+ let(:service) { Whatsapp::OneoffCampaignService.new(campaign: campaign) }
+
+ it 'commits recovery eligibility before executing the campaign' do
+ allow(campaign).to receive(:execute_campaign).and_raise(Interrupt, 'worker terminated before enqueue')
+
+ expect { campaign.trigger! }.to raise_error(Interrupt, 'worker terminated before enqueue')
+ expect(campaign.reload).to have_attributes(campaign_status: 'processing', whatsapp_cursor: 0)
+ campaign.update!(updated_at: 16.minutes.ago)
+
+ expect { Campaigns::RecoverWhatsappCampaignsJob.perform_now }
+ .to have_enqueued_job(Campaigns::SendWhatsappBatchJob).with(campaign, 0)
+ end
+
+ it 'does not repeat an accepted send when the response is lost and continues untouched contacts' do
+ stub_const('Whatsapp::OneoffCampaignService::BATCH_SIZE', 2)
+ contacts = create_list(:contact, 3, :with_phone_number, account: account)
+ contacts.each { |contact| contact.update_labels([label.title]) }
+ destinations = []
+ allow(whatsapp_channel).to receive(:send_template) do |destination, _template, _message|
+ destinations << destination
+ raise Interrupt, 'response lost after acceptance' if destinations.one?
+
+ "wamid.#{destination}"
+ end
+ campaign.trigger!
+
+ expect { service.perform_batch(0) }.to raise_error(Interrupt, 'response lost after acceptance')
+ expect(campaign.reload.whatsapp_cursor).to eq(0)
+ interrupted = campaign.campaign_recipients.find_by!(contact: contacts.first)
+ expect(interrupted).to have_attributes(status: 'queued', source_id: nil, send_attempted_at: be_present)
+
+ Campaigns::SendWhatsappBatchJob.perform_now(campaign, 0)
+ Campaigns::SendWhatsappBatchJob.perform_now(campaign, 0)
+
+ expect(destinations).to eq(contacts.map(&:phone_number))
+ expect(campaign.reload).to be_completed
+ expect(campaign.campaign_recipients.sent.count).to eq(2)
+ expect(interrupted.reload.error_message).to include('Send outcome unknown')
+ end
+
+ it 'recovers a lost handoff using the saved cursor even when an old job is replayed' do
+ stub_const('Whatsapp::OneoffCampaignService::BATCH_SIZE', 1)
+ contacts = create_list(:contact, 2, :with_phone_number, account: account)
+ contacts.each { |contact| contact.update_labels([label.title]) }
+ allow(whatsapp_channel).to receive(:send_template).and_return('wamid.first', 'wamid.second')
+ campaign.trigger!
+ allow(Campaigns::SendWhatsappBatchJob).to receive(:perform_later).and_raise(StandardError, 'queue unavailable')
+
+ expect { Campaigns::SendWhatsappBatchJob.perform_now(campaign) }.to raise_error(StandardError, 'queue unavailable')
+ expect(campaign.reload.whatsapp_cursor).to eq(contacts.first.id)
+ campaign.update!(updated_at: 16.minutes.ago)
+ allow(Campaigns::SendWhatsappBatchJob).to receive(:perform_later).and_call_original
+
+ expect { Campaigns::RecoverWhatsappCampaignsJob.perform_now }
+ .to have_enqueued_job(Campaigns::SendWhatsappBatchJob).with(campaign, contacts.first.id)
+ Campaigns::SendWhatsappBatchJob.perform_now(campaign, 0)
+ Campaigns::SendWhatsappBatchJob.perform_now(campaign, 0)
+
+ expect(whatsapp_channel).to have_received(:send_template).exactly(2).times
+ expect(campaign.campaign_recipients.sent.count).to eq(2)
+ expect(campaign.reload).to be_completed
+ end
+
+ it 'does not resend an in-flight recipient when another worker acquires an expired lease' do
+ stub_const('Whatsapp::OneoffCampaignService::BATCH_SIZE', 2)
+ contacts = create_list(:contact, 3, :with_phone_number, account: account)
+ contacts.each { |contact| contact.update_labels([label.title]) }
+ destinations = []
+ campaign.trigger!
+ allow(whatsapp_channel).to receive(:send_template) do |destination, _template, _message|
+ destinations << destination
+ if destinations.one?
+ key = format(Redis::Alfred::WHATSAPP_CAMPAIGN_MUTEX, campaign_id: campaign.id)
+ Redis::Alfred.expire(key, 0)
+ Campaigns::SendWhatsappBatchJob.perform_now(Campaign.find(campaign.id))
+ end
+ "wamid.#{destination}"
+ end
+
+ Campaigns::SendWhatsappBatchJob.perform_now(campaign)
+ Campaigns::SendWhatsappBatchJob.perform_now(campaign)
+
+ expect(destinations).to eq(contacts.map(&:phone_number))
+ expect(campaign.campaign_recipients.sent.count).to eq(3)
+ expect(campaign.campaign_recipients.queued).to be_empty
+ expect(campaign.reload).to be_completed
+ end
+
+ it 'does not rewind the checkpoint when a worker finishes after its lease expires' do
+ stub_const('Whatsapp::OneoffCampaignService::BATCH_SIZE', 1)
+ contacts = create_list(:contact, 2, :with_phone_number, account: account)
+ contacts.each { |contact| contact.update_labels([label.title]) }
+ campaign.trigger!
+ allow(whatsapp_channel).to receive(:send_template).and_return('wamid.first', 'wamid.second')
+ replacement = Campaign.find(campaign.id)
+ replacement_service = Whatsapp::OneoffCampaignService.new(campaign: replacement)
+ allow(service).to receive(:process_contacts).and_wrap_original do |process, batch|
+ process.call(batch)
+ key = format(Redis::Alfred::WHATSAPP_CAMPAIGN_MUTEX, campaign_id: campaign.id)
+ Redis::Alfred.expire(key, 0)
+ replacement.update!(whatsapp_cursor: contacts.first.id)
+ Campaigns::SendWhatsappBatchJob.perform_now(replacement, contacts.first.id)
+ end
+ allow(Whatsapp::OneoffCampaignService).to receive(:new).and_return(service, replacement_service)
+
+ Campaigns::SendWhatsappBatchJob.perform_now(campaign)
+
+ expect(campaign.reload.whatsapp_cursor).to eq(contacts.last.id)
+ expect(whatsapp_channel).to have_received(:send_template).exactly(2).times
+ expect(campaign.campaign_recipients.sent.count).to eq(2)
+ end
+
+ it 'excludes historical queued, sent and failed recipients when a legacy batch is retried' do
+ contacts = create_list(:contact, 4, :with_phone_number, account: account)
+ contacts.each { |contact| contact.update_labels([label.title]) }
+ campaign.processing!
+ campaign.update!(whatsapp_cursor: nil)
+ queued = campaign.campaign_recipients.create!(account: account, inbox: whatsapp_inbox, contact: contacts.first)
+ campaign.campaign_recipients.create!(account: account, inbox: whatsapp_inbox, contact: contacts.second, status: :failed)
+ campaign.campaign_recipients.create!(account: account, inbox: whatsapp_inbox, contact: contacts.third,
+ status: :sent, source_id: 'wamid.existing')
+ allow(whatsapp_channel).to receive(:send_template) do |destination, _template, _message|
+ "wamid.#{destination}"
+ end
+
+ Campaigns::SendWhatsappBatchJob.perform_now(campaign)
+
+ expect(whatsapp_channel).to have_received(:send_template).with(contacts.last.phone_number, anything, nil).once
+ expect(whatsapp_channel).to have_received(:send_template).once
+ expect(queued.reload).to have_attributes(status: 'queued', send_attempted_at: nil)
+ expect(queued.error_message).to include('Send outcome unknown')
+ expect(campaign.campaign_recipients.failed.count).to eq(1)
+ expect(campaign.campaign_recipients.sent.count).to eq(2)
+ expect(campaign.reload).to be_completed
+ end
+ end
end
diff --git a/spec/jobs/campaigns/send_whatsapp_batch_job_spec.rb b/spec/jobs/campaigns/send_whatsapp_batch_job_spec.rb
index c68112e4422..dde8dace14d 100644
--- a/spec/jobs/campaigns/send_whatsapp_batch_job_spec.rb
+++ b/spec/jobs/campaigns/send_whatsapp_batch_job_spec.rb
@@ -47,6 +47,8 @@ RSpec.describe Campaigns::SendWhatsappBatchJob do
campaign.processing!
service = Whatsapp::OneoffCampaignService.new(campaign: campaign)
allow(Whatsapp::OneoffCampaignService).to receive(:new).and_return(service)
+ expect(service).to receive(:process_contacts).with(contacts.first(2))
+ described_class.perform_now(campaign)
expect(service).to receive(:process_contacts).with([])
described_class.perform_now(campaign, contacts.second.id)
@@ -95,4 +97,44 @@ RSpec.describe Campaigns::SendWhatsappBatchJob do
expect { Whatsapp::OneoffCampaignService.new(campaign: create(:campaign, account: account, inbox: channel.inbox)).perform }
.to raise_error('WhatsApp campaigns feature not enabled')
end
+
+ it 'does not process a campaign while another worker holds its Redis lock' do
+ campaign.processing!
+ manager = Redis::LockManager.new
+ key = format(Redis::Alfred::WHATSAPP_CAMPAIGN_MUTEX, campaign_id: campaign.id)
+ expect(manager.lock(key, described_class::LOCK_TIMEOUT)).to be(true)
+ expect(Whatsapp::OneoffCampaignService).not_to receive(:new)
+
+ described_class.perform_now(campaign)
+ expect(manager.locked?(key)).to be(true)
+ ensure
+ manager.unlock(key)
+ end
+
+ it 'releases the lock after a batch fails so another execution can continue' do
+ campaign.processing!
+ allow(Whatsapp::OneoffCampaignService).to receive(:new).and_return(sender)
+ allow(sender).to receive(:perform_batch).and_raise(StandardError, 'interrupted')
+ expect { described_class.perform_now(campaign) }.to raise_error(StandardError, 'interrupted')
+
+ key = format(Redis::Alfred::WHATSAPP_CAMPAIGN_MUTEX, campaign_id: campaign.id)
+ expect(Redis::LockManager.new.locked?(key)).to be(false)
+ allow(sender).to receive(:perform_batch).and_return(nil)
+ described_class.perform_now(campaign)
+
+ expect(campaign.reload).to be_completed
+ end
+
+ it 'allows another execution after an abandoned worker lease expires' do
+ campaign.processing!
+ key = format(Redis::Alfred::WHATSAPP_CAMPAIGN_MUTEX, campaign_id: campaign.id)
+ manager = Redis::LockManager.new
+ manager.lock(key, described_class::LOCK_TIMEOUT)
+ Redis::Alfred.expire(key, 0)
+
+ described_class.perform_now(campaign)
+
+ expect(campaign.reload).to be_completed
+ expect(manager.locked?(key)).to be(false)
+ end
end