惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
Security Latest
Security Latest
P
Proofpoint News Feed
GbyAI
GbyAI
PCI Perspectives
PCI Perspectives
博客园 - Franky
N
Netflix TechBlog - Medium
博客园_首页
WordPress大学
WordPress大学
K
Kaspersky official blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Vercel News
Vercel News
T
Threatpost
The Hacker News
The Hacker News
H
Help Net Security
S
Securelist
Recent Announcements
Recent Announcements
腾讯CDC
T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Engineering at Meta
Engineering at Meta
C
Cisco Blogs
V
V2EX
C
Check Point Blog
S
Schneier on Security
Cyberwarzone
Cyberwarzone
C
Cybersecurity and Infrastructure Security Agency CISA
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog RSS Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Jina AI
Jina AI
M
MIT News - Artificial intelligence
T
Threat Research - Cisco Blogs
博客园 - 叶小钗
A
Arctic Wolf
AWS News Blog
AWS News Blog
Latest news
Latest news
Martin Fowler
Martin Fowler
Recorded Future
Recorded Future
Last Week in AI
Last Week in AI
The GitHub Blog
The GitHub Blog
小众软件
小众软件
B
Blog
aimingoo的专栏
aimingoo的专栏
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
P
Palo Alto Networks Blog
Spread Privacy
Spread Privacy

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything BFF模式详解:构建前后端协同的中间层 I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
The php-fpm Tuning Cheat Sheet: 5 Settings That Decide Your p99
Gabriel Anha · 2026-05-24 · via DEV Community

Your Laravel app is slow under load. CPU sits at 30%. Memory is fine. The database isn't sweating. And p99 still spikes to 8 seconds during the Tuesday-morning rush.

You open Grafana. You look at the queries. You look at the cache hit ratio. You add another Redis node. Nothing changes.

The problem isn't your code. It's php-fpm. Specifically, five lines in www.conf that ship with values picked for a Raspberry Pi.

The pool model in 60 seconds

php-fpm runs a pool of worker processes. A web request comes into Nginx, Nginx forwards it through FastCGI to the pool, a worker picks it up, the worker runs your PHP code, sends the response back, then waits for the next request.

The whole game is: how many workers, when to spawn them, when to recycle them.

You pick one of three process managers in www.conf:

; /etc/php/8.4/fpm/pool.d/www.conf
pm = dynamic

Enter fullscreen mode Exit fullscreen mode

  • pm = static: fixed number of workers, always alive. Predictable memory. No spawn latency. Wastes RAM when traffic dips.
  • pm = dynamic: a min/max range, scales up and down based on demand. The default in most distros. Has spawn latency at the boundaries.
  • pm = ondemand: workers spawn only when a request arrives, die after idle timeout. Lowest memory floor. Adds 5-50ms to cold requests.

For a single-purpose API server serving real traffic, static is almost always the right answer. Spawn cost during a burst is the worst latency outlier you can hand a user. We'll come back to this.

Setting 1: pm.max_children (the one most teams get wrong)

This is the cap. It's how many PHP processes can run at once on this box. Set it too low, requests queue. Set it too high, the kernel OOM-kills your workers and your Redis sidecar.

The formula every distro doc skips:

pm.max_children = (total_RAM - reserved_for_OS_and_sidecars) / avg_worker_memory

Enter fullscreen mode Exit fullscreen mode

The two values you need to measure, not guess:

  1. avg_worker_memory: actual RSS of a settled worker after handling a few requests. Not the boot value. Workers grow as autoloaders load classes, opcache warms, and Laravel hydrates service containers. Measure after a real warmup.
# settled RSS per worker, in MB
ps -ylC php-fpm8.4 --sort:rss \
  | awk 'NR>1 { sum+=$8; n++ } END { printf "avg=%.1f MB\n", sum/n/1024 }'

Enter fullscreen mode Exit fullscreen mode

A bare Laravel 12 worker is usually 50-80 MB. A monolith with 200 routes, Telescope and a few Filament resources sits at 120-180 MB. A worker doing heavy image transforms can balloon past 400 MB transiently.

  1. reserved RAM: the OS itself, Nginx, Redis if it's local, OPcache shared memory (defaults to 128 MB), the APM agent if you've got one. On a 4 GB box you're usually looking at 700 MB to 1 GB reserved before php-fpm gets a slice.

Worked example. c5.large EC2: 4 GB RAM, 2 vCPUs, Ubuntu, Nginx + php-fpm + a local Redis.

  • Total: 4096 MB
  • Reserved (OS + Nginx + Redis + OPcache + buffers): ~900 MB
  • Available for php-fpm: ~3200 MB
  • Measured avg worker RSS: 140 MB
  • pm.max_children = 3200 / 140 = ~22
pm = static
pm.max_children = 22

Enter fullscreen mode Exit fullscreen mode

A common shape on this exact box: someone ships pm.max_children = 50 because that's what some Stack Overflow answer from 2014 said. Traffic comes in, the 23rd worker pushes them into swap, latency goes vertical, and the on-call engineer adds more workers thinking it'll help. It doesn't. It makes it worse.

The CPU side check. If your average request is CPU-bound and short (under 50ms), there's no point having more workers than vCPU * 2-4. They'll just thrash the scheduler. On the c5.large that's 4-8 workers max if you're CPU-bound. Pick whichever bound is smaller, RAM or CPU.

Setting 2: pm.max_requests (memory-leak insurance)

PHP doesn't leak the way C does, but php-fpm workers absolutely do grow. Composer autoloading, opcache, hydrated containers, accidental static caches in your own code. After 50,000 requests the same worker that started at 80 MB might be sitting at 220 MB and not giving it back.

pm.max_requests recycles workers after N requests. They exit cleanly, php-fpm spawns a fresh replacement.

pm.max_requests = 500

Enter fullscreen mode Exit fullscreen mode

The right value is "high enough that recycling cost is invisible, low enough that leaks don't matter." For most apps that's 500-1000. Library code that allocates aggressively (PDF generation, image processing, HTTP clients with caching layers) wants the lower end. Lean API workers can run at 2000+.

The gotcha: pm.max_requests = 0 (the default in some distros) means workers never recycle. If you've got it set to 0 and you've never explicitly tuned it, you have memory growth you don't know about. Set it to something. Even 2000 is safer than 0.

Setting 3: request_terminate_timeout (the timeout that actually fires)

This is the timeout that wins.

PHP has max_execution_time in php.ini. Nginx has fastcgi_read_timeout in its server block. php-fpm has request_terminate_timeout in www.conf. They are three different timeouts that kill the same request, and the shortest one wins.

request_terminate_timeout = 30s

Enter fullscreen mode Exit fullscreen mode

What goes wrong: a slow query takes 60 seconds. fastcgi_read_timeout is 60s. max_execution_time is 30s but it's inside a sleep() or a blocked socket call, so it can't fire (PHP only checks the timer at opcode boundaries). The request hangs the worker for the full 60s. Repeat 22 times and your whole pool is wedged on the same broken upstream.

request_terminate_timeout is enforced by the php-fpm master with a signal, so it fires regardless of what the worker is doing. It's the only timeout that reliably frees a wedged worker.

Set all three. Keep request_terminate_timeout slightly higher than max_execution_time so PHP gets a chance to throw Maximum execution time exceeded and log a stack trace before the master nukes the worker:

; www.conf
request_terminate_timeout = 35s

Enter fullscreen mode Exit fullscreen mode

; php.ini
max_execution_time = 30

Enter fullscreen mode Exit fullscreen mode

# Nginx server block
fastcgi_read_timeout = 40s;

Enter fullscreen mode Exit fullscreen mode

The order: PHP throws at 30s (you get a stack trace), php-fpm kills at 35s (worker is freed), Nginx closes the connection at 40s (request returns 504). Each layer is a backstop for the previous one failing.

Setting 4: pm.process_idle_timeout (only relevant for ondemand)

If you're on pm = dynamic or pm = static, skip this section. It's a no-op.

For pm = ondemand, workers spawn on the first request and die after pm.process_idle_timeout seconds of doing nothing.

pm = ondemand
pm.max_children = 22
pm.process_idle_timeout = 60s
pm.max_requests = 500

Enter fullscreen mode Exit fullscreen mode

The trap: a too-short process_idle_timeout thrashes spawn/kill, which is the most expensive thing php-fpm does. A 60-second timeout is reasonable for low-traffic services where you genuinely want to release RAM during quiet periods. Going below 10s is almost always wrong.

When to actually use ondemand. Multi-tenant hosting where you've got 50 pools on one box and most of them are dormant. Background workers that handle bursty cron-driven traffic. A staging environment where memory matters more than latency.

When to never use ondemand. Anything user-facing with real traffic. The spawn cost of a worker (autoloader, opcache hydration, framework bootstrap if you're not on Octane) is 50-200ms. That's an entire latency budget gone before your PHP code runs a single line. static with a tighter pm.max_children is a better trade.

Setting 5: listen.backlog (the SYN-queue knob nobody touches)

This is the one nobody knows about and it's the one that decides your behavior during traffic spikes.

listen.backlog is the size of the socket accept queue. When all your workers are busy and Nginx tries to hand off another request, the connection sits in this queue waiting for a worker to free up.

listen = /run/php/php8.4-fpm.sock
listen.backlog = 4096

Enter fullscreen mode Exit fullscreen mode

The default in many distros is 511. On a box that can take 22 concurrent workers handling 50ms requests, you can chew through 511 queued connections in roughly 1.2 seconds at full burst. After that, new connections get refused with connect() failed (11: Resource temporarily unavailable).

You've seen this in Nginx logs. It looks like php-fpm crashed. It didn't. The queue overflowed.

Bump listen.backlog to 4096 or 8192:

listen.backlog = 8192

Enter fullscreen mode Exit fullscreen mode

The kernel ceiling that bites. listen.backlog is silently capped at the smaller of itself and the kernel's net.core.somaxconn. On older Linux distros somaxconn defaults to 128. You can set listen.backlog = 65535 in www.conf and the actual queue size will be 128.

Check the kernel value:

sysctl net.core.somaxconn

Enter fullscreen mode Exit fullscreen mode

Raise it if it's lower than your php-fpm setting:

# /etc/sysctl.d/99-php-fpm.conf
net.core.somaxconn = 8192
net.ipv4.tcp_max_syn_backlog = 8192

Enter fullscreen mode Exit fullscreen mode

sudo sysctl -p /etc/sysctl.d/99-php-fpm.conf

Enter fullscreen mode Exit fullscreen mode

After this change, restart php-fpm so the listener picks up the new backlog. A reload isn't enough. The socket has to be recreated.

sudo systemctl restart php8.4-fpm

Enter fullscreen mode Exit fullscreen mode

Listen for the queue depth in production with ss:

# Recv-Q on the LISTEN socket = current queue depth
ss -lntp | grep php-fpm

Enter fullscreen mode Exit fullscreen mode

If Recv-Q is climbing during peak, your workers aren't keeping up. Backlog buys you time; it doesn't fix throughput. The fix is more workers, faster code, or Octane.

A real tuning walkthrough on c5.large, Laravel 12

Setup: c5.large, 2 vCPU, 4 GB RAM, Laravel 12 app with Telescope on, MySQL on a separate box, local Redis, Nginx + php-fpm 8.4.

Before:

pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 0
request_terminate_timeout = 0
listen.backlog = 511

Enter fullscreen mode Exit fullscreen mode

Load test with k6, 200 RPS for 5 minutes. p99 at 4800ms. Steady-state RAM at 92% with OOM-killer firing twice during the run.

After:

pm = static
pm.max_children = 20
pm.max_requests = 800
request_terminate_timeout = 35s
listen = /run/php/php8.4-fpm.sock
listen.backlog = 8192

Enter fullscreen mode Exit fullscreen mode

# /etc/sysctl.d/99-php-fpm.conf
net.core.somaxconn = 8192

Enter fullscreen mode Exit fullscreen mode

Same load test. p99 at 380ms. RAM steady at 78%. No OOMs. Throughput went up because the box stopped paging.

The lesson: pm.max_children = 50 on a 4 GB box wasn't "scaling," it was queuing requests inside swap. Cutting it to 20 made everything faster.

When to switch to Octane instead

Octane (Swoole or FrankenPHP backend) keeps the Laravel app booted in memory between requests. The autoloader doesn't re-run, the service container isn't rebuilt, the middleware stack stays intact. That 30-80ms framework boot cost goes to zero.

If your php-fpm worker spends 60ms in framework boot and 40ms in actual request work, Octane gives you a 2.5x throughput jump on the same hardware. That's not a tuning improvement; that's an architecture shift.

Octane needs your code to be more careful. Static state survives across requests, container singletons stay singleton across requests, anything that assumed a fresh process is now wrong. It's worth the work for high-traffic apps. For a CMS doing 10 RPS, php-fpm tuned correctly is fine.

The five settings above get you 80% of the way there before you change architecture. Octane gets you the last 20%. Tune first, then decide.

What's your current pm.max_children and how did you pick it? Drop your numbers (RAM, avg worker RSS, the value you settled on) in the comments. Curious how far off the defaults most folks are running.


If this was useful

php-fpm tuning gets you the box right, but the box is a small slice of why apps slow down at scale. The other slice (service boundaries, framework coupling, the layers that decide whether your team can scale the code itself) is what Decoupled PHP is about. It's the architectural layer your codebase reaches for once you've outgrown the framework defaults.

Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework

Available on Kindle, Paperback, and Hardcover. English, German, and Japanese editions out now — Portuguese and Spanish coming soon.