An HTTP 504 Gateway Timeout means a reverse proxy or edge load balancer (Cloudflare, Nginx, Caddy, or HAProxy) could not read a complete response header from its upstream origin before a configured timer (proxy_read_timeout, fastcgi_read_timeout, timeout server, or Cloudflare's 100-second origin limit) expired. Do not blindly bump proxy_read_timeout to 600 seconds: in 95% of real incidents, a 504 is the downstream symptom of upstream worker pool saturation (PHP-FPM pm.max_children, Gunicorn workers, or a blocked Node.js event loop), PostgreSQL lock contention, or Linux kernel socket accept-queue drops (TcpExtListenOverflows).
When pages are firing at 2 AM, you need deterministic triage—not trial-and-error config reloads. Follow this top-down runbook to pinpoint the exact stalled hop in under two minutes.
curl -w)Every proxy leaves a fingerprint in the HTTP response headers and error log telling you who timed out and at which phase of the upstream lifecycle:
| Proxy / Edge Layer | Default Timeout Ceiling | Exact Error Log Signature | Meaning & Immediate Action |
|---|---|---|---|
Cloudflare Edge (524 / 504) |
100s hard read ceiling (Free/Pro/Biz) |
HTTP 524 A Timeout Occurred or cf-ray header on 504 |
Origin accepted TCP on 443, sent 0 HTTP bytes for 100s. Offload job to async queue (202 Accepted) or stream SSE keep-alives |
Nginx proxy_connect_timeout |
60s (way too high; set 3s–5s!) |
upstream timed out (110: Connection timed out) while connecting to upstream |
Kernel SYN backlog full on backend, firewall DROP, or dead container IP |
Nginx proxy_read_timeout |
60s between two successive read() calls |
upstream timed out (110: ...) while reading response header from upstream |
Upstream accepted TCP & read request, then hung in SQL, external API, or CPU lock |
Nginx fastcgi_read_timeout |
60s |
upstream timed out ... while reading response header on unix:/run/php/php-fpm.sock |
PHP-FPM pm.max_children exhausted or PHP script hung waiting on DB/cURL |
Caddy reverse_proxy |
Unlimited read unless response_header_timeout set; dial_timeout 3s |
http.log.error ... context deadline exceeded / i/o timeout |
Upstream failed TCP dial within dial_timeout or exceeded response_header_timeout |
HAProxy timeout queue / server |
Explicit in haproxy.cfg |
Termination state sH (server header timeout) or qR/cQ (queue timeout) |
HAProxy sH = app hung processing; cQ = maxconn full on backend servers |
Before touching any config file, run curl directly on the origin box against 127.0.0.1 (bypassing Cloudflare and Nginx) and against the local proxy with a phase-by-phase timing breakdown:
# Measure DNS, TCP connect, TLS handshake, and Time-To-First-Byte (TTFB) separately
curl -sS -o /dev/null -w \
"http_code=%{http_code} dns=%{time_namelookup}s tcp=%{time_connect}s tls=%{time_appconnect}s ttfb=%{time_starttransfer}s total=%{time_total}s\n" \
--max-time 65 http://127.0.0.1:3000/api/slow-endpoint
tcp hangs at 3.0s or 7.0s (powers-of-two Linux TCP SYN retransmit intervals!), the backend process's kernel listen backlog queue is overflowing.tcp finishes in 0.001s and ttfb hits 60.001s, the OS accepted the socket immediately, and your application runtime or database is stuck.SYN-RECV Drops (ss -lnt)Every listening socket maintains two kernel queues: the incomplete SYN queue and the completed accept() queue (capped at min(backlog, net.core.somaxconn)). In ss -lnt, for listening sockets, Recv-Q shows the current number of established connections waiting for your app to call accept4(), and Send-Q shows the maximum configured backlog! If Recv-Q >= Send-Q (for instance, 129 waiting on a backlog of 128 because all worker threads are busy), the kernel silently drops incoming SYN packets, causing Nginx to stall in SYN-SENT until proxy_connect_timeout triggers a 504:
# 1. Inspect current accept-queue depth (Recv-Q) vs max capacity (Send-Q) on port 3000 & 9000
sudo ss -lnt '( sport = :3000 or sport = :9000 )'
# 2. Check cumulative kernel TCP listen-queue overflow counters (run twice 5s apart)
nstat -az TcpExtListenOverflows TcpExtListenDrops
# 3. Check PostgreSQL for blocked queries waiting behind locks (classic 504 cascade culprit!)
psql -d app_db -c "
SELECT pid, usename, state, wait_event_type, wait_event,
now() - query_start AS runtime, pg_blocking_pids(pid) AS blocked_by,
left(query, 90) AS sql
FROM pg_stat_activity
WHERE state <> 'idle' AND query_start < now() - interval '3 seconds'
ORDER BY runtime DESC;"
Look closely at pg_blocking_pids(pid): one developer running an unguarded ALTER TABLE orders ADD COLUMN ... that stalls behind an idle in transaction reporting session acquires a pending AccessExclusiveLock request—causing every subsequent SELECT and INSERT on orders to queue behind the DDL lock until every HTTP worker times out with 504! Always set SET lock_timeout = '2s'; SET statement_timeout = '15s'; in migrations and application connection pools.
pm.max_children & Slowlog TracingIn PHP/WordPress/Laravel stacks, if pm.max_children = 10 and ten users hit an unindexed search route or hung outbound webhook, request #11 sits inside the UNIX domain socket queue until Nginx's fastcgi_read_timeout fires. Check sudo journalctl -u php8.3-fpm for server reached pm.max_children setting, size max_children = (Available_RAM_MB) / (Avg_PHP_Process_RSS_MB), and enable request_slowlog_timeout = 5s + slowlog = /var/log/php8.3-fpm-slow.log in /etc/php/8.3/fpm/pool.d/www.conf to capture the exact PHP C-level stack trace of hung workers without guessing.
libuv Threadpool ExhaustionBecause Node.js multiplexes thousands of sockets onto a single V8 JavaScript thread, one synchronous crypto.pbkdf2Sync, JSON.stringify on a 150 MB array, or catastrophic regex (ReDoS) freezes every in-flight request—including /healthz! Less obvious is libuv threadpool starvation: Node's dns.lookup() (used by fetch() and http.request whenever you connect to a hostname!) shares a default 4-thread libuv C++ pool with fs.* and zlib. If four outbound DNS queries hang on a slow resolver, all outbound HTTP calls across the entire Node process stall! Set UV_THREADPOOL_SIZE=16, enable dns.setDefaultResultOrder('ipv4first') if IPv6 routing isn't present, and pass signal: AbortSignal.timeout(5000) on every outbound fetch().
Global 300-second timeouts are an anti-pattern—they allow a slow-read event or broken downstream dependency to pin every file descriptor on your proxy. Keep global defaults tight (3s connect, 30s read), disable proxy_next_upstream retries on non-idempotent POST timeouts (otherwise Nginx duplicates a slow payment charge on a second backend node!), and extend proxy_read_timeout only on dedicated streaming or report routes:
# /etc/nginx/conf.d/upstream-timeouts.conf
upstream app_cluster {
server 127.0.0.1:3001 max_fails=3 fail_timeout=10s;
server 127.0.0.1:3002 max_fails=3 fail_timeout=10s;
keepalive 64;
}
server {
listen 443 ssl;
http2 on;
server_name api.example.com;
# Default API routes: fail fast on dead TCP (3s), strict 30s read ceiling
location /api/ {
proxy_pass http://app_cluster;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_connect_timeout 3s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# CRITICAL: Never auto-retry timed-out POST/PATCH mutations on another node!
proxy_next_upstream error http_502;
}
# Streaming SSE / LLM / export route: disable buffering + extend read window
location /api/v1/stream/ {
proxy_pass http://app_cluster;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off;
proxy_cache off;
proxy_connect_timeout 3s;
proxy_read_timeout 300s;
}
}
And the equivalent hardened setup in Caddy (/etc/caddy/Caddyfile) and HAProxy (/etc/haproxy/haproxy.cfg):
# Caddyfile: fast 3s TCP dial fail-over + explicit 30s response header deadline
api.example.com {
@streaming path /api/v1/stream/*
handle @streaming {
reverse_proxy 127.0.0.1:3001 127.0.0.1:3002 {
flush_interval -1
transport http {
dial_timeout 3s
response_header_timeout 300s
}
}
}
handle {
reverse_proxy 127.0.0.1:3001 127.0.0.1:3002 {
lb_try_duration 4s
transport http {
dial_timeout 2s
response_header_timeout 30s
}
}
}
}
proxy_read_timeout 60s actually measure 60 seconds?Contrary to popular belief, proxy_read_timeout 60s does not cap the total duration of the entire HTTP download to 60 seconds! It measures the maximum idle gap between two consecutive read(2) socket operations from the upstream server. If an SSE stream or chunked CSV download flushes even a single : heartbeat comment every 15 seconds (with proxy_buffering off), the connection can stay alive cleanly for hours without raising proxy_read_timeout.
502 Bad Gateway: Instant protocol/socket failure—upstream returned TCP RST (Connection refused because the daemon is stopped), closed the socket mid-header (ECONNRESET), or emitted invalid HTTP bytes.503 Service Unavailable: Explicit overload shedding—either HAProxy/Nginx hit a configured concurrency cap/limit_conn, or the app intentionally rejected load during maintenance/startup.504 Gateway Timeout: Silence—the socket opened (or sat in SYN-SENT), and the clock ran out waiting for bytes.Never hold a synchronous browser HTTP POST open for 2+ minutes across internet proxies. Have POST /api/jobs insert a database job row, enqueue work to a background worker, and return HTTP 202 Accepted in 15 ms with {"jobId":"job_91a","statusUrl":"/api/jobs/job_91a"}. Poll statusUrl every 2 seconds (or subscribe via Server-Sent Events emitting a 15s keep-alive ping) until the worker writes the completed artifact to Cloud Storage.
During container restarts without graceful connection draining, old containers receive SIGTERM and drop active DB work or stop calling accept(), while new containers spend several seconds compiling JIT routes or warming connection pools. Configure your app to catch SIGTERM, fail readiness probes first, finish active requests within 10s, and deploy behind dual-upstream health checks (or use "live-restore": true and rolling workers on Managed Docker Containers).
Explore With AI & Cite This Page
Open a grounded prompt in your AI assistant or copy a clean Markdown, HTML, or APA reference link.
Validate protocols and subnets directly in your browser or continue reading related architecture notes.
HTTP Redirect Checker — Trace 301 & 308 Hops
CVE Vulnerability & CISA KEV Banner Advisor
UFW Firewall Rule Generator & Chmod Calculator
Nginx & Caddy Reverse Proxy Troubleshooting Cheat Sheet: Fixing 502, 504, 403, and TLS Errors
Deterministic Linux terminal diagnostic workflow for isolating and fixing 502 Bad Gateway, 504 Gateway Timeout, 403 Forbidden, 413 Payload Too Large, WebSocket upgrade drops, and TLS handshake errors.
Understanding and Resolving HTTP 403 Forbidden: Linux VFS Traverse Bits, SELinux, Reverse Proxies & Object Storage
Debug HTTP 403 Forbidden errors across every stack layer: Linux parent-directory +x traverse bits (namei -l), SELinux httpd_sys_content_t labels, Nginx autoindex/try_files, S3/Blob SAS clock skew, and Cloudflare WAF.
504 Gateway Time-Out Architecture: Timeout Chains, Retry Storms & Async Job Offloading
Why bumping proxy_read_timeout makes 504 outages worse: engineering concentric timeout budgets (Edge > LB > App > DB), stopping exponential retry storms with full jitter, and offloading slow work to async queues and SSE streams.
Fixing "Search Not Found" and 404 Errors: HTTP Routing, PostgreSQL GIN Planner Traps, and Hybrid pgvector Search
Isolate and fix HTTP 404 routing errors vs empty 200 OK search responses—including fixing the PostgreSQL GIN + OR ILIKE sequential-scan trap with pg_trgm and adding hybrid pgvector RRF search.