Lesson 3 of 9 · 27m
Polling vs Webhooks and the Real Meaning of an Update
Compare long polling with webhook delivery, manage update offsets and idempotency, and build ingestion that tolerates retries and out-of-order effects.
The question is not whether webhooks are 'better' than polling. The real question is where you want operational complexity to live. Polling makes your service actively ask Telegram for updates; webhooks make Telegram push updates into your public ingress. Both can be correct. Both become unreliable when teams treat an update as a one-time event instead of a delivery record that may repeat.
Long polling is operationally simple
With getUpdates, your worker asks Telegram for a batch and advances an offset after processing:
curl -sS "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/getUpdates?timeout=30&offset=812345680" | jqThe important detail is the offset. Telegram keeps unacknowledged updates available. You acknowledge them by asking for offset = last_update_id + 1. If you acknowledge before processing and then crash, the update is gone. If you process first and crash before acknowledgment, it returns. The correct architecture therefore assumes duplicates.
Long polling is useful for small deployments, private networks, development, and services that cannot expose a public HTTPS endpoint. Its cost is a continuously running worker and less natural horizontal scaling.
Webhooks move ingress complexity to you
A webhook is registered with Telegram:
curl -sS -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/setWebhook" -H 'content-type: application/json' -d '{
"url":"https://ops.sudosecurity.org/hooks/telegram",
"secret_token":"0123456789abcdef0123456789abcdef",
"allowed_updates":["message","callback_query","pre_checkout_query"],
"max_connections":40
}'Telegram then POSTs updates to your endpoint. You control concurrency, response latency, TLS termination, retry behavior, and ingress security. That is powerful, but it means a broken deployment is now a message-delivery incident. Telegram retries delivery for a period, but retries are not a substitute for correctness.
The endpoint contract is strict enough to matter
A webhook handler should authenticate the request, parse it minimally, enqueue durable work, and return quickly. Do not run your whole business workflow inside the HTTP request if it can block:
async def telegram_webhook(request):
if request.headers.get("X-Telegram-Bot-Api-Secret-Token") != settings.webhook_secret:
return Response(status_code=401)
update = await request.json()
await queue.put_nowait(update)
return Response(status_code=200)Returning 200 only after durable enqueue is a reasonable compromise for small systems. Returning 200 before any durable acceptance is data loss. Performing a slow payment provider call before response is a retry amplifier.
Update IDs are per bot, not a global ordering proof
Updates arrive with monotonically increasing update_id values in ordinary operation, but production logic should not depend on perfect ordering for side effects. Edits, callback queries, service messages, and payment events are different objects in one stream. Persist the highest processed ID or maintain per-conversation ordering state where sequence matters.
A durable ingestion table can be as simple as:
create table telegram_updates (
update_id bigint primary key,
payload jsonb not null,
received_at timestamptz not null default now(),
processed_at timestamptz,
attempts integer not null default 0
);The primary key makes duplicate delivery harmless. Workers can claim rows transactionally and retry failures without losing evidence.
Choose deliberately
Use long polling when one worker is enough, ingress is undesirable, or the deployment is internal. Use webhooks when latency matters, you already operate reliable public HTTP services, or concurrency must scale beyond one poller. Do not run both against the same bot token unless you fully understand the ownership transition; setting a webhook disables normal getUpdates delivery behavior until deleted.
Field notes
- Process-then-acknowledge means duplicates. Acknowledge-then-process means loss. There is no free lunch.
allowed_updatesreduces noise and accidental ingestion of message types you never designed for.- Telegram webhook retries can duplicate user-visible effects. Idempotency belongs in command handlers, not only ingress.
- Public webhook paths are not secret security controls. Use the secret token header and network controls where available.
- Never expose the bot token in the webhook URL as your only defense; tokens leak through access logs.
Was this lesson helpful?