baileys whatsapp-cloud-api migration zero-downtime production-deployment

Migrate from Baileys to WhatsApp Cloud API without downtime

-

Why “Just Switch” Causes Downtime

You’ve been running your bot on Baileys for months. Now you know the risks — detection patterns leading to bans are real, and Meta’s enforcement is tightening. You want to migrate to WhatsApp Cloud API. But you can’t just flip a switch.

What breaks if you “just switch”:

  1. Session loss — Baileys maintains a persistent device session (like a linked WhatsApp Web). When you shut it down without proper handoff, customers mid-conversation see your number go offline. New messages they send during the gap are lost or delayed.

  2. Conversation context — Your agent’s conversation state (where each customer is in a flow, pending requests, user preferences) lives in your Baileys instance’s memory or database. Cloud API doesn’t inherit this state automatically.

  3. Webhook routing — Baileys delivers messages via WebSocket or local REST endpoint. Cloud API delivers via HTTPS webhooks with signature validation. If your agent isn’t ready to receive Cloud API webhooks when you kill Baileys, messages fall into a black hole.

  4. Template approval lag — Cloud API requires pre-approved templates for business-initiated messages outside the 24-hour window. If you haven’t created and approved templates before migration, you lose the ability to send proactive notifications.

  5. Number registration — You can’t use your personal Baileys number directly on Cloud API. You need a registered business number. Customers who saved your old number won’t automatically know about the new one.

The playbook below avoids all of these.

Pre-Flight: What to Set Up Before Migration Day

1. Register Your Business Number on Cloud API

If you’re using Baileys with a personal WhatsApp number, you cannot migrate that number to Cloud API. Personal accounts and Business API accounts are fundamentally different.

Your options:

  • New business number — Register a new phone number through Meta Business Manager (direct registration as Tech Provider) or through a managed bridge like Pipes.bot (BYON flow). This is the cleanest path.

  • Pool number (for personal agents) — If your use case is a personal AI agent (not business support), activate a pool number on Pipes.bot. Customers message the pool number; messages route to your agent. Your personal Baileys number stays separate.

Timeline: Allow 24–48 hours for number verification and initial template approvals.

2. Create and Approve Message Templates

Cloud API requires message templates for proactive messages sent outside the 24-hour customer service window.

Required templates before migration:

  • Welcome message — Sent when customer first contacts your new number
  • Handoff notification (optional) — If you’re migrating customers from old Baileys number to new Cloud API number, you need a template to notify them: “We’re upgrading! Save this new number: +1…”
  • Business-critical templates — Order confirmations, appointment reminders, authentication codes, shipping updates

How to create:

  1. Go to WhatsApp Manager → Message Templates
  2. Write template text with variable placeholders (e.g., {{1}} for customer name)
  3. Submit for Meta approval (usually 1–24 hours)
  4. Test approved templates in sandbox before production

Common rejection reasons: Spammy language, unclear opt-in, missing business context. Read Meta’s template guidelines.

3. Set Up and Validate Webhook Endpoint

Cloud API delivers messages via HTTPS POST to your webhook URL. Unlike Baileys (which your code polls or connects to), Cloud API is push-based.

Requirements:

  • Public HTTPS URL with valid SSL certificate
  • GET endpoint for verification handshake (Meta sends hub.challenge, you echo it back)
  • POST endpoint for message notifications
  • HMAC-SHA256 signature validation (using your App Secret)
  • Idempotency handling (Meta retries failed deliveries)

Implementation checklist:

  • Webhook responds to GET verification with hub.challenge
  • POST handler validates X-Hub-Signature-256 header
  • Deduplication by wamid (message ID) to prevent double-processing on retries
  • Responds 200 OK within 20 seconds
  • Queues agent work asynchronously (don’t block webhook on LLM inference)

Read the full webhook guide: WhatsApp Cloud API webhooks for AI agents: retries, idempotency, signatures

Testing:

  1. Register webhook URL in WhatsApp Manager
  2. Send test message from your personal WhatsApp to your Cloud API number
  3. Verify webhook receives notification with correct signature
  4. Confirm your agent processes and replies successfully

If you’re using a managed bridge like Pipes.bot: The bridge handles webhook signature validation and retry logic for you. You connect your agent via outbound WebSocket (no public webhook needed).

4. Verify Conversation Context Portability

Your Baileys bot stores conversation state somewhere:

  • In-memory (worst case — lost on restart)
  • Redis or similar cache
  • Database (Postgres, MongoDB, etc.)

Before migration, audit:

  1. What state do you store? (conversation step, user preferences, pending requests, session variables)
  2. Is state keyed by phone number? (good) or by Baileys session ID? (bad)
  3. Can you map Baileys customer ID to Cloud API customer ID? Both use WhatsApp IDs (international format like 5511999999999), so this should be straightforward

Migration strategy:

  • If state is keyed by phone number (wa_id), no change needed — Cloud API uses the same IDs
  • If state includes Baileys-specific session metadata, write a migration script to strip that before cutover
  • Test that your agent can resume a conversation started on Baileys after it’s continued on Cloud API

Dual-Run Architecture: Run Both During Cutover

The safest migration strategy is dual-run: keep Baileys alive while you validate Cloud API in parallel, then switch traffic.

Architecture:

Phase 1 (Testing):
  Customer → WhatsApp → Baileys → Your Agent (production)
                     → Cloud API (test number) → Your Agent (staging)

Phase 2 (Dual-run):
  Customer → WhatsApp → Baileys → Your Agent (receives, processes, replies)
                     → Cloud API → Your Agent (receives, logs, no reply)

Phase 3 (Cutover):
  Customer → WhatsApp → Cloud API → Your Agent (production)
  (Baileys shut down)

How to implement Phase 2 (dual-run):

  1. Route Cloud API webhooks to your agent but set a flag cloud_api_dry_run = true
  2. Your agent processes Cloud API messages (maintains conversation state) but does not send replies via Cloud API
  3. Baileys continues to receive and reply as normal
  4. Log discrepancies: if a message arrives on Cloud API but not Baileys (or vice versa), alert your monitoring

Why this works:

  • Customers see no change — Baileys still replies
  • You validate that Cloud API delivers messages correctly
  • You test your webhook signature validation and idempotency in production traffic
  • Conversation state is already synchronized when you flip to Cloud API

Duration: Run dual-mode for 24–72 hours. Monitor for:

  • Cloud API webhook delivery rate matches Baileys message rate
  • No signature validation failures
  • No duplicate processing (idempotency working)
  • Agent can reconstruct conversation state from Cloud API messages

Webhook Cutover Checklist

When dual-run validation passes, you’re ready to cut over.

The switch:

  1. Announce maintenance window (optional) — “We’re upgrading our systems. You may experience a 1–2 minute delay in replies around [time].”
  2. Stop Baileys from sending replies — Set a flag in your agent: baileys_readonly = true. Baileys still receives (for logging) but doesn’t send.
  3. Enable Cloud API replies — Set cloud_api_active = true. Your agent starts sending replies via Graph API.
  4. Monitor for 15 minutes — Verify replies go out successfully, customers receive them, no errors.
  5. Shut down Baileys WebSocket — Disconnect Baileys session gracefully (don’t just kill the process — call sock.logout() if your library supports it).
  6. Update customer-facing materials — If you migrated to a new number, update your website, email signatures, social profiles.

Critical: Do this during low-traffic hours (e.g., 2–4 AM in your primary market). If something goes wrong, you have time to rollback before peak traffic.

Session and Multi-Device Risk When Killing Baileys

Baileys emulates a linked device. When you shut it down, WhatsApp sees a “device disconnected” event. Here’s what happens:

