Telegram Bot API rate limits and why naive loops crash
Most developers start implementing broadcasts with a simple database query and an iterative loop calling the sendMessage endpoint. While this works effortlessly on a local development setup with ten test accounts, running it against thousands of real subscribers fails immediately. The application either freezes completely or gets throttled by Telegram Bot API anti-spam defenses.
Telegram protects its infrastructure with strict rate limits. The baseline constraints are straightforward: a bot cannot send more than one message per second to a single private chat, and should not exceed roughly 30 messages per second across all chats combined. Group chats are even stricter, capped at approximately 20 messages per minute. Breaching these limits triggers immediate request rejection from the API.
A naive synchronous loop also creates severe concurrency bottlenecks. Executing HTTP requests sequentially turns a broadcast to a large user base into hours of idle waiting. Conversely, spawning unconstrained threads or goroutines exhausts OS socket handles and triggers an avalanche of throttling errors. A reliable broadcast architecture strictly decouples job submission from message dispatch.
- Per-chat threshold: at most one message per second to any single private user conversation.
- Global bot throughput: a safe operational ceiling of 25 to 30 messages per second across all chats.
- Group and channel limits: approximately 20 messages per minute in a single group to prevent feed spam.
- Socket exhaustion: uncontrolled concurrency drains available network file descriptors and triggers IP throttling.
Handling HTTP 429 retry_after and 403 user blocks
In any large-scale notification system, errors are a certainty rather than an exception. A resilient architecture must classify HTTP response codes and adjust its delivery pace dynamically. The most frequent operational signal is HTTP 429 Too Many Requests. When returning a 429, Telegram includes a JSON payload containing the retry_after field, which specifies the exact number of seconds the bot must wait.
When a worker encounters a 429 error, it must immediately pause further dispatch for the specified duration plus a small randomized jitter. Continuing to bombard the API during a cooldown period prolongs the penalty window or risks temporary token suspension. The worker must re-queue the task with an updated execution timestamp and yield control to avoid blocking the pipeline.
The second critical category is HTTP 403 Forbidden. This response typically indicates that the bot was blocked by the user or the target account was deactivated. Retrying delivery to these users is pointless and wastes valuable rate limit quota. The application must update the subscriber record immediately, setting the active status to false and recording the timestamp of the block.
- HTTP 429 Too Many Requests: read the retry_after value, suspend dispatch, and re-queue the task with delayed execution.
- HTTP 403 Forbidden (bot blocked): flag the user as inactive immediately and record the unsubscription event.
- HTTP 400 Bad Request (chat not found): mark the user identifier as invalid and purge it from future broadcast batches.
- HTTP 5xx Server Error: transient Telegram data center outage; back off exponentially and retry safely.
- Network timeouts: lost responses require idempotent verification before re-attempting delivery.
Worker pool and queue architecture in Go
At Anaxita, we build high-throughput Telegram broadcasting systems using an asynchronous pipeline in Go. Creating a broadcast campaign in an admin panel only writes metadata and target criteria to the database. Actual message delivery is handled by a background worker pool reading from a persistent queue. For a deep dive into these patterns, see our guide on background jobs and queues in Go.
The core pipeline consists of a batch dispatcher, a global rate limiter, and a pool of worker goroutines. The dispatcher fetches subscriber batches from PostgreSQL using FOR UPDATE SKIP LOCKED. This locking mechanism enables horizontal scaling across multiple service instances without the risk of duplicate delivery. For webhook management and connection considerations, check webhook or long polling.
The rate limiter uses a token bucket or leaky bucket algorithm configured to a sustained limit of 25 to 30 tokens per second. Workers must acquire a token before making an outgoing HTTP call. If any worker encounters an HTTP 429 response, the rate limiter freezes token distribution globally for the specified retry_after interval, protecting the entire system from cascading failures.
- Persistent database queue: every message delivery task is stored on disk and survives server crashes or restarts.
- Global rate limiter: a centralized token bucket enforces the safe threshold of 25 to 30 requests per second.
- Fixed worker pool: a bounded set of goroutines maintains predictable CPU and network socket utilization.
- Exponential backoff: progressive delays between retries prevent infrastructure overload during transient network glitches.
Idempotency and preventing duplicate broadcasts
Sending duplicate marketing or notification messages is one of the quickest ways to lose audience trust and trigger spam reports. Duplicates typically occur when network connections fail silently: a worker sends a sendMessage request, Telegram delivers it to the user, but the HTTP 200 response drops before reaching your server. If the worker retries naively, the subscriber receives the identical message twice.
Because the Telegram Bot API sendMessage method does not natively accept client-provided idempotency keys, duplicate prevention must be enforced inside your database architecture. We cover the foundational patterns in our guide to API idempotency and retries. For broadcasts, the system creates a composite unique constraint combining the campaign identifier and the subscriber ID: campaign_id + user_id.
Each delivery item transitions through a strict state machine: pending, processing, sent, failed, or blocked. Transitioning a record to processing occurs in an atomic database transaction prior to the network call. If a worker process terminates unexpectedly, a background watchdog detects abandoned processing tasks and schedules safe recovery.
- Composite unique constraint: a UNIQUE(campaign_id, user_id) database rule completely prevents duplicate job creation.
- Atomic status locking: tasks are marked as processing before issuing the HTTP call to the Bot API.
- Storing message identifiers: recording the returned message_id enables post-broadcast editing or deletion if needed.
- Watchdog for stalled tasks: tasks remaining in processing longer than a safety threshold trigger automated reconciliation.
Audience segmentation and timezone scheduling
Blasting an identical message to an entire subscriber base creates notification fatigue and accelerates churn. Effective broadcast campaigns rely on granular audience segmentation. Delivering tailored content that matches a user's recent interactions dramatically improves engagement and protects the bot from user blocks.
Common segmentation parameters include language preference, purchase history, tags, and conversation state. If a customer is currently in the middle of a checkout process or support inquiry, sending an unrelated marketing broadcast breaks the flow. For strategies on keeping dialogue state separate from notification flows, see bot conversation state.
Timezone scheduling is equally critical for audience retention. Receiving a loud marketing notification in the middle of the night inevitably prompts subscribers to mute or block the bot. Storing the user's timezone allows the dispatch scheduler to deliver broadcasts strictly within a comfortable daytime window (for example, between 09:00 and 21:00 local time).
User consent, opt-out mechanisms, and bot reputation
Telegram closely monitors user behavior and spam complaints. When a noticeable percentage of recipients block a bot or tap 'Report Spam' after receiving a broadcast, Telegram may restrict the bot's messaging capabilities or permanently revoke its API token. Safeguarding your bot's reputation requires explicit user consent and effortless opt-out mechanisms.
Subscribers should explicitly opt in to different messaging categories during bot onboarding or via a preferences menu. Distinguish strictly between transactional notifications (order updates, verification codes) and promotional broadcasts (discounts, product announcements). Transactional messages should always be delivered, while marketing communications must remain strictly optional.
Every promotional broadcast should feature an inline button allowing the recipient to unsubscribe or adjust notification preferences with a single tap. The button triggers an inline callback query that instantly sets the marketing subscription flag to false in the database. When users can opt out effortlessly, they do not resort to blocking the bot or reporting it for spam.
- Notification tier separation: distinct database flags for mandatory transactional alerts versus optional marketing campaigns.
- One-tap inline opt-out: inline keyboard buttons allowing immediate unsubscription without leaving the chat.
- Block rate monitoring: a rising share of users who block the bot after a broadcast indicates urgent need for content and frequency revisions.
- Zero re-engagement: strict enforcement preventing promotional follow-ups to users who opted out.
Delivery reports, metrics, and when custom broadcast pays off
A production-grade broadcast pipeline must provide end-to-end delivery visibility. Operators and marketing teams need real-time telemetry beyond a simple progress bar: total messages queued, delivered successfully, bounced due to user blocks, and current delivery throughput per minute. Aggregating these metrics in a relational database allows clean auditability and ongoing list hygiene.
Building a custom Go broadcast engine is the right architectural choice for businesses with large audiences, personalized data payloads, CRM synchronization, and strict uptime requirements. Anaxita specializes in designing these resilient backends; explore our Telegram bot development services. When sending individualized invoices, appointment reminders, or proprietary content, off-the-shelf marketing tools lack the necessary security and reliability.
However, not every messaging requirement calls for custom code. For one-to-many public announcements without personalization, a standard Telegram channel is far more efficient. Channels deliver updates across Telegram's global CDN with zero Bot API rate limits. For early-stage validation with a small subscriber base, no-code automation platforms can be sufficient, as explored in n8n vs custom code.
- Telegram Channel: optimal for public broadcasts and broad announcements; zero Bot API throttling and zero server load.
- No-code builders: suitable for small prototype audiences and simple triggers during initial MVP validation.
- Custom Go microservice: essential for large audiences, personalized payloads, CRM integration, and enterprise-grade reliability.