Start free trial
Start free trial Log in

14-day free trial. No credit card.

How to Monitor Slow Queries in Laravel Production

Three layers (database slow logs, Laravel query hooks, and a proper APM) and when each is the right tool.

  • Guide
  • 3 min read

How do I find slow queries in Laravel?

Use Laravel's DB::whenQueryingForLongerThan() to flag requests whose total query time crosses a threshold, enable your database's slow query log (MySQL's slow_query_log or Postgres's log_min_duration_statement) as a safety net, and install an APM that groups queries by normalized fingerprint and tracks p95 duration per pattern. NightOwl records every query each request runs, groups them by pattern with their P95, and points each call to the file and line that ran it.

Updated

Slow queries are the most common reason a Laravel app gets slower as it succeeds. The query that returned instantly against a few hundred rows in development is the same query scanning two million rows in production, and nothing in your code changed. The data did. That's the frustrating shape of database performance: it degrades gradually, on a curve you can't see from the code, until a page that was always fine crosses a threshold and starts timing out. Catching it early is entirely about measurement, because you can't reason your way to which query grew.

Layer 1: Database slow-query log

Your database already knows which queries were slow. Turn the log on as a baseline.

PostgreSQL (postgresql.conf)

ini
log_min_duration_statement = 500  # log anything over 500ms
log_line_prefix = '%m [%p] %q%u@%d '
log_statement = 'none'

MySQL (my.cnf)

ini
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 0.5
log_queries_not_using_indexes = 1

It's cheap and it sees every query, but it has no request context: you get the SQL but not which controller fired it or what the user was doing. Useful for capacity planning and index design; not actionable for "the /orders page is slow."

Layer 2: Laravel query hooks

Laravel gives you two hooks in AppServiceProvider::boot().

Fire once per request when total query time exceeds 500ms

php
use Illuminate\Support\Facades\DB;

DB::whenQueryingForLongerThan(500, function ($connection, $event) {
    logger()->warning('Slow request: SQL queries exceeded 500ms', [
        'url' => request()->fullUrl(),
        'method' => request()->method(),
        'user_id' => auth()->id(),
    ]);
});

Fire on every query (keep the callback cheap)

php
DB::listen(function ($query) {
    if ($query->time < 100) return;

    logger()->warning('Slow query', [
        'sql' => $query->sql,
        'bindings' => $query->bindings,
        'time_ms' => $query->time,
        'connection' => $query->connectionName,
    ]);
});

DB::listen runs for every query. At 1,000 req/sec with 10 queries per request, that's 10,000 callback invocations per second. Keep the callback cheap (never write to the database or call the network from it) and prefer the whenQueryingForLongerThan variant for production-facing logic.

Layer 3: Full APM with pattern grouping

The real unlock is grouping queries by fingerprint. A raw log says "this query took 800ms at 14:23." Pattern grouping says "this query pattern has fired 840,000 times today with a p95 of 640ms, up from 90ms yesterday."

Laravel already sends bound values as ? placeholders, so queries from the same line of code usually share one SQL string. Nightwatch's fingerprint is a hash of the connection name and that SQL, with in (...) lists and insert values collapsed so a different number of items doesn't split the group. Literals the query builder writes straight into the SQL, like the limit, stay as they are:

sql
-- SQL Laravel sends (the values travel separately as bindings):
select * from "orders" where "user_id" = ? and "status" in (?, ?) order by "created_at" desc limit 10
select * from "orders" where "user_id" = ? and "status" in (?, ?, ?) order by "created_at" desc limit 10

-- Both roll up into one pattern, hashed as:
select * from "orders" where "user_id" = ? and "status" in (...?) order by "created_at" desc limit 10

-- A different limit is a separate pattern:
select * from "orders" where "user_id" = ? and "status" in (?, ?) order by "created_at" desc limit 25

Options that do this out of the box:

  • Laravel Nightwatch Cloud: official
  • NightOwl: BYOD Postgres dashboard on the same Nightwatch instrumentation
  • Sentry / Scout / New Relic: generic APMs, weaker at Laravel-specific views

What to actually fix first

