Detect Slow Database Requests in Laravel
Have you ever optimized a slow SQL query but found that your page was still taking too long to load?
Sometimes, the problem isn't one query. It's the combined execution time of multiple database queries.
Laravel provides DB::whenQueryingForLongerThan() to help detect this situation.
Monitor Cumulative Query Time
You can configure this in your AppServiceProvider:
use Illuminate\Database\Connection;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
public function boot(): void
{
DB::whenQueryingForLongerThan(
500,
function (
Connection $connection,
QueryExecuted $event
) {
logger()->warning(
'Database query time exceeded the threshold.',
[
'sql' => $event->sql,
'time' => $event->time,
]
);
}
);
}
Here, 500 represents 500 milliseconds of cumulative database query time for the request.
When the threshold is exceeded, Laravel invokes the callback with the database connection and the query event that triggered the threshold.
Why Is This Useful?
Imagine a dashboard that runs several queries:
- Fetching total sales
- Loading recent orders
- Calculating monthly revenue
- Retrieving customer statistics
Each query might be reasonably fast, but their combined execution time can still affect performance.
This monitoring helps you identify requests that spend too much time interacting with the database.
Log More Information
You can capture the query and its execution time for debugging:
logger()->warning('Slow database activity detected', [
'query' => $event->sql,
'bindings' => $event->bindings,
'query_time_ms' => $event->time,
]);
Be careful when logging bindings because they may contain sensitive data. In production, consider sending a sanitized alert to your monitoring system instead.
When Should You Use It?
This feature is useful for:
- Monitoring admin dashboards
- Investigating slow API endpoints
- Detecting excessive database activity
- Finding requests that need query optimization
- Alerting developers about performance regressions