Start free trial
Start free trial Log in

14-day free trial. No credit card.

How to debug Laravel timeouts

How to tell which layer timed out (PHP, PHP-FPM, Nginx or the database) and fix it without raising every limit.

  • Guide
  • 3 min read

How do I debug a Laravel 504 timeout?

Identify the layer that gave up first. Check Nginx access logs for the 504. You'll see URL, timestamp, and upstream_response_time. A 504 means Nginx waited longer than fastcgi_read_timeout, and upstream_response_time will sit near that value. If PHP-FPM kills the worker at request_terminate_timeout, Nginx returns a 502 instead, and if PHP hits max_execution_time the request ends with a 500 fatal error. The layer tells you where to look: a 504 is often a slow database query or external HTTP call, visible in an APM's per-request trace.

Updated

A timeout rarely surfaces where it's caused. Nginx returns the 504, but Nginx didn't do anything wrong: it stopped waiting for PHP, and PHP was usually waiting on a query that was itself stuck behind a lock. Debugging a timeout means walking that chain backwards to the layer that actually stalled, and each layer signals in its own way that it was the one that gave up first.

The timeout layers

A Laravel HTTP request touches multiple layers. Each has its own timeout:

Layer Default Config
Client (browser, curl)Varies (curl has none)Client-specific
Load balancer (ALB, CF)60s AWS ALB defaultidle_timeout
Nginx upstream60sfastcgi_read_timeout
PHP-FPM request0 (unlimited)request_terminate_timeout
PHP script30smax_execution_time
Database statementUnlimited (dangerous)statement_timeout (Postgres)

Diagnose the layer that failed

Nginx access log

Terminal
# Enable timing fields in log_format
log_format upstream_timing '$remote_addr $request $status '
                           'request=$request_time upstream=$upstream_response_time';

# Look for 504s with timing
grep ' 504 ' /var/log/nginx/access.log | tail

If upstream_response_time is roughly equal to fastcgi_read_timeout, Nginx gave up waiting. That timer runs between two successive reads from PHP-FPM, not over the whole response, so a request that keeps sending output can run longer than it. If upstream_response_time is -, Nginx never contacted an upstream for that request, so the problem sits in front of PHP-FPM.

PHP-FPM slowlog

/etc/php/8.2/fpm/pool.d/www.conf

ini
slowlog = /var/log/php-fpm/slow.log
request_slowlog_timeout = 10s
request_terminate_timeout = 60s

PHP-FPM dumps the stack trace of any request taking longer than request_slowlog_timeout. Useful for catching where the hang actually happens, often inside a database driver or file operation.

Database-level timeouts

app/Providers/AppServiceProvider.php (PostgreSQL)

php
use Illuminate\Database\Events\ConnectionEstablished;
use Illuminate\Support\Facades\Event;

public function boot(): void
{
    // Per-session statement timeout on every new pgsql connection
    Event::listen(function (ConnectionEstablished $event) {
        if ($event->connection->getDriverName() === 'pgsql') {
            $event->connection->statement("SET statement_timeout = '15s'");
        }
    });
}

Laravel's config/database.php has no statement_timeout key, so set it with a listener like this or on the role itself: ALTER ROLE app_user SET statement_timeout = '15s';. Without statement_timeout, a query can hold a PHP-FPM worker indefinitely. Set a value lower than your request timeout so DB hangs fail recoverably instead of taking out the worker.

Common 504 causes

  1. Synchronous external HTTP call with a long or missing timeout. Guzzle on its own has no timeout, and Laravel's Http client defaults to 30 seconds. Set Http::timeout(5) on every external call.
  2. Slow DB query on unindexed column. EXPLAIN ANALYZE reveals full-table scans.
  3. Exhausted PHP-FPM worker pool. pm.max_children too low, legitimate requests queue, queue exceeds timeout.
  4. Lock contention on a hot row. SELECT ... FOR UPDATE blocking other requests. Visible in Postgres's pg_locks.
  5. Blocking cron job on the same server. A scheduled task hogging CPU or disk starves web workers.

Don't just raise every timeout

The instinct to bump fastcgi_read_timeout to 300s papers over the real issue. A request taking 300s shouldn't run in a request at all. Queue it. Have the request dispatch a job and return a 202 with a polling URL, or notify the client by webhook when the job finishes.

Find the span that ran out the clock

Nginx makes the 504, so PHP never sees it. In NightOwl you find those requests by duration: filter a route to its requests at or above P95 or P99, then open one to see the query or HTTP call that hung.

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

Why am I getting 504 Gateway Timeout errors in Laravel?

Nginx waited longer than its fastcgi_read_timeout for PHP-FPM to send the next part of the response. Common culprits: a hung database query, a slow external API called synchronously, or an exhausted PHP-FPM worker pool that leaves requests queuing. Two other limits look similar but return different codes: PHP-FPM killing the worker at request_terminate_timeout gives a 502, and PHP hitting max_execution_time gives a 500 fatal error. The 504 is the symptom. The trace of the affected request shows which span actually took the time.

What's the default PHP timeout in Laravel?

max_execution_time defaults to 30 seconds for HTTP requests in most php.ini configurations. CLI is unlimited by default. On Linux it only counts the script's own CPU time, so time spent waiting on the database or an HTTP call doesn't count toward it. Laravel doesn't override this unless you do it explicitly with set_time_limit() or ini_set(). Nginx and PHP-FPM each have their own timeouts (request_terminate_timeout in PHP-FPM, fastcgi_read_timeout in Nginx), which must all be compatible.

How do I increase the Laravel request timeout?

Three layers, all must increase together. PHP: set_time_limit(120) or ini_set('max_execution_time', 120). PHP-FPM: request_terminate_timeout = 120. Nginx: fastcgi_read_timeout 120s. If any one is lower, requests still time out at that layer. For most apps, a better answer is to not run long work in a request. Use queues.

What's the difference between 504 and 502 in Laravel?

504 Gateway Timeout: Nginx waited longer than fastcgi_read_timeout for PHP-FPM. The request was in progress but too slow. 502 Bad Gateway: PHP-FPM closed the connection or couldn't be reached, for example because the worker was killed (request_terminate_timeout, a crash) or PHP-FPM isn't running. Both come from Nginx; their causes differ.

How do I find which request timed out in Laravel?

Check Nginx's access log for 504 status codes. The URL and timestamp give you the request. Then check PHP-FPM's slowlog (configure with request_slowlog_timeout) to see the PHP stack trace at the moment of the timeout. Or use an APM that records every request with its duration. The 504 itself comes from Nginx and never reaches PHP, but the slow request behind it does, as long as PHP got to finish it.

Why do Laravel queue jobs time out?

Laravel's worker enforces the timeout: the job's $timeout property, or the worker's --timeout option (60 seconds by default), using the pcntl extension. When a job runs past it, the worker process kills itself and your process manager restarts it. The job is marked failed if it has no attempts left or sets $failOnTimeout; otherwise it becomes available again once the connection's retry_after passes. Keep --timeout a few seconds below retry_after so a job can't be picked up twice. PHP's max_execution_time doesn't apply, since it's unlimited on the CLI.

How do I prevent database queries from hanging Laravel requests?

Set statement_timeout in PostgreSQL or max_execution_time in MySQL for the session. config/database.php has no key for either, so set it on the database role (ALTER ROLE app_user SET statement_timeout = '15s') or run a SET statement from a ConnectionEstablished listener. MySQL's max_execution_time is in milliseconds and only applies to SELECT statements. A query that exceeds the timeout fails with a QueryException instead of hanging the PHP-FPM worker indefinitely.

What's the right PHP-FPM pm.max_children setting?

Roughly: (available_memory - overhead) / average_process_memory. For an 8GB server with 100MB per process and ~2GB overhead, that's (8000-2000)/100 = 60 children. Set too low and requests queue and 504. Set too high and workers swap memory and everything slows down. Monitor with pm.status_path and tune from data, not guesses.

Related

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