Repository navigation
First-class slow query detection and callbacks in Laravel #61649
|
I think Laravel could benefit from a first-class way to detect slow database queries without having to manually register a listener and implement the threshold logic in every application. For example, something like: DB::whenQueryExceeds(500, function ($query) { Or perhaps: DB::slowQueries(500)->each(function ($query) { The goal would be to make it easy to detect queries that exceed a configurable execution time. Why? Currently, applications often need to implement this themselves using DB::listen(): DB::listen(function ($query) { This works, but the threshold logic, environment checks, logging and monitoring integration tend to be duplicated across projects. A first-class API could make this easier while remaining completely opt-in. Potential use cases: Log queries slower than a specific threshold. Send slow-query information to an observability platform. Detect performance regressions in production. Configure different thresholds per connection. Enable it only in specific environments. For example: DB::whenQueryExceeds( Would something like this make sense as a framework-level feature, or is DB::listen() intentionally considered sufficient for this use case? |
Replies: 1 comment
|
I think this would make sense as a framework-level API, especially if it builds on top of the existing query event/listener infrastructure rather than introducing a separate mechanism. One thing that could make the API useful beyond For example: DB::whenQueryingForLongerThan(500, function ($connection, $event) {
// ...
});This could also avoid exposing threshold logic to every application while keeping the callback opt-in. It might be worth considering whether the callback should receive the connection as well as the query event, since applications may want different monitoring behavior depending on which database connection produced the slow query. The main advantage I see is having the threshold detection handled consistently by the framework, while |
I think this would make sense as a framework-level API, especially if it builds on top of the existing query event/listener infrastructure rather than introducing a separate mechanism.
One thing that could make the API useful beyond
DB::listen()is supporting both a global threshold and per-connection thresholds.For example:
This could also avoid exposing threshold logic to every application while keeping the callback opt-in.
It might be worth considering whether the callback should receive the connection as well as the query event, since applications may want different monitoring behavior depending on whi…