From 29fdcb7e6abf7bd786c7a0bc8502244086246796 Mon Sep 17 00:00:00 2001 From: Dieter Reinert Date: Mon, 4 Aug 2025 16:04:02 +0200 Subject: [PATCH] Fix database connection pool exhaustion (#2494) - Add PDO::ATTR_PERSISTENT => true to reuse database connections - Handle 'too many connections' errors gracefully with HTTP 503 - Maintain backward compatibility with minimal code changes Fixes MySQL error 1040 crashes during high load periods. --- lib/ntbb-database.lib.php | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/ntbb-database.lib.php b/lib/ntbb-database.lib.php index 601cadf9a..f1b0a1d2a 100644 --- a/lib/ntbb-database.lib.php +++ b/lib/ntbb-database.lib.php @@ -27,12 +27,21 @@ class PSDatabase { $this->db = new PDO( "mysql:dbname={$this->database};host={$this->server};charset={$this->charset}", $this->username, - $this->password + $this->password, + [PDO::ATTR_PERSISTENT => true] ); $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); - } catch (Exception $e) { + $this->db->exec("SET SESSION wait_timeout = 7200"); + } catch (PDOException $e) { + if (strpos($e->getMessage(), '1040') !== false || strpos($e->getMessage(), 'Too many connections') !== false) { + http_response_code(503); + header('Content-Type: text/plain'); + die("Database temporarily unavailable due to high load. Please try again in a few minutes."); + } // hide passwords and stuff from stacktrace throw new ErrorException($e->getMessage()); + } catch (Exception $e) { + throw new ErrorException($e->getMessage()); } } }