Sorted by impact:

  1. Queries repeated dozens of times in one request: N+1s. See our N+1 guide.
  2. Patterns with high call count and mid-range duration: 0.5M daily calls at a 150ms average is 75,000 seconds of DB time per day. Missing index, usually.
  3. Individually slow queries (p95 > 1s): often full table scans or large OFFSETs. Use EXPLAIN to see the plan. EXPLAIN ANALYZE runs the statement for real, so point it at reads or a copy of the data.
  4. Queries with growing duration trend: healthy yesterday, slow today. Usually the table grew past an index's sweet spot.

See your slow query patterns on real traffic

NightOwl groups every SQL statement by pattern with calls, total time, average and P95 over any range. Open a pattern to see each call's duration, the file and line that ran it, and the request or job it came from. Bindings aren't captured, so the SQL shows its ? placeholders.

No credit card needed.

Terminal
composer require nightowl/agent
php artisan nightowl:install
php artisan nightowl:agent

Frequently asked questions

Anything else, write to support@usenightowl.com

How do I find slow queries in Laravel?

Three layers from cheapest to best: (1) your database's slow-query log (MySQL slow_query_log, Postgres log_min_duration_statement) catches everything at the DB level, (2) Laravel's DB::listen() or whenQueryingForLongerThan() hook lets you log slow queries in-app with request context, (3) an APM like NightOwl that records every query per request with grouping and p95 trending.

How do I log Laravel queries that take longer than N ms?

Use DB::whenQueryingForLongerThan(500, fn($connection, $event) => logger()->warning(...)) in AppServiceProvider. This fires once per request when the cumulative query time exceeds the threshold. For per-query logging, use DB::listen() but note it fires for every query and is expensive at high traffic.

What's the difference between the MySQL slow query log and Laravel-level monitoring?

The MySQL slow query log captures raw SQL with its execution time, but not the request, controller or user behind it. Laravel-level monitoring (DB::listen, APMs) ties queries back to the request that fired them, which is what you need to actually fix the problem. Use both: MySQL's log as a safety net, Laravel-level for actionable insight.

How do I monitor query patterns, not just individual queries?

Group queries by a fingerprint of their SQL text. Eloquent and the query builder already send bound values as ? placeholders, so ten thousand select * from users where id = ? executions share one SQL string and roll up into aggregate metrics (call count, total time, average and p95 duration). NightOwl and Laravel Nightwatch Cloud both do this grouping automatically.

Can I use EXPLAIN on slow queries programmatically?

Yes. DB::select('EXPLAIN '.$sql, $bindings) returns the plan the Postgres (or MySQL) planner would use. EXPLAIN ANALYZE goes further and actually executes the statement to report real timings, so only run it on reads, or inside a transaction you roll back. The hard part is capturing the slow query with its bindings in the first place. Slow-query logs capture SQL but not always bindings; DB::listen captures both. Store the plan alongside the slow-query record for later analysis.

What's a reasonable threshold for 'slow' in Laravel?

Anything over 100ms per query deserves attention; anything over 500ms is usually a real problem. But thresholds depend on the endpoint: a 200ms query is fine in a nightly export job and catastrophic in a page render. Measure p95 duration per query pattern, not single-query thresholds.

How do I monitor queries without hitting performance?

Keep the in-process work small. DB::listen runs on every query, so its callback has to stay cheap: check $query->time first and never write to your primary DB from it. The laravel/nightwatch package that NightOwl uses records queries in memory and hands them to a local agent after the response is sent; Laravel puts its overhead at under 3ms. If you need less, sample whole requests with NIGHTWATCH_REQUEST_SAMPLE_RATE or stop recording queries with NIGHTWATCH_IGNORE_QUERIES. There's no per-query sample rate, and the NightOwl agent itself doesn't sample.

Flat pricing, whatever your traffic does

Every plan starts with a 14-day free trial. No credit card needed.

Hobby
$5 a month

One app for a side project. Issues and alerts, with a 14-day dashboard window.

Start my 14-day trial
TeamRecommended
$15 a month

Up to 3 apps and 5 people per team. Full history, the MCP server, data clearing and agent health.

Start my 14-day trial
Agency
$69 a month

Unlimited client apps and people, one overview of every app, and apps you can hand over.

Start my 14-day trial

Related

Find your slow queries on your own app

Every query is grouped by pattern with its P95, and each call points back to the file and line that ran it. No credit card needed.