Client Project Lessons

Lessons from a Late-Night Incident Response and What Changed After

By Nikhil Bhangale··6 min read

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.

Lessons from a Late-Night Incident Response and What Changed After

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:30Nightly scheduled tenant export cron job starts across 42 customer workspaces
23:44APAC morning logins ramp up; PHP-FPM socket listen queue begins overflowing
23:47External checks trip HTTP 502 alerts; founder reports total dashboard outage
23:49Connected over SSH; confirmed Nginx and PostgreSQL active, inspected /var/log/nginx/error.log
23:52Confirmed PHP-FPM pm.max_children exhaustion (10/10 workers blocked on slow report generation)
23:56Killed stalled internal loopback export workers, raised pm.max_children to 25, reloaded php8.2-fpm
00:08Queue drained; p95 response latency stabilized at 140ms with zero 5xx responses
00:35Root 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:

bash · terminal
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:

bash · terminal
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:

bash · terminal
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:

config / ini
; /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):

bash · terminal
# /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:

nginx.conf
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:

yaml
- 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.

#incident-response#linux#nginx#postgresql#monitoring
← Back to all posts

Related Articles

Browse all articles →
Client Project Lessons13 min read

How I Recovered a Broken SolusVM 2 KVM Virtual Machine Using Chroot, Repaired the Linux System, and Safely Migrated Critical Data

Recently, I worked on a challenging recovery involving a SolusVM 2 KVM virtual machine that would no longer boot. What initially appeared to be a kernel or filesystem problem turned out to involve multiple layers of system corruption.

Read article →
Daily Work Log13 min read

SolusVM 2 Migration Guide: Fix Agents, License & WHMCS

Today's hands-on work log: migrating a live SolusVM 2 Management Server to a new VPS without touching running Compute Resource VMs, fixing the license IP lock, debugging RabbitMQ and solus-agent start/stop/create failures, and restoring WHMCS automation.

Read article →
Security11 min read

PHP Nov 2026 Critical RCEs: Patch 8.5.13 & 8.4.28 Now

The PHP Foundation released 8.5.13, 8.4.28, 8.3.37, and 8.2.36 on November 19, 2026 fixing 18 security flaws including CVSS 9.2 PHP-FPM smuggling and session upload RCEs. Here is my Linux sysadmin audit, hot mitigation, and multi-PHP patch playbook.

Read article →
Chat on WhatsApp