Tuesday, July 25, 2017

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

Leave a Comment

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.

2 Answers

Answers 1

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.

Answers 2

Errno 110 appears to be for sockets in general (e.g. here, here, and here). To fix it, you probably will need to check server connections (what happens with ping?)

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment