Voice AI

Keeping WhatsApp Coexistence Honest: Build a Sync Monitor for Hybrid WhatsApp Channels

One WhatsApp number, two write paths. Your front-desk team types into the WhatsApp Business app. Your reminder system sends through the WhatsApp Business API. Coexistence mode lets both operate on the same line — which is exactly what you want, and exactly how your application state drifts out of sync with reality.

If a customer reschedules with a human agent, your API-driven system doesn't know unless something tells it. That "something" is the message.echo webhook, and treating it as an afterthought is how conflicting information reaches your customers.

This post walks through the WhatsApp Coexistence Sync Monitor, a small Flask service that closes that loop: it verifies the number's lifecycle state through the Telnyx API, receives and authenticates message.echo webhooks, filters events that arrive while the number is mid-sync, and appends every legitimate Business-app message to an audit log. It's a couple hundred lines of Python, and the pattern generalizes to any hybrid channel you operate.

What the App Does

The service has three responsibilities:

  1. Verify lifecycle state. Before trusting that the hybrid channel is coherent, the service queries the Telnyx API for the number's coexistence status: is_on_biz_app (is the number registered on the WhatsApp Business app?) and coexistence_state (is sync active?). Results are cached in memory for 60 seconds.
  2. Receive and authenticate echo webhooks. A Flask route at POST /webhooks/whatsapp/echo accepts message.echo events — fired when someone sends a message from the WhatsApp Business app — and validates the Telnyx Ed25519 signature before touching the payload.
  3. Log to an audit trail. Accepted events are appended to a JSONL file, one JSON object per line: a replayable record of every manual message.

The gate between (2) and (3) is the interesting part. Events that arrive while the number is mid-sync are acknowledged but not logged, because during a sync window the echo stream can't be trusted to be complete.

How It Works

The webhook receiver: verify first, parse second

Telnyx signs webhooks with Ed25519 and delivers the signature in two headers: telnyx-signature-ed25519 and telnyx-timestamp. The service refuses to do anything with the payload until both check out:

client = telnyx.Client(api_key=TELNYX_API_KEY, public_key=TELNYX_PUBLIC_KEY)

def verify_webhook_signature(headers: dict, raw_body: bytes) -> bool:
    signature = headers.get("telnyx-signature-ed25519")
    timestamp = headers.get("telnyx-timestamp")
    if not signature or not timestamp:
        return False

    # Reject timestamps that skew too far from now
    ts = int(timestamp)
    if abs(time.time() - ts) > MAX_TIMESTAMP_SKEW_SECONDS:
        return False

    try:
        # unwrap verifies the Ed25519 signature over "<timestamp>|<payload>"
        # and raises ValueError on any failure (bad key, bad sig, stale ts).
        # NOTE: the kwarg is `key` (NOT `public_key`) in SDK >= 4.x.
        client.webhooks.unwrap(
            payload=raw_body.decode("utf-8"),
            headers={
                "telnyx-signature-ed25519": signature,
                "telnyx-timestamp": timestamp,
            },
            key=TELNYX_PUBLIC_KEY,
        )
        return True
    except Exception:
        return False


@app.route("/webhooks/whatsapp/echo", methods=["POST"])
def whatsapp_echo_webhook():
    raw_body = request.get_data()
    if not verify_webhook_signature(request.headers, raw_body):
        return jsonify({"error": "Invalid signature"}), 401
    # ... only now is the payload parsed

MAX_TIMESTAMP_SKEW_SECONDS bounds how old a signed request may be, which closes the replay window — an attacker can't capture a valid signed payload and replay it hours later.

Note the failure mode: an invalid signature is a 401, never a 200. If you ACK unverified webhooks, you've converted a security control into a suggestion. And one SDK trap worth calling out: the unwrapping kwarg is key, not public_key — the comment block above is in the repo precisely so you don't lose an afternoon to that one.

The state checker: don't log what you can't verify

Every accepted webhook triggers a state check — but calling the API on every event would be wasteful and would couple your logging latency to API latency. The service keeps a tiny in-memory cache with a 60-second TTL (STATE_CHECK_TTL_SECONDS), wrapped in a StateChecker class:

class StateChecker:
    def verify_with_number_api(self) -> dict:
        """Queries the Telnyx API to verify coexistence status of a WhatsApp number.

        SDK v4: client.whatsapp.phone_numbers.retrieve_phone_number(phone_number)
        """
        if DEMO_MODE:
            return self._fetch_state()  # simulated state, no live API call

        if not self.phone_number:
            raise ValueError("WHATSAPP_NUMBER must be set when DEMO_MODE=false")

        number = client.whatsapp.phone_numbers.retrieve_phone_number(self.phone_number)
        return {
            "phone_number": getattr(number, "phone_number", self.phone_number),
            "is_on_biz_app": number.is_on_biz_app,
            "coexistence_state": number.coexistence_state,
        }

    def get_state(self) -> dict:
        """Return the current state, using the TTL cache."""
        now = time.time()
        cached = self._cache.get("state")
        if cached and (now - cached[0]) < self.ttl_seconds:
            return cached[1]

        state = self._fetch_state()
        self._cache["state"] = (now, state)
        return state

    def is_active(self) -> bool:
        """True if the number is on the biz app and in 'active' coexistence state."""
        state = self.get_state()
        return bool(state.get("is_on_biz_app")) and state.get("coexistence_state") == "active"

If you're monitoring more than one number, there's a bulk variant — GET /v2/whatsapp/business_accounts/{waba_id}/phone_numbers — and since each StateChecker owns one number, you simply run one checker per number.

The gate: skip mid-sync events, but ACK them

Here's the decision logic that ties it together:

    event_type = payload.get("event_type")
    if event_type != "message.echo":
        app.logger.info("Ignoring non-message.echo event: %s", event_type)
        return jsonify({"status": "ignored"}), 200

    # Check coexistence state (with TTL cache)
    if not state_checker.is_active():
        # Accept with 200 — do NOT reject, otherwise Telnyx retries delivery
        return jsonify({"ok": "skipped", "reason": "number_not_active"}), 200

    # Validate the echo semantics:
    # - origin must be 'whatsapp_business_app' for a manual-channel echo
    # - cost must be null / {amount: null, currency: null} (no billing event)
    origin_matches_biz_app = origin == "whatsapp_business_app"
    cost = message.get("cost")
    if cost is None:
        no_charge = True  # cost field absent or explicitly null
    elif isinstance(cost, dict) and cost.get("amount") is None and cost.get("currency") is None:
        no_charge = True
    else:
        no_charge = False

The subtle choice: when the number is mid-sync, the service returns 200 and skips logging. It does not return an error. A skip is a decision, not a failure — if you returned a 5xx here, Telnyx would retry the delivery, and you'd log a duplicate once sync completes. ACK the event, record the skip, move on.

And note what happens to an echo whose origin isn't whatsapp_business_app, or whose cost looks like a billing event: it is not discarded. Both checks become boolean verdicts — origin_matches_biz_app, no_charge — that ride along in the audit record, so anomalies are captured, not silently dropped.

The message logger: an audit trail you can replay

class MessageLogger:
    """Appends accepted message.echo events to a JSONL file for audit purposes."""

    def __init__(self, path: str):
        self.path = Path(path)

    def append(self, event: dict) -> None:
        """Append one event as a JSON line. Creates the file if needed."""
        with self.path.open("a", encoding="utf-8") as f:
            f.write(json.dumps(event, ensure_ascii=False) + "\n")


# inside the webhook handler, after all gates pass:
log_entry = {
    "timestamp": datetime.now(timezone.utc).isoformat(),
    "event_id": event_id,
    "event_type": event_type,
    "origin": origin,
    "origin_matches_biz_app": origin_matches_biz_app,
    "text": message.get("text"),
    "message_id": message.get("id"),
    "no_charge": no_charge,
}
message_logger.append(log_entry)

Note what's absent from that record: no from, no to, no cost amount. Raw phone numbers and monetary figures never touch the audit log — only the boolean verdicts derived from them. That's deliberate PII minimization: the trail stays replayable and greppable without becoming a database of customer phone numbers.

JSONL is deliberately boring: append-only, one JSON object per line, trivially greppable, trivially replayable into any downstream system. In production you'd swap this for a database or a queue — the interface stays the same.

Setup

git clone https://github.com/team-telnyx/telnyx-code-examples.git
cd telnyx-code-examples/whatsapp-coexistence-sync-monitor

python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

cp .env.example .env

Fill in .env:

TELNYX_API_KEY=KEYyour_api_key
TELNYX_PUBLIC_KEY=your_ed25519_public_key
WABA_ID=your_whatsapp_business_account_id
WHATSAPP_NUMBER=+155****4567
ECHO_LOG_PATH=./echo_log.jsonl
STATE_CHECK_TTL_SECONDS=60
MAX_TIMESTAMP_SKEW_SECONDS=300
PORT=5000
DEMO_MODE=false

Your API key and public key come from the Telnyx console; the WABA ID and number come from your WhatsApp Business Account once it's connected to Telnyx. DEMO_MODE swaps live API calls for simulated state so you can exercise the logging flow without a coexistence-enabled number — leave it false anywhere that matters.

Run it:

python app.py

Confirm it's alive:

curl http://localhost:5000/health
# {"status": "ok"}

Point your Telnyx webhook profile at your public URL (ngrok works fine in development), then send a message from the WhatsApp Business app on your coexistence-enabled number and watch the trail:

tail -f echo_log.jsonl
# {"timestamp": "2026-10-16T18:42:03.117221+00:00", "event_id": "4005fe34-...", "event_type": "message.echo", "origin": "whatsapp_business_app", "origin_matches_biz_app": true, "text": "Running 10 min late, see you soon", "message_id": "wamid.HBg...", "no_charge": true}

Conclusion

Coexistence is the right model for teams whose WhatsApp traffic is part human, part automated — but it makes sync your problem, and the message.echo webhook is the only honest signal the Business-app side emits. This monitor is small on purpose: verify the signature, check the state, log the message, ACK everything.

From here, swap the JSONL file for a database, add drift alerting by diffing the echo log against your API send log, or wire the state checker into a dashboard. The full sample — including the complete signature-verification flow and the mid-sync gate — is in the telnyx-code-examples repo. Telnyx's AI Communications Infrastructure handles the WhatsApp Business API complexity, lifecycle state, and signed webhook delivery, so the code you write is the code that matters: the sync logic that keeps your hybrid channel consistent.

Ready to build with low-latency voice AI?

Join developers building the future of real-time conversations