Building High-Concurrency Telegram Webhooks with PHP: Architecture Deep Dive #
When your Telegram bot grows from a few hundred users to hundreds of thousands of daily interactions, traditional synchronous webhook handling starts to crack. Users experience delayed message delivery, timeouts appear in the Telegram Webhook Info, and your server CPU spikes.
In this architectural deep dive, we explore how to optimize your PHP webhooks for sub-50ms execution times and massive concurrency.
The Rule of Fast Webhooks: Acknowledge First #
The golden rule of high-scale Telegram webhooks is:
Acknowledge Telegram with HTTP 200 OK as fast as possible.
Do not perform heavy operations (such as generating AI completions, sending multi-recipient broadcasts, or downloading 20MB voice files) directly inside the incoming HTTP thread.
The Fast-Response Architecture #
User Message
│
▼
Telegram API Server
│ (HTTPS POST)
▼
[Botlify Webhook Gateway] ────▶ [Fast HTTP 200 OK + Connection Close]
│
▼
[Async Background Task / Queue]
│
▼
[Bot Business Logic & Telegram API Reply]Technique 1: Utilizing FastCGI fastcgifinishrequest() #
If your PHP server runs PHP-FPM (like Botlify's container infrastructure), you can instantly flush the HTTP 200 status back to Telegram and continue processing in the background:
<?php
// Receive payload
$input = file_get_contents('php://input');
$update = json_decode($input, true);
// Send HTTP 200 OK immediately to release Telegram connection
http_response_code(200);
echo json_encode(['ok' => true]);
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request(); // Telegram receives response immediately!
}
// Now you can safely run longer background operations:
processHeavyBotLogic($update);Technique 2: Webhook Secret Token Verification #
In Telegram Bot API 6.1+, you can set a secret token via setWebhook:
curl -F "url=https://botlify.cloud/webhook.php" \
-F "secret_token=my_super_secret_token_abc123" \
https://api.telegram.org/bot<TOKEN>/setWebhookIn your PHP webhook, verify this token instantly before doing anything else:
$secret = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
if ($secret !== 'my_super_secret_token_abc123') {
http_response_code(403);
exit('Unauthorized access.');
}This prevents unauthorized third-party requests and bots from hitting your backend endpoints.
Technique 3: Connection Reuse with cURL Keep-Alive #
Making a new TLS connection to api.telegram.org for every single message consumes 100-200ms in SSL handshake overhead. Reusing your cURL handle or using persistent HTTP connections speeds up message delivery by 400%:
function telegram_request(string $method, array $params = []): array
{
static $ch = null;
$token = getenv('BOT_TOKEN');
$url = "https://api.telegram.org/bot{$token}/{$method}";
if ($ch === null) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_TCP_KEEPALIVE => 1,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
]);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
$res = curl_exec($ch);
return json_decode((string)$res, true) ?: [];
}Conclusion #
By adopting fastcgifinishrequest(), verifying secret tokens, and reusing persistent cURL connections, your PHP Telegram bots can comfortably handle thousands of concurrent requests with rock-solid stability.