I built a Telegram bot using PHP that works with webhooks. Every time there’s an update, my PHP script gets called. Right now I’m using curl to send JSON requests to the Telegram API, but the response time is really slow - about 1 second per message.
I think the problem is that curl creates a new connection each time and then closes it when the PHP script ends. I also made a Java version that uses the getUpdate method every 5 seconds, and it’s much faster at around 500ms because it keeps the connection alive.
Is there a way to make my PHP bot faster like the Java one? Can I somehow keep the connection open between different PHP script executions?
your DNS lookups might be the problem - try using telegram’s server IP instead of the hostname. also check if your host has connection limits or throttling. i switched from curl to guzzle http client and saw massive improvements since it handles connection pooling automatically.
Connection overhead is killing your performance. I had the same issue with a PHP bot and got my response times down to around 300ms. Add CURLOPT_TCP_KEEPALIVE and set CURLOPT_FORBID_REUSE to false - this’ll reuse connections instead of opening new ones every time. ReactPHP’s HTTP client is worth checking out too since it handles async operations and persistent connections really well. You could also set up a queue system - instead of hitting the API directly from your webhook, dump the message into a database or Redis queue and have a separate PHP process handle the actual sending with a persistent connection.
The webhook approach might be your bottleneck. I hit the same performance wall and switched to a hybrid setup that fixed everything. Don’t process stuff synchronously in the webhook handler - just acknowledge the request immediately and queue the work instead. Then run a separate PHP daemon with ReactPHP that chews through the queue and keeps persistent connections to Telegram’s API. My webhook now responds under 50ms and the real processing happens async with reused connections. Also try enabling HTTP/2 in curl (CURLOPT_HTTP_VERSION to CURL_HTTP_VERSION_2_0) if your server supports it. Telegram handles HTTP/2 well and it cuts connection overhead big time.