I'm running a Laravel application hosted on an AWS EC2 instance, using Apache2 as the web server. The setup includes an AWS Application Load Balancer (ALB) directing traffic to the EC2 instance.
Issue: I've observed that database connections to my MySQL database are not closing as expected, leading to an accumulation of open connections. This eventually results in the "Too many connections" error, causing service disruptions.
Details:
Laravel Version: 10.48.28
PHP Version: 8.2
Database: MySQL 8.0.39 (AWS RDS)
Server OS: Ubuntu 24.04 LTS
Configurations Checked:
Database Configuration in Laravel:
Ensured that PDO::ATTR_PERSISTENT is set to false in config/database.php. Verified that the wait_timeout and interactive_timeout settings in MySQL are appropriately configured to prevent long-lived idle connections. Apache2 Settings:
Confirmed that KeepAlive is set to Off in the Apache configuration to prevent persistent HTTP connections that might hold database connections open. AWS ALB Configuration:
Reviewed the ALB's idle timeout settings to ensure they are not excessively long, which could contribute to lingering connections. Observations:
Despite the above configurations, the issue persists. Monitoring tools indicate a growing number of sleeping MySQL connections over time.
One similar problem I encountered was that target groups have a setting for health checks, and the load balancer will access the health check route from time to time.
If your laravel's SESSION_DRIVER
env is set to database
, then your db's sessions
table would accumulate with those health check sessions.
I'm not sure if the connection will remain for the ELB request, but I still think it might be worth looking into it. Here's a neat implementation to ignore bots' session being stored into the database with the following implementation.
https://stackoverflow.com/a/49310249/10849089
Laravel 11 has a health check route by default as mentioned here.