Lesson 8 of 9 · 28m
Scaling Bots: Queues, Telegram Rate Limits, and Idempotent Workers
Separate ingestion from execution, respect Telegram throttles, coalesce chat bursts, and design workers that can retry side effects safely.
A bot that works for ten users can fall over at a thousand for reasons that look mysterious only if ingestion, state, and side effects are tangled together. Telegram adds its own constraints: method-call rate limits, chat-specific throttles, webhook retry behavior, and large update bursts during incidents. Scaling is less about raw throughput and more about preserving correctness under bursty, duplicated, partially ordered traffic.
Split ingress from execution
The ingestion layer accepts updates and persists them. Workers execute business logic. A queue between them gives you backpressure and retry control:
webhook -> postgres/redis queue -> worker pool -> Telegram API callsThis separation lets you deploy workers without closing the ingress, isolate slow payment processing from command handling, and replay poisoned messages after a fix. Even a Postgres-backed table is enough for many production bots; you do not need Kafka because a product manager said 'scale.'
Telegram throttles are part of the protocol
Telegram rate limits vary by method, chat, and global load, and exact numbers are intentionally not a stable contract. Your code must handle 429 Too Many Requests with retry_after rather than hardcoding folklore values:
except RetryAfter as exc:
await queue.requeue(job, delay=exc.retry_after)Respect the retry delay. Retrying immediately can turn a small burst into a platform-level denial-of-service against your own bot. Chat-level ordering often matters more than global concurrency. If a user sends five rapid commands, parallel workers may send replies out of order or race shared state. Partition work by chat ID:
worker queue key = chat_idThat preserves per-chat serialization while still allowing different chats to process concurrently.
Idempotency is the scaling primitive
Retries are guaranteed in any serious design. Workers crash, queues redeliver, Telegram repeats callbacks, users tap buttons twice. Use natural keys:
create unique index command_effects_uidx
on command_effects (update_id, effect_kind);For external effects such as provisioning or charging, carry an idempotency key derived from the immutable business object, not from a random value generated per attempt. order_01J9XQ6K7M:activate is stable across retries; uuid4() is not.
Control fan-out deliberately
Broadcasting to users is dangerous because one method call per recipient multiplies quickly. You need rate-aware jobs, cancellation, progress tracking, and segmented audiences:
campaign recipients -> batch planner -> rate-limited sender -> delivery ledgerA delivery ledger records recipient, campaign, status, error, and next retry time. Telegram users can block the bot, deactivate accounts, or revoke permissions. Those are terminal states for that recipient, not transient errors worth infinite retries.
Backpressure protects users and infrastructure
When queues grow, choose what degrades. Interactive commands should outrank analytics events. Payment verification should outrank typing indicators. Nonessential edits can be dropped. A bot that tries to do everything eventually does the most important thing late. Useful metrics include queue age, worker retry count, Telegram 429 count, per-chat lag, and dead-letter count. Queue depth alone is misleading; ten thousand cheap typing events are less concerning than fifty stalled payment updates.
Field notes
- Serialize by chat when conversation state can race; serialize globally only when throughput is truly trivial.
retry_afteris authoritative in the response. Treat static rate-limit tables as hints, not guarantees.- Do not retry terminal errors forever: blocked user, chat not found, message not found, and insufficient rights often need state cleanup.
- Dead-letter queues are operational tooling, not a shame bucket. Inspect them and make replay safe.
- Sending typing indicators is cosmetic traffic. During backlog, disable them before user-impacting work.
Was this lesson helpful?