Certainly! Here’s a step-by-step approach to track down what’s causing the spike in database connections in your Laravel app running on Vapor with AWS RDS:
1. Enable Laravel Query Logging
While Laravel logs queries, it does not log connection creation by default. However, you can listen for connection events.
Add the following to your AppServiceProvider's boot() method:
use Illuminate\Database\Events\ConnectionEstablished;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
public function boot()
{
Event::listen(ConnectionEstablished::class, function ($event) {
Log::info('Database connection established', [
'connection' => $event->connectionName,
'time' => now(),
'request' => request()->fullUrl() ?? 'N/A',
'user_id' => auth()->id() ?? 'guest',
]);
});
}
This will log every time a new DB connection is established, along with some context.
2. Check for Persistent Connections
If you’re using Laravel Vapor, make sure you’re using serverless drivers and not persistent connections. Persistent connections can cause connection spikes in serverless environments.
Check your .env:
DB_CONNECTION=serverless
3. Monitor RDS
AWS RDS provides Enhanced Monitoring and Performance Insights. Use these tools to:
- See which queries are running
- View the source of connections (IP, user, etc.)
- Check for long-running or idle connections
4. Check Laravel Queue Workers & Jobs
If you have many queue workers or scheduled jobs, each may open a new connection. Review your Vapor queue configuration and scale settings.
5. Review Code for Unclosed Connections
Ensure you’re not manually opening connections and forgetting to close them. Laravel handles this automatically, but custom code or packages might not.
6. Check for Health Checks or Bots
Sometimes, health checks or bots can cause a spike in connections if they hit endpoints that trigger DB queries.
7. Summary
- Log connection events in Laravel (see code above)
- Use AWS RDS monitoring tools
- Review your queue and job scaling
- Ensure you’re using the correct DB driver for serverless
- Check for code or endpoints causing excessive connections
By logging connection events and correlating with RDS monitoring, you should be able to pinpoint what’s causing the spike.