Immediate effects:

  • Baileys WebSocket closes
  • WhatsApp servers mark your emulated device as offline
  • If you never reconnect Baileys, the “device” stays in your account’s linked devices list but inactive

What does NOT happen:

  • Your personal WhatsApp account is not logged out (if you were using a personal number via Baileys)
  • Messages sent to your number after Baileys disconnects are not lost — they’re queued by WhatsApp servers. When you connect Cloud API with the same number (if you used BYON), those messages deliver to Cloud API. If you’re using a new number, old messages stay with the old account.

Multi-device quirk:

If you were using Baileys with a personal number and you migrate to a new Cloud API business number, your personal number remains active. Customers who message your old number reach your personal WhatsApp app (if you still use it). This is why communicating the number change is critical.

Mitigation:

  • Use your personal phone to send a broadcast message: “I’m now using [new number] for bot conversations. Please save this contact.”
  • If the old number is only for the bot (not personal use), you can delete the WhatsApp account after migration to force customers to use the new number. (Warning: This is irreversible.)

Rollback Plan: What If Cloud API Fails?

Always have a rollback path.

Scenario: You cut over to Cloud API, but 30 minutes later you discover:

  • Webhook signature validation is broken (configuration error)
  • Cloud API rate limits are hit (you forgot to request higher throughput)
  • Your agent crashes under Cloud API load
  • Meta’s API has an outage (rare but possible)

Rollback steps:

  1. Re-enable Baileys replies — Set baileys_readonly = false, restart Baileys WebSocket connection
  2. Disable Cloud API replies — Set cloud_api_active = false
  3. Communicate to customers — “We’re experiencing technical issues. Service restored via our previous contact method.”
  4. Investigate and fix — Debug Cloud API issue in staging
  5. Retry cutover when fixed

Rollback window: Baileys can reconnect within minutes. Session data (encryption keys) persists in your Baileys credentials file. As long as you haven’t deleted it, you can reconnect.

After successful migration: Keep Baileys credentials backed up for 7 days, then delete. This prevents accidental reconnection (which could trigger ban detection).

FAQ: Migration-Specific Questions

Can I migrate my Baileys phone number to Cloud API?

If it’s a personal number: No. WhatsApp personal accounts cannot be converted to Business API accounts. You need a new business phone number.

If it’s a business number previously used with Baileys: Technically yes, via BYON (Bring Your Own Number) on Cloud API. But:

  • You’ll need to verify ownership through SMS or call
  • WhatsApp may flag the number if it was previously used with unofficial APIs (Baileys)
  • Safer to start with a fresh number

What happens to messages sent during the cutover gap?

If there’s a 2-minute window where Baileys is down and Cloud API isn’t live yet:

  • Customer sends message → WhatsApp queues it
  • When Cloud API comes online → Queued messages deliver to your webhook within seconds
  • No messages are lost as long as cutover gap is <5 minutes

Meta’s webhook retry logic handles brief outages. But don’t let the gap exceed 10 minutes or retries may give up.

Do I need to migrate conversation history?

Message content: No. WhatsApp Cloud API doesn’t give you access to historical messages. Only new messages (post-migration) arrive via webhooks.

Conversation state: Yes. If your agent needs to know “this customer is in the middle of checkout flow”, that state must persist through migration. Store it in a database keyed by customer phone number (wa_id).

How do I test the migration without affecting production customers?

Strategy 1: Test number

  • Register a separate test number on Cloud API
  • Run your agent in staging mode connected to test number
  • Send test messages from your personal WhatsApp
  • Validate full flow before touching production Baileys number

Strategy 2: Canary rollout

  • If you have multiple Baileys instances (e.g., one per customer in a SaaS product), migrate 5% of instances first
  • Monitor for 48 hours
  • If stable, migrate remaining 95%

Can WAHA or Evolution API help with migration?

No. WAHA and Evolution API are wrappers around Baileys. They use the same reverse-engineered protocol under the hood. Migrating from Baileys to WAHA is not a migration — it’s staying on unofficial infrastructure with the same ban risks.

Read: Baileys vs WhatsApp Cloud API: why your bot gets banned

Does migrating to Cloud API affect message costs?

Yes. Starting October 1, 2026, Cloud API service messages are charged (with 1,000 free per month per number).

Before migration (Baileys):

  • Cost: $0 for messages (but risk of losing number = infinite cost)

After migration (Cloud API):

  • First 1,000 service messages/month: Free
  • After 1,000: ~$0.0068/message (Brazil) or local utility rate
  • Plus your LLM cost (if using AI agent)

Read cost optimization guide: WhatsApp service messages October 2026 playbook

Can I run Baileys and Cloud API on the same number simultaneously?

No. A WhatsApp number can only be active on one platform at a time:

  • Registered on Business API → Cannot use with Baileys
  • Linked to personal account → Cannot register on Business API

The “dual-run” strategy described above uses:

  • Baileys on your old number (e.g., +55 11 98888-8888)
  • Cloud API on a new number (e.g., +55 11 97777-7777)

Or, if you have separate test and production environments, run them on different accounts.

When a Managed Bridge Simplifies Migration

If you’re migrating a production bot and don’t want to manage webhook infrastructure, use a managed bridge like Pipes.bot.

What Pipes.bot provides for migration:

  1. Already registered as Meta Tech Provider — Skip the weeks-long onboarding process
  2. Outbound WebSocket connection — Your agent connects to Pipes.bot (no public webhook URL needed). No changes to your firewall or infrastructure.
  3. Built-in webhook validation and retry handling — HMAC signature validation, idempotency, and queuing are handled by Pipes.bot
  4. Pool numbers or BYON — Use a Pipes.bot-provided number (for testing or personal agents) or register your own business number
  5. Dual-run testing — Connect Cloud API via Pipes.bot while Baileys is still running. Test in parallel, then flip.

Migration flow with Pipes.bot:

  1. Sign up at Pipes.bot, create an App
  2. Activate a pool number or register your business number (BYON)
  3. Connect your agent to Pipes.bot WebSocket (same agent code that talks to Baileys, just different transport layer)
  4. Run in dry-run mode (receive but don’t reply) while Baileys is live
  5. Validate for 48 hours
  6. Flip: Disable Baileys replies, enable Cloud API replies via Pipes.bot
  7. Shut down Baileys

Rollback: Disconnect from Pipes.bot WebSocket, reconnect Baileys. No infrastructure changes needed.

Next Steps: Start the Migration

Week 1: Setup

  • Register business number on Cloud API (direct or via Pipes.bot)
  • Create and submit message templates for approval
  • Set up webhook endpoint (or Pipes.bot WebSocket connection)
  • Write conversation state migration script (if needed)

Week 2: Validation

  • Test webhook/WebSocket connection with test messages
  • Enable dual-run mode (Cloud API receives but doesn’t reply)
  • Monitor for 48 hours: verify delivery, signature validation, idempotency

Week 3: Cutover

  • Schedule cutover window (low-traffic hours)
  • Disable Baileys replies → Enable Cloud API replies
  • Monitor for errors
  • Shut down Baileys after 24 hours of stable Cloud API operation

Week 4: Cleanup

  • Communicate new number to customers (if applicable)
  • Delete Baileys credentials and session files
  • Update documentation and runbooks
  • Celebrate compliant infrastructure

Recommended reading order:

  1. Baileys vs WhatsApp Cloud API: why your bot gets banned — Understand the risks you’re migrating away from
  2. WhatsApp Cloud API webhooks for AI agents — Technical implementation of webhook endpoint
  3. WhatsApp service messages October 2026 playbook — Cost optimization after migration
  4. Pipes.bot Getting Started Guide — If using managed bridge

For migration support or technical questions, the Pipes.bot team is available — founder Tulio Faria personally responds to all inquiries.