What idempotent handling means
An operation is idempotent when running it once or many times with the same input leaves the same lasting effect. For a bot that means: if Telegram, Discord or WhatsApp delivers the same inbound event twice, the user gets one reply, the order is created once, and the ticket is opened once.
Delivery is almost always at-least-once. Networks drop responses, your process restarts mid-handler, a proxy times out after the work finished, or the platform resumes a session and replays missed events. Designing for exactly-once delivery is the wrong bet. Designing so a duplicate never produces a second business effect is the right one.
That design has two layers:
- Ingress deduplication. Recognize that this delivery is the same event you already saw, using a stable platform ID.
- Idempotent side effects. Even if two workers both pass the check briefly, database writes, outbound messages and third-party calls still do not double-apply.
If you are still choosing how the bot receives events, start with webhooks vs polling. Idempotency matters in both models.
Stable IDs by platform
| Platform | Primary key for an inbound event | Where duplicates come from |
|---|---|---|
| Telegram | update.update_id |
Webhook retries; replaying unconfirmed updates with getUpdates |
| Discord (HTTP interactions) | Interaction id |
Retries; two processes sharing one token |
| Discord (Gateway) | Message id, interaction id, or other snowflake on the event |
Resume replay after a disconnect |
| WhatsApp Cloud API | messages[].id (wamid); for statuses, id plus status |
Meta retries failed webhook deliveries |
Keys belong to the event inside the payload, not to the HTTP request as a whole. One WhatsApp POST can carry several items; one Telegram update is one unit; a Discord resume can replay a batch of Dispatch events.
Telegram: update_id and confirmation
Telegram's Bot API documents that every Update has an update_id: a unique integer that starts from a positive number and increases sequentially. The docs call out that this identifier is especially useful with webhooks, because it lets you ignore repeated updates or restore sequence if deliveries arrive out of order. At the time of writing they also note that if there are no new updates for at least a week, the next identifier may be chosen randomly instead of sequentially, so treat update_id as an opaque unique key, not as a perfect clock.
Incoming updates are stored until the bot receives them, and they are not kept longer than 24 hours. With long polling, an update is considered confirmed once getUpdates is called with an offset higher than that update's update_id. If you crash without advancing the offset, the next poll can return the same updates again. With a webhook, Telegram expects a timely HTTP success; if the request fails or times out, the same update can be delivered again.
Practical rules:
- Persist every processed
update_id(scoped to the bot token) before sending a user-visible reply or mutating business state. - Prefer claiming the ID atomically (
INSERTwith a unique constraint, or RedisSET NX) rather than check-then-insert. - Keep IDs at least as long as Telegram retains updates (24 hours), with a small margin.
- For polling, always pass
offset = last_update_id + 1after successful handling, and run a single consumer per token (a second poller or a webhook gets a 409 Conflict).
Related reading on this site: Telegram setWebhook step by step and graceful shutdown for bots.
Discord: interactions and Gateway resume
Discord apps receive interactions over the Gateway or over an Interactions Endpoint URL. Either way, each interaction object has a unique snowflake id. You may acknowledge an interaction with exactly one initial callback to POST /interactions/{id}/{token}/callback. A second initial response returns error 40060 ("Interaction has already been acknowledged"). That error often means a duplicate delivery or two processes sharing the same application token both tried to answer.
On the Gateway, disconnects are normal. Discord's resume flow asks you to cache session_id, resume_gateway_url and the last Dispatch sequence number s, then send Resume (opcode 6). After a successful resume, Discord replays missed events in order and finishes with a Resumed event. Those replayed events are real deliveries of the same underlying objects: if your handler keys only on channel and author, a resumed MESSAGE_CREATE can look new. Key on the event's own ID (for example message.id or the interaction id).
Practical rules:
- Deduplicate HTTP interactions by interaction
idbefore any acknowledge or defer. - Deduplicate Gateway message handling by
message.id(and similar snowflakes for other event types you act on). - Never run two live instances with the same bot token against production traffic.
- After acknowledging once, further edits go through the interaction webhook follow-up routes, not a second initial callback.
See also Discord gateway intents explained and Discord slash commands in discord.js v14.
WhatsApp Cloud API: message IDs and retries
Meta delivers WhatsApp Cloud API events as webhooks. Official documentation states that if a webhook request does not get an HTTP 200, or cannot be delivered for another reason, Meta retries with decreasing frequency until the request succeeds, for up to 7 days at the time of writing. Retries go to every app subscribed to the relevant fields for that messaging account, and those retries can produce duplicate webhook notifications.
Inbound user messages carry a WhatsApp message ID (messages[].id, often shown as a wamid... string). Status callbacks for outbound messages reuse the message ID across sent, delivered, read and failed, so the dedupe key for a status event is the pair (id, status), not the ID alone. Deduplicate each item inside the payload; do not treat the whole POST body as one event.
Practical rules:
- Reply
200quickly after verifying the signature, then process asynchronously if work is slow. - Claim
msg:{wamid}for inbound messages andst:{wamid}:{status}for statuses with a TTL of at least eight days (seven days of retries plus margin). - Model statuses as observations that can arrive out of order; do not assume a simple forward-only state machine.
Webhook TLS and verification belong in a custom domain and HTTPS for bot webhooks. Sending your first message is covered in WhatsApp Cloud API first message.
A small Python claim store
The same pattern works across platforms: build a string key, claim it once, skip if the claim fails. This example uses SQLite for a single-process bot; replace the store with Redis SET key 1 NX EX ttl or a unique index when you scale out.
import sqlite3
import time
DB = sqlite3.connect("idempotency.db", check_same_thread=False)
DB.execute(
"CREATE TABLE IF NOT EXISTS seen ("
" key TEXT PRIMARY KEY,"
" created_at REAL NOT NULL"
")"
)
DB.commit()
def claim(key: str, ttl_seconds: int) -> bool:
"""Return True if this key is new and now owned by the caller."""
now = time.time()
DB.execute("DELETE FROM seen WHERE created_at < ?", (now - ttl_seconds,))
try:
DB.execute(
"INSERT INTO seen(key, created_at) VALUES (?, ?)",
(key, now),
)
DB.commit()
return True
except sqlite3.IntegrityError:
DB.rollback()
return False
def telegram_key(update: dict) -> str:
return f"tg:{update['update_id']}"
def discord_interaction_key(interaction: dict) -> str:
return f"dc:ix:{interaction['id']}"
def whatsapp_message_key(msg: dict) -> str:
return f"wa:msg:{msg['id']}"
def whatsapp_status_key(status: dict) -> str:
return f"wa:st:{status['id']}:{status['status']}"
Wire it at the edge of the handler:
def handle_telegram_update(update: dict):
key = telegram_key(update)
if not claim(key, ttl_seconds=36 * 3600):
return # duplicate delivery; acknowledge and stop
# side effects only after a successful claim
process_telegram(update)
Claim first, then act. If you act first and crash before recording the key, the retry will run the side effect again. If the claim must survive a crash mid-work, store a processing then done state, or make every side effect itself idempotent (upsert by business key, outbound APIs with their own idempotency keys).
Where the webhook host and landing page live
Idempotency lives in your application code, but the URL platforms call still needs a stable HTTPS hostname. Register a short domain for hooks.example.com through a registrar such as Namecheap domains, point DNS at your bot host, and terminate TLS as described in the custom-domain guide above. The same root domain can serve a one-page status or privacy note; small shared Namecheap hosting is enough for that static page while the webhook subdomain stays on the bot server. If you are still picking a registrar and a home for DNS, Namecheap is one place that covers both domains and basic hosting.
Keep secrets out of that landing page. Tokens, app secrets and the idempotency database stay on the bot host; see securing bot tokens.
Checklist
- Pick the platform's stable event ID (
update_id, interaction or message snowflake, wamid / status pair) and ignore request-level fingerprints. - Claim the key atomically before any reply, charge, ticket or CRM write.
- Keep keys at least as long as the platform retries (24 hours for Telegram updates; about seven days for Meta webhooks at the time of writing).
- Make side effects idempotent too: upserts, unique business keys, and provider idempotency headers where they exist.
- Run one consumer per Telegram token; avoid duplicate Discord bot processes in production.
- Acknowledge webhooks quickly with success only after signature checks pass; process heavy work after the claim.
- Give the endpoint a durable HTTPS name on a domain you control, and a small public page that explains what the bot does.
Sources
- Telegram Bot API, Update (
update_id) and Getting updates (getUpdatesoffset): core.telegram.org/bots/api#update - Telegram Bot API, Getting updates (24-hour retention): core.telegram.org/bots/api#getting-updates
- Discord, Gateway (Resuming and sequence numbers): docs.discord.com/developers/events/gateway
- Discord, Interactions overview: docs.discord.com/developers/interactions/overview
- Meta, WhatsApp webhooks overview (retries up to 7 days and duplicate notifications): developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview