When scaling a service or launching marketing campaigns, Telegram bot developers inevitably face Bot API rate limits. A simple sendMessage call in a loop quickly leads to HTTP 429 (Too Many Requests) errors, temporary IP address blocks, and system log overflows. In this article, we will break down official and unofficial лимиты Telegram, write a reliable PHP HTTP client with retry_after handling, and build an outgoing message queue architecture supporting batching.
1. Anatomy of Telegram Bot API Limits: Chats, Groups, and Global Thresholds
Telegram imposes limits at several levels. Ignoring any of them causes a cascading failure across the entire message delivery system:
- Global bot limit: no more than 30 messages per second across all chats combined.
- Direct chat with a user: no more than 1 message per second. Sending two consecutive messages a few milliseconds apart might work, but a long stream will trigger a 429 error.
- Groups and supergroups: no more than 20 messages per minute to the same chat.
- Массовые рассылки: recommended speed when broadcasting to different users is no more than 25–30 messages per second to avoid triggering the server's spam filters.
If a bot exceeds a limit, the Telegram server returns an HTTP status code 429 Too Many Requests with a JSON response containing the parameters.retry_after parameter. This parameter specifies how many seconds the bot must delay sending requests to the API.
Important: If you continue sending requests during the
retry_afterperiod, Telegram will increase the penalty delay time, and repeated violations will result in a temporary IP address block.
2. Custom cURL Client for Handling 429 Retry-After
The standard approach of immediately retrying on error is harmful. We need HTTP-клиент that can extract the delay time from Telegram's response and throw a specialized exception for the business logic layer.
<?php
declare(strict_types=1);
class TelegramRateLimitException extends RuntimeException
{
private int $retryAfter;
public function __construct(int $retryAfter, string $message = '')
{
parent::__construct($message, 429);
$this->retryAfter = $retryAfter;
}
public function getRetryAfter(): int
{
return $this->retryAfter;
}
}
class TelegramApiException extends RuntimeException {}
class TelegramApiClient
{
private string $token;
public function __construct(?string $token = null)
{
$this->token = $token ?? (string) getenv('TELEGRAM_BOT_TOKEN');
if (empty($this->token)) {
throw new InvalidArgumentException('TELEGRAM_BOT_TOKEN не задан в окружении');
}
}
public function request(string $method, array $params = []): array
{
$url = 'https://api.telegram.org/bot' . $this->token . '/' . $method;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 5,
]);
$response = curl_exec($ch);
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr = curl_error($ch);
curl_close($ch);
if ($response === false) {
throw new RuntimeException("Ошибка cURL: {$curlErr}");
}
$decoded = json_decode((string) $response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Некорректный JSON в ответе Telegram API');
}
if ($httpCode === 429) {
$retryAfter = (int) ($decoded['parameters']['retry_after'] ?? 1);
throw new TelegramRateLimitException(
$retryAfter,
"Превышен лимит запросов. Retry after {$retryAfter} sec"
);
}
if (empty($decoded['ok'])) {
$description = $decoded['description'] ?? 'Неизвестная ошибка';
$errorCode = (int) ($decoded['error_code'] ?? $httpCode);
throw new TelegramApiException($description, $errorCode);
}
return $decoded['result'] ?? [];
}
}
3. Outgoing Message Queue Architecture with Redis Rate Limiter
To guarantee delivery without blocks, all outgoing messages should not be sent synchronously within the Webhook HTTP thread, but placed into a queue (RabbitMQ, Redis, Beanstalkd, Laravel Queue, Yii Queue). The queue worker must comply with rate limits using time-based Redis locks (sliding window / token bucket).
<?php
declare(strict_types=1);
class QueueProcessor
{
private TelegramApiClient $client;
private Redis $redis;
public function __construct(TelegramApiClient $client, Redis $redis)
{
$this->client = $client;
$this->redis = $redis;
}
public function processOutboundJob(array $jobData): bool
{
$chatId = (int) $jobData['chat_id'];
$text = (string) $jobData['text'];
// 1. Проверяем глобальную паузу бота (если ранее был 429)
if ($this->redis->exists('tg:global_pause')) {
$ttl = (int) $this->redis->ttl('tg:global_pause');
sleep(max(1, $ttl));
}
// 2. Лимит 1 сообщение в секунду на один конкретный чат
$lastSentKey = "tg:chat_last_sent:{$chatId}";
$lastSent = (float) $this->redis->get($lastSentKey);
$now = microtime(true);
if (($now - $lastSent) < 1.0) {
$sleepMs = (int) ((1.0 - ($now - $lastSent)) * 1000000);
usleep($sleepMs);
}
try {
$this->client->request('sendMessage', [
'chat_id' => $chatId,
'text' => $text,
'parse_mode' => 'HTML',
]);
$this->redis->set($lastSentKey, (string) microtime(true), ['ex' => 5]);
return true;
} catch (TelegramRateLimitException $e) {
// Устанавливаем глобальный флаг паузы для всех воркеров
$this->redis->set('tg:global_pause', '1', ['ex' => $e->getRetryAfter()]);
return false; // Возвращаем job обратно в очередь с задержкой
} catch (TelegramApiException $e) {
// Если пользователь заблокировал бота или удалил аккаунт (403 / 400)
if ($e->getCode() === 403 || str_contains($e->getMessage(), 'bot was blocked')) {
$this->deactivateUser($chatId);
return true; // Задача выполнена (удаляем из очереди)
}
throw $e;
}
}
private function deactivateUser(int $chatId): void
{
// Логика отключения активности пользователя в базе данных
// UPDATE users SET is_active = 0 WHERE telegram_id = :chatId
}
}
4. Batching and Combining Notifications for a Single Chat
A common mistake is sending multiple service messages in a row when an order status changes or a series of events occurs. Instead of sending 5 separate messages in 3 seconds (which triggers a 429 at the chat level), you should accumulate events in a buffer and combine them into a single text block.
<?php
declare(strict_types=1);
class NotificationBufferManager
{
private Redis $redis;
private TelegramApiClient $client;
public function __construct(Redis $redis, TelegramApiClient $client)
{
$this->redis = $redis;
$this->client = $client;
}
public function pushNotification(int $chatId, string $eventText): void
{
$key = "tg:buffer:{$chatId}";
$this->redis->rPush($key, $eventText);
$this->redis->expire($key, 60); // Буфер живет 1 минуту
}
public function flushBuffer(int $chatId): void
{
$key = "tg:buffer:{$chatId}";
$events = [];
while ($item = $this->redis->lPop($key)) {
$events[] = (string) $item;
}
if (empty($events)) {
return;
}
// Группируем события в одно текстовое сообщение
$header = "<b>Обновления по вашему заказу:</b>
";
$lines = array_map(fn($e) => "• " . htmlspecialchars($e, ENT_QUOTES, 'UTF-8'), $events);
$fullText = $header . implode("
", $lines);
// Соблюдаем максимальную длину sendMessage в 4096 символов
$chunks = str_split($fullText, 4000);
foreach ($chunks as $chunk) {
try {
$this->client->request('sendMessage', [
'chat_id' => $chatId,
'text' => $chunk,
'parse_mode' => 'HTML',
]);
} catch (TelegramApiException $e) {
// Обработка ошибок при доставке
}
}
}
}
5. Typical Issues in Mass Mailings
Mass mailings are the main source of errors when working with the Bot API. Below are critical issues that break message delivery:
- Unhandled 403 Forbidden status code: The user has blocked the bot or stopped the conversation. Attempting to resend wastes API quota. Upon receiving 403, you must immediately mark the user in the database as inactive (
is_active = 0) and exclude them from future broadcasts. - Worker crashing due to out-of-memory errors: Running a broadcast for 50,000 subscribers in a single script causes memory leaks. Use iterators (yield/cursor) when reading from the database and restart workers once the processed task limit is reached.
- Uncontrolled concurrency: Running 10 queue workers without a shared lock (Redis Lock) will guaranteed exceed the global limit of 30 messages per second.
If you need professional development of fault-tolerant Telegram-бот s and Mini Apps of any complexity, contact the specialists at BotCreator.