Lessons from a Late-Night Incident Response and What Changed After
At 23:47 PM, a multi-tenant SaaS server started returning 502 Bad Gateway errors to every user. Walk through the exact Nginx and PHP-FPM diagnostic trail, worker memory math for pm.max_children, systemd batch isolation, and Prometheus alerts that prevented a repeat outage.
At 23:47 on a Thursday night, my phone lit up with a critical uptime alert followed thirty seconds later by a message from the client's founder: "Site is down. Getting 502 Bad Gateway on every page." Behind that Nginx error screen sat a multi-tenant B2B SaaS platform serving roughly 2,000 active users across North American and Asia-Pacific time zones from a single Ubuntu 22.04 VPS (4 vCPUs, 8 GB RAM, Nginx, PHP 8.2-FPM, and PostgreSQL 15). When I opened an SSH session two minutes later, the server still had 3.8 GB of available RAM and idle CPU headroom, yet every browser request died with an HTTP 502.
Outages where hardware looks half-idle while customers are completely locked out almost always point to a concurrency bottleneck between two daemons. Here is the exact diagnostic trail from that night, the memory math we used to resize the worker pool safely, and the permanent guardrails we shipped the next morning so a background cron job could never take down production again.
Incident Timeline
| Time (UTC) | Event |
|---|---|
| 23:30 | Nightly scheduled tenant export cron job starts across 42 customer workspaces |
| 23:44 | APAC morning logins ramp up; PHP-FPM socket listen queue begins overflowing |
| 23:47 | External checks trip HTTP 502 alerts; founder reports total dashboard outage |
| 23:49 | Connected over SSH; confirmed Nginx and PostgreSQL active, inspected /var/log/nginx/error.log |
| 23:52 | Confirmed PHP-FPM pm.max_children exhaustion (10/10 workers blocked on slow report generation) |
| 23:56 | Killed stalled internal loopback export workers, raised pm.max_children to 25, reloaded php8.2-fpm |
| 00:08 | Queue drained; p95 response latency stabilized at 140ms with zero 5xx responses |
| 00:35 | Root cause verified across cron scripts, FPM logs, and pg_stat_activity |
Following the Evidence in Nginx and PHP-FPM Logs
During a 502 outage, restarting Nginx blindly destroys diagnostic state and solves nothing if the upstream FastCGI socket is jammed. My first stop was /var/log/nginx/error.log:
tail -n 15 /var/log/nginx/error.log
# 2026/04/09 23:48:41 [error] 1409#1409: *884210 connect() to unix:/run/php/php8.2-fpm.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: 198.51.100.74, server: app.example.com, request: "GET /dashboard HTTP/2.0", upstream: "fastcgi://unix:/run/php/php8.2-fpm.sock:"
Look closely at the kernel errno inside parentheses: (11: Resource temporarily unavailable), which maps to EAGAIN on a Unix domain socket. Unlike (111: Connection refused) (daemon crashed) or (13: Permission denied) (broken socket permissions), errno 11 means /run/php/php8.2-fpm.sock exists and the master process is alive, yet its kernel socket backlog is completely full because zero worker children are free to call accept().
Checking the php8.2-fpm journal confirmed why every worker was tied up:
journalctl -u php8.2-fpm --since "23:25:00" --no-pager | grep -E "WARNING|NOTICE"
# Apr 09 23:30:19 prod-saas-01 php-fpm8.2[982]: [09-Apr-2026 23:30:19] WARNING: [pool www] server reached pm.max_children setting (10), consider raising it
The server was still running Ubuntu's stock pm.max_children = 10 default inside /etc/php/8.2/fpm/pool.d/www.conf. Worse, inspecting active PHP processes (ps aux | grep php and pg_stat_activity) exposed an architectural footgun: the 23:30 CLI cron script (artisan export:run) generated monthly PDF invoices by firing 42 concurrent asynchronous HTTP requests back into the application's own public HTTPS URL to render HTML views. Ten of those internal requests grabbed all ten www FPM workers while streaming large PostgreSQL joins, locking real users out completely.
Calculating Safe pm.max_children Limits From Real Worker RSS
For immediate triage at 23:56, verifying free -m gave us confidence to bump pm.max_children from 10 to 25 and run systemctl reload php8.2-fpm, restoring customer traffic in seconds without dropping active sockets.
The next morning, we replaced guesswork with real memory math. Picking an arbitrary high number like pm.max_children = 150 on an 8 GB server that shares hardware with PostgreSQL is a trap: during a traffic surge, PHP workers allocate 6+ GB of anonymous RAM and wake up the Linux Out-Of-Memory (OOM) killer, which routinely terminates postgres first due to its shared memory footprint.
Measure the actual Resident Set Size (RSS) of live PHP-FPM workers under production load before setting pool ceilings:
ps --no-headers -o rss,comm -C php-fpm8.2 | awk '
NR>1 {sum+=$1; if($1>max) max=$1; n++}
END {printf "Active children: %d | Avg RSS: %.1f MB | Max RSS: %.1f MB
", n, sum/n/1024, max/1024}'
# Active children: 22 | Avg RSS: 64.8 MB | Max RSS: 82.3 MB
Always size your pool against peak worker RSS (~85 MB), never average RSS, and budget the entire 8 GB host explicitly:
- Total host RAM:
8,192 MB - Linux kernel, slab cache, Nginx, and monitoring agents:
1,280 MB - PostgreSQL (
shared_buffers = 2GB+work_mem+ active backends):2,816 MB - Safety buffer for filesystem page cache and burst headroom:
1,024 MB - Remaining RAM safely available for PHP-FPM:
3,072 MB
Dividing 3,072 MB by 85 MB per heavy worker yields 36 workers maximum. We configured the primary web pool at 32 children and reserved a separate 4-worker pool strictly for internal webhooks:
; /etc/php/8.2/fpm/pool.d/www.conf
[www]
listen = /run/php/php8.2-fpm.sock
listen.backlog = 1024
pm = dynamic
pm.max_children = 32
pm.start_servers = 8
pm.min_spare_servers = 6
pm.max_spare_servers = 16
pm.max_requests = 1000
request_terminate_timeout = 60s
pm.status_path = /fpm-status
Setting pm.max_requests = 1000 recycles each child gracefully after 1,000 requests so slow library memory leaks never bloat RSS over weeks of uptime, while request_terminate_timeout = 60s prevents hung external API calls from wedging workers indefinitely.
Isolating Nightly Batch Exports With systemd-run, nice, and ionice
Resizing www.conf added headroom; re-architecting the cron job removed the trigger. We refactored PDF generation to render directly inside queued CLI jobs in chunks of --batch-size=50 rather than making HTTP loopback requests through Nginx. Next, we wrapped scheduled exports in transient systemd-run cgroup slices paired with CPU and I/O priorities (matching the cgroup v2 controls in our Linux high-CPU troubleshooting checklist):
# /etc/cron.d/saas-exports
30 3 * * * deploy systemd-run --quiet --unit=tenant-nightly-export --property=CPUQuota=80% --property=MemoryMax=1024M nice -n 10 ionice -c 2 -n 7 /usr/bin/php /var/www/app/current/artisan export:run --batch-size=50
Moving the export window to 03:30 UTC (the lowest traffic trough across both US and APAC users) and capping it inside an 80% single-core quota ensures interactive customer traffic always wins CPU and NVMe priority.
Enabling /fpm-status With Prometheus and Grafana Alerts
Before this outage, monitoring only checked whether php8.2-fpm was active and whether / returned 200 OK, alerting us only after users already saw 502. We exposed PHP-FPM's live status endpoint locally inside Nginx:
location = /fpm-status {
allow 127.0.0.1;
deny all;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}
Scraping http://127.0.0.1/fpm-status via php-fpm_exporter into Prometheus and graphing active processes versus listen queue in Grafana gave us immediate visibility, backed by a proactive capacity alert:
- alert: PhpFpmPoolNearSaturation
expr: (phpfpm_active_processes{pool="www"} / 32) > 0.80
for: 2m
labels:
severity: warning
annotations:
summary: "PHP-FPM pool www above 80% capacity on {{ $labels.instance }}"
Pairing early capacity thresholds with low-noise alert hold times and severity routing gives us a calm warning at 80% utilization long before listen queue climbs above zero. Fixing a midnight outage takes ten minutes; building strict bulkheads between user requests and batch jobs is what prevents the sequel.