A single user reports AJAX-heavy pages loading slowly, but the server has spare worker capacity and CPU is barely loaded. The PHP-FPM status page shows active workers climbing toward max_children. You raise max_children and nothing improves. The slow log, when configured, shows stack traces parked at session_start().
This is session lock contention. PHP’s default file-based session handler acquires an exclusive flock(LOCK_EX) on the session file at session_start() and holds it until the script ends or session_write_close() is called. When one browser session makes concurrent requests (parallel AJAX calls, SPA data fetching, long-polling, upload progress checks), those requests serialize completely behind that single lock.
Each blocked request occupies a worker slot while sleeping on a kernel flock, burning near-zero CPU. Raising max_children does not help: the new workers immediately block on the same lock.
What this means
PHP’s files session handler (the default) calls flock(fd, LOCK_EX) inside session_start(). The call blocks until no other process holds the lock. For a request that only reads $_SESSION and never writes, the lock is still held for the full request duration. There is no read-shared mode.
Two properties make this especially insidious:
session.lazy_writedoes not help. This INI setting (default1since PHP 7.0) skips the write call if session data has not changed, but it does not release the lock early. The lock is held fromsession_start()untilsession_write_close()or script shutdown. Even read-only session access blocks all other requests for the same session ID.max_execution_timedoes not interrupt the block. On Unix,max_execution_timemeasures CPU time, not wall-clock time. Time spent sleeping insideflockis not CPU time, so a request blocked on a session lock can hang indefinitely regardless of timeout settings.request_terminate_timeoutin PHP-FPM is your only reliable kill switch for stuck workers, and even that only fires on wall-clock duration from request acceptance.
The serialization is per session ID, not global. One user with ten parallel AJAX requests sees all ten queue behind one lock. Two hundred users doing the same thing at once means two hundred independent lock queues, each consuming workers. Aggregate worker utilization climbs, CPU stays low, throughput collapses.
sequenceDiagram
participant Browser
participant Nginx
participant W1 as FPM Worker A
participant W2 as FPM Worker B
participant W3 as FPM Worker C
participant SF as Session file (flock LOCK_EX)
Browser->>Nginx: AJAX req 1 (sess=abc)
Browser->>Nginx: AJAX req 2 (sess=abc)
Browser->>Nginx: AJAX req 3 (sess=abc)
Nginx->>W1: dispatch req 1
Nginx->>W2: dispatch req 2
Nginx->>W3: dispatch req 3
W1->>SF: flock(LOCK_EX) acquired
W2->>SF: flock(LOCK_EX) BLOCKED
W3->>SF: flock(LOCK_EX) BLOCKED
W1-->>SF: script ends, lock released
Note over W2,SF: lock acquired by W2
W2-->>SF: script ends, lock released
Note over W3,SF: lock acquired by W3
W3-->>SF: script ends, lock releasedCommon causes
| Cause | What it looks like | First thing to check |
|---|---|---|
| AJAX-heavy page firing parallel requests with the same session cookie | One user’s page load is slow, server-wide metrics look normal | Slow log for session_start() frames on AJAX endpoints |
| Long-running request holding the session lock (file upload, report generation, slow external API call) | Intermittent slowness on specific endpoints, other requests for same user stall behind it | Per-worker request duration on the full status page |
| Polling endpoint (chat, notifications, progress) using PHP sessions | Steady-state worker saturation with low CPU, slow log shows polling URIs | Whether the polling route actually needs session write access |
| SPA batch-fetching multiple data endpoints on route change | Bursty latency spikes when users navigate, resolves between navigations | Browser devtools network tab for parallel same-session requests |
Read-only endpoint that calls session_start() out of habit or framework default | Endpoints that never write $_SESSION still block | Application code or framework middleware for unnecessary session_start() calls |
Quick checks
# Check session handler and save path (path varies by distro and php.ini)
php -r "echo 'handler: ' . ini_get('session.save_handler') . \"\n\"; echo 'path: ' . ini_get('session.save_path') . \"\n\"; echo 'lazy_write: ' . ini_get('session.lazy_write') . \"\n\";"
# Check for multiple processes holding or waiting on the same session file.
# Adjust the path to match your session.save_path.
lsof /var/lib/php/sessions/sess_* 2>/dev/null | awk '{print $9}' | sort | uniq -c | sort -rn | head
# Alternative with fuser if lsof is unavailable. Output format differs: PIDs
# are printed per file rather than one row per descriptor.
fuser /var/lib/php/sessions/sess_* 2>/dev/null
# Fetch the full status page (requires pm.status_path set in the pool config;
# the URL path depends on your web server and pm.status_path value).
curl -s http://127.0.0.1/status?full | head -80
# Slow log entries showing session_start blocking (requires request_slowlog_timeout > 0)
grep -A8 "session_start" /var/log/php-fpm/slow.log | head -40
# Confirm request_slowlog_timeout is configured (0 means disabled)
php-fpm -tt 2>&1 | grep -E "slowlog|request_slowlog_timeout"
# Check whether read_and_close or session_write_close is already used in the codebase
grep -rn "read_and_close\|session_write_close" /path/to/app/
If session.save_handler returns files, you are vulnerable to this contention pattern. If lsof shows two or more FPM worker PIDs against the same sess_* file, you have active contention right now.
How to diagnose it
Confirm the slow log is capturing session_start frames. If
request_slowlog_timeoutis0(disabled, the default), enable it first. A value of 2-5 seconds is sufficient for detecting session lock contention. Restart or reload the pool for the change to take effect, then wait for a reproduction or trigger one. The stack trace should show the worker stopped insidesession_start()or the session open callback, withlast request cpunear zero on the full status page.Cross-reference with lsof output. Run the
lsofcommand from the quick checks during a slow period. Multiple worker PIDs against a single session file confirms that requests are queuing on the lock, not on compute or database I/O.Check the CPU-to-active-process ratio. Compare
active processesfrom the status page against host CPU. If active workers are high but CPU utilization is low (under 20-30%), the workers are sleeping on something. Session locks are one cause; slow database queries and external API timeouts are the other usual suspects. The slow log distinguishes them: session lock contention showssession_start()in the trace, database contention shows PDO or mysqli calls.Identify the originating endpoints. The full status page exposes
request URIper worker. Look for patterns where multiple workers are serving the same user’s session (identical or related URIs from the same session cookie). AJAX endpoints, polling routes, and SPA data-fetch paths are the usual offenders.Distinguish from genuine worker exhaustion. In real worker exhaustion (traffic spike or slow backend), the slow log shows diverse URIs and diverse blocking points (database, curl, file I/O). In session lock contention, the slow log concentrates on
session_start()and the affected URIs are all from the same session ID. The telltale sign is low CPU with high active workers andsession_start()in every slow trace.
Metrics and signals to monitor
| Signal | Why it matters | Warning sign |
|---|---|---|
| Slow requests counter rate | Each increment is a request that exceeded request_slowlog_timeout, and the slow log tells you where | Sustained non-zero rate with session_start frames in the log |
| Active processes vs system CPU | Workers sleeping on flock show high active count but low CPU | Active climbing past 80% of max_children while CPU stays flat |
| Per-worker request duration (full status) | Blocked requests show long durations with low last request cpu | Bimodal distribution: some workers fast, some parked for seconds |
| Per-worker request URI (full status) | Identifies which endpoints are involved in contention | Multiple workers serving related URIs from the same session |
max children reached counter | Indicates the pool tried to scale and could not | Incrementing while CPU stays low suggests I/O-bound workers, not compute saturation |
Fixes
Close the session early in application code
The primary mitigation is calling session_write_close() as early as possible in the request lifecycle, after the last read or write to $_SESSION. This releases the flock immediately, letting the next queued request proceed.
// After all session reads/writes are done:
$_SESSION['last_activity'] = time();
session_write_close();
// Long-running work (API call, file processing, report generation) proceeds
// without holding the session lock.
$response = $httpClient->get('/slow-endpoint');
This is the lowest-risk fix because it does not change the session backend or application architecture. The tradeoff is that you cannot write to $_SESSION after calling session_write_close(). If you need to update session state later in the request, restructure the code to write first, close, then do the slow work.
Use read_and_close for read-only requests
Since PHP 7.0, session_start() accepts an options array. Passing ['read_and_close' => true] reads the session data and immediately releases the lock. This is useful for endpoints that need to check authentication or read session state but never modify it.
session_start(['read_and_close' => true]);
$user_id = $_SESSION['user_id'] ?? null;
// Lock is already released. Concurrent requests for this session proceed immediately.
One caveat: read_and_close does not update the session file’s modification time. If your application relies on session.gc_maxlifetime for session expiry based on last access time, read-only requests will not refresh the timer. Sessions can be garbage collected while still in active read-only use.
Do not start sessions on endpoints that do not need them
API endpoints returning JSON, static data endpoints, polling routes, and health checks often call session_start() through framework middleware even when they never touch $_SESSION. Audit your routing and middleware configuration. If an endpoint does not read or write session data, it should not start a session. This eliminates lock contention entirely for those routes.
Switch to a session backend with different locking semantics
If application-level fixes are impractical (large codebase, framework constraints, many endpoints), switching the session handler changes the locking model:
- Redis (phpredis): Does not lock by default. Locking can be opted into via
redis.session.locking_enabled=1. Without explicit locking enabled, concurrent requests for the same session proceed in parallel. This eliminates file-based flock contention but means concurrent writes to the same session can produce last-write-wins behavior. - Memcached: Locks by default (
memcached.sess_lockingdefaults to on). Switching to Memcached does not eliminate contention by itself, but the locking implementation uses a retry loop rather than a kernel flock, which can behave differently under high contention and avoids NFS-related flock issues.
Switching handlers requires careful testing of session consistency assumptions in your application. If your code assumes serialized session access (for example, using $_SESSION as a per-request mutation guard), removing locking can introduce race conditions.
Separate long-running endpoints from session-using ones
File uploads, report generation, and external API calls that take seconds should not hold a session lock. Either call session_write_close() before the slow work begins, or route these endpoints through a mechanism that does not use PHP sessions (a signed token, a job queue with polling, or a separate API path).
Prevention
- Enable
request_slowlog_timeouton every production pool. Without it, you have no visibility into where workers are blocking. A value of 2-5 seconds catches session lock contention before it saturates the pool. - Audit
session_start()calls. Every endpoint that starts a session but does not need write access should useread_and_closeor skip the session entirely. Frameworks that auto-start sessions on every request are the most common source of unnecessary locks. - Design parallel endpoints to be sessionless. If a page fires ten AJAX requests on load, at most one should hold a session lock. The other nine should authenticate via a token or cookie that does not require
session_start(). - Document the flock behavior for your team. The default file handler’s exclusive locking is not obvious from the API surface. Developers who have not encountered it will assume read-only session access is concurrency-safe.
How Netdata helps
- Per-second active and idle process counts let you see the active-but-low-CPU pattern that distinguishes lock contention from compute-bound saturation. A sudden climb in active workers with flat CPU is the leading indicator.
- Slow requests counter tracked as a rate, not just a cumulative gauge, surfaces the moment requests start exceeding
request_slowlog_timeout. Correlate the rate spike with the slow log to confirmsession_start()frames. - CPU utilization alongside PHP-FPM metrics on the same dashboard makes the I/O-bound diagnosis immediate. Low CPU with high active workers points to flock, database waits, or external API stalls; the slow log disambiguates.
- Anomaly detection on active process count can flag unexpected saturation events that do not match traffic patterns, which is often how session lock contention first surfaces during an AJAX-heavy page redesign or SPA migration.
- Listen queue depth monitoring at per-second resolution catches the downstream effect: once session-serialized workers fill the pool, the listen queue builds and connections start refusing.
Related guides
- PHP-FPM 502 Bad Gateway: the web server cannot reach the pool
- PHP-FPM 504 Gateway Timeout: requests accepted but never finishing in time
- PHP-FPM active processes near max_children: reading pool utilization
- PHP-FPM in containers: cgroup limits and the silent OOM kill
- PHP-FPM “child N exited on signal 11 (SIGSEGV)”: worker segfaults
- PHP-FPM “connect() failed (111: Connection refused) while connecting to upstream”
- PHP-FPM crash loop and fork storm: workers dying faster than they serve
- PHP-FPM dynamic mode scaling lag: why the pool cannot keep up with bursts
- PHP-FPM emergency restart: “failed processes threshold reached, initiating reload”
- PHP-FPM graceful reload: the brief no-worker window on SIGUSR2
- How PHP-FPM actually works in production: a mental model for operators
- PHP-FPM idle processes at zero: no burst headroom left






