I have a chatbot that works on a callback api, which sends a request on my server every time someone writes a message
Recently, I have read of so-called persistent connections, that made me think that I can avoid reconnecting to database each time I get a request on my server, because the database loading takes some time and I would like to speed up that process
So, I've changed any connection in my script to have a p:
prefix, like this
$conn = new mysqli("p:".$servername, $username, $password, $dbname);
As I've understood, this way mysqli finds an existing connection with same parameters or creates one if it doesn't exist, instead of opening a new connection every time
But still, a couple of hours later I've checked open connections and I've noticed bunch of similar connections, different only by their ID
, like this
ID | USER | HOST | DB | COMMAND | TIME | STATE | INFO |
+---------+------+-----------+----------+---------+------+-------+------+
| 5248403 | user | localhost | database | Sleep | 24 | | NULL |
| 5248609 | user | localhost | database | Sleep | 113 | | NULL |
| 5247822 | user | localhost | database | Sleep | 1 | | NULL |
| 5248652 | user | localhost | database | Sleep | 79 | | NULL |
(with user
and database
masking actual user and database)
Is there something that I've misunderstood about persistent connections? What can I do to avoid similar connections?
A textbook XY problem
the database loading takes some time and I would like to speed up that process
I have a feeling that a persistent connection would have been the last option to solve your problem, if any.
As I've understood, this way mysqli finds an existing connection with same parameters or creates one if it doesn't exist, instead of opening a new connection every time
It is actually far from that. A persistent connection in PHP is bound to a number of threads PHP executes in. And each thread which happen to open a connection will hold it open further, providing this already opened connection for the scripts it is going to execute. Means a persistent connection is persistent, or in other words, a persistently open.
Hence, the picture you can see is expected.
As long as you don't run into "Too many connections" error it is all right, though I doubt thee is a measurable benefit in using a persistent connection.