Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO connection timed out in API, php-fpm restart solves it

Tags:

php

pdo

I keep getting the following error from my code:

Database connect failed: PDO::__construct(): send of 12 bytes failed with errno=110 Connection timed out

This error persistently happens on an api. If that api keeps getting called a lot during the day this does not happen. Only when the api is not used for some time.

I can solve this by doing a php-fpm restart/reload, but this shouldn't be the solution.

Does anybody have any idea how to solve this?

--EDIT--

This is the code for connection to the database:

public function connectDatabase($allow_persistent = true)
{
    $this->db = null;

    $this->readINI();

    $pdo_attr = [
        PDO::ATTR_PERSISTENT => $allow_persistent,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET CHARACTER SET utf8;",
        PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true,
    ];

    $this->db = new PDO("mysql:host=" . $this->db_data_dbhost . ";dbname=" . $this->db_data_dbname . ";charset=utf8", $this->db_data_username, $this->db_data_password, $pdo_attr);

    $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

To itterate some more, this is used on two API's at the moment.

  • One is consistently used by customers and never encounters this problem
  • The second is not used by a lot of customers yet seeing as this is still in development, it's only with a few customers for testing purposes. We do try to push an app to the appstore but it gets shot down by this problem. This API will eventually run into the error as depicted above and will not recover from this state without restarting/reloading the php-fpm service.
like image 725
Wouter Avatar asked Oct 18 '22 10:10

Wouter


1 Answers

Using persistant connections is not that good (see why), but still, to solve this you may want to increase MySQL connections timeout.

To achieve this, see wait_timeout parameter for my.ini.

p.s. Also, you can catch this error and just reconnect to the database.

like image 85
Abraham Tugalov Avatar answered Oct 23 '22 21:10

Abraham Tugalov