Telegram Bot API Limits in Practice: Handling 429 Retry-After, Queues, and Batching in PHP

When scaling a Telegram bot or launching broadcast notifications, developers inevitably encounter the HTTP 429 Too Many Requests response. Ignoring Telegram Bot API limits leads to lost messages, hung webhooks, and even temporary or permanent bot bans by the platform. In this article, we will examine in detail the official and practical Bot API restrictions, implement proper retry handling in PHP, and design an architecture for an outgoing message queue.

Official and Actual Limits of Telegram Bot API

Telegram imposes strict limits on the number of sent requests. These restrictions are distributed across several levels:

  • Global bot limit: no more than 30 messages per second combined across all chats.
  • Limit per specific private chat: no more than 1 message per second. Sending 2–3 messages in a row to the same user per second will inevitably trigger a 429 error.
  • Limit for groups and channels: no more than 20 messages per minute to a single group or channel.
  • Limit on editing/deleting: frequent calls to editMessageText or deleteMessage fall under the same restriction of 1 request per second per chat.

When any of these thresholds are exceeded, the Telegram server returns an HTTP status 429 and a JSON response containing the parameters.retry_after field, which specifies the number of seconds to wait before retrying the request.

Implementing a cURL Client with Auto-Retry on 429

For reliable interaction with the API, you shouldn't use basic file_get_contents. You must use cURL with explicit header checking, JSON error parsing, and handling of retry_after.

Below is a working example of a request sending function for the Bot API with retry support:

function sendTelegramApiRequest(string $method, array $payload, int $maxRetries = 3): array
{
$botToken = getenv('TELEGRAM_BOT_TOKEN');
if (!$botToken) {
throw new RuntimeException('TELEGRAM_BOT_TOKEN environment variable is missing.');
}

$url = "https://api.telegram.org/bot{$botToken}/{$method}";
$attempt = 0;

while ($attempt < $maxRetries) {
$attempt++;
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 5,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($response === false) {
throw new RuntimeException("cURL error during request to {$method}: {$error}");
}

$decoded = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException("Invalid JSON response from Telegram API: " . json_last_error_msg());
}

if ($httpCode === 429) {
$retryAfter = $decoded['parameters']['retry_after'] ?? 1;
sleep((int)$retryAfter + 1);
continue;
}

if (isset($decoded['ok']) && $decoded['ok'] === true) {
return $decoded;
}

$errorCode = $decoded['error_code'] ?? $httpCode;
$description = $decoded['description'] ?? 'Unknown API error';

return [
'ok' => false,
'error_code' => $errorCode,
'description' => $description,
];
}

return ['ok' => false, 'description' => 'Max retries exceeded due to rate limits'];
}

Outgoing Message Queue Architecture and Throttling

Sending mass broadcasts synchronously directly inside a webhook HTTP request or site controller is the main beginner mistake. Вебхук Telegram expects a 200 OK response within a few seconds. If you delay the response due to bulk sending, Telegram will start resending the same update_ids, triggering a massive request storm.

The correct approach: store sending tasks in a database table or Redis, while a background daemon (Worker) sends them while respecting the limits.

function processOutboundQueue(PDO $pdo): void
{
$stmt = $pdo->prepare("SELECT id, chat_id, payload_json FROM telegram_queue WHERE status = 'pending' ORDER BY id ASC LIMIT 30");
$stmt->execute();
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($messages)) {
return;
}

$updateStatusStmt = $pdo->prepare("UPDATE telegram_queue SET status = :status, error_message = :err, updated_at = NOW() WHERE id = :id");

foreach ($messages as $msg) {
$payload = json_decode($msg['payload_json'], true);
if (!$payload) {
$updateStatusStmt->execute([':status' => 'failed', ':err' => 'Invalid JSON payload', ':id' => $msg['id']]);
continue;
}

$result = sendTelegramApiRequest('sendMessage', $payload);

if ($result['ok']) {
$updateStatusStmt->execute([':status' => 'sent', ':err' => null, ':id' => $msg['id']]);
} else {
$errorCode = $result['error_code'] ?? 0;
$desc = $result['description'] ?? 'Unknown error';

if ($errorCode === 403) {
// Пользователь заблокировал бота — помечаем статус и отключаем активный флаг у профиля
$updateStatusStmt->execute([':status' => 'blocked', ':err' => $desc, ':id' => $msg['id']]);
$deactivateStmt = $pdo->prepare("UPDATE users SET is_active = 0 WHERE telegram_chat_id = :chat_id");
$deactivateStmt->execute([':chat_id' => $msg['chat_id']]);
} else {
$updateStatusStmt->execute([':status' => 'failed', ':err' => $desc, ':id' => $msg['id']]);
}
}

// Задержка ~35 миллисекунд гарантирует соблюдение глобального лимита в 30 собщ/сек
usleep(35000);
}
}

Webhook Validation and Deduplication of Incoming Updates

When processing incoming webhooks, security and protection against duplicate processing (idempotency) play a key role. If handling an incoming event fails with an error, Telegram will retry the request. Therefore, it is necessary to store the update_id and validate the X-Telegram-Bot-Api-Secret-Token header.

function handleTelegramWebhook(PDO $pdo): void
{
$secretHeader = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
$expectedSecret = getenv('TELEGRAM_WEBHOOK_SECRET');

if ($secretHeader !== $expectedSecret) {
http_response_code(403);
echo json_encode(['error' => 'Invalid secret token']);
exit;
}

$input = file_get_contents('php://input');
$update = json_decode($input, true);

if (json_last_error() !== JSON_ERROR_NONE || !isset($update['update_id'])) {
http_response_code(400);
echo json_encode(['error' => 'Invalid update payload']);
exit;
}

$updateId = (int)$update['update_id'];

// Проверка идемпотентности по сохраненным update_id
$checkStmt = $pdo->prepare("SELECT id FROM telegram_processed_updates WHERE update_id = :update_id");
$checkStmt->execute([':update_id' => $updateId]);
if ($checkStmt->fetch()) {
http_response_code(200);
echo json_encode(['ok' => true, 'status' => 'duplicate_ignored']);
exit;
}

// Фиксация входящего update_id
$insertStmt = $pdo->prepare("INSERT INTO telegram_processed_updates (update_id, created_at) VALUES (:update_id, NOW())");
$insertStmt->execute([':update_id' => $updateId]);

// Дальнейшая передача в обработчик бизнес-логики...
http_response_code(200);
echo json_encode(['ok' => true]);
}

What Breaks During Broadcasts and How to Handle It

During large-scale broadcasts, a number of nuances emerge that are not noticeable when testing on single chats:

  1. Increase in 403 Forbidden errors: Between 5% and 20% of the audience during a broadcast may turn out to have blocked the bot. If you continue sending to these users, Telegram considers it spam. You must immediately exclude them from your mailing lists in the DB.
  2. Combining and batching messages: Instead of 5 separate short notifications (e.g., about order status), combine them into a single HTML block using formatting. This preserves the 1 msg/sec limit per user.
  3. Incorrect callback_data length: As a reminder, the callback_data parameter in InlineKeyboardButton is strictly limited to 64 bytes. Using identifiers like lead_id = bin2hex(random_bytes(7)) allows you to save space and link clicks to DB records.
Compliance with Telegram Bot API limits is the key to stable operation of your services without lost notifications or sanctions from the messenger platform.

If you need professional development of scalable bots and Mini Apps without the risk of API bans, the BotCreator team will help bring a project of any complexity to life.

New articles on Telegram

We explain what to automate in your business and how it works in practice. No spam.