Hi @SandeepDeb ,
The “Connection refused (2002)” error in Cloud SQL for MySQL typically indicates network instability, connection exhaustion, or resource limitations, rather than a SQL syntax issue. Since it occurs intermittently, the root cause is often connection leaks in Laravel, inefficient database usage, or Cloud SQL constraints. Addressing these factors systematically can resolve the issue.
Laravel does not maintain a traditional persistent connection pool; instead, it establishes a new database connection per request and reuses it within that lifecycle. The most common cause of connection issues is connection leaks, where connections remain open due to improper handling. Laravel’s Query Builder and Eloquent ORM automatically manage connections, but if using DB::connection(), ensure explicit disconnection:
DB::connection()->disconnect();
For high-traffic applications experiencing frequent reconnections, enabling persistent connections may help:
'options' => [PDO::ATTR_PERSISTENT => true],
Instead of blindly increasing max_connections, monitoring connection usage and query performance is key. Using Laravel’s query listener can help identify long-running queries that may be holding connections open longer than necessary:
DB::listen(function ($query) { Log::info($query->sql); });
Cloud SQL enforces limits on connections, CPU, and memory, which can lead to connection refusals if thresholds are exceeded. Monitoring active connections using:
SHOW STATUS WHERE variable_name = 'Threads_connected';
and checking aborted connections with:
SHOW GLOBAL STATUS LIKE 'Aborted_connects';
can provide real-time insights. Additionally, enabling the slow query log helps identify inefficient queries:
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 2;
Additionally, TCP keep-alives should be configured at the OS level to prevent premature connection drops:
sysctl -w net.ipv4.tcp_keepalive_time=120
For deeper inspection, checking active network connections with:
netstat -an | grep 3306
or detecting query locks via:
SHOW ENGINE INNODB STATUS;
can reveal performance bottlenecks. If connection churn remains an issue, ProxySQL can be implemented to efficiently manage and pool database connections, reducing the load on Cloud SQL.