Same-user requests that should run in parallel are completing one after another. AJAX panels load sequentially, dashboards stall on parallel fetches, and the slow log shows workers blocked at session_start(). The PHP-FPM pool has spare capacity and CPU is low. This is session lock serialization, and the fix is almost always one of two moves: release the file lock earlier with session_write_close(), or move sessions to a backend whose locking semantics do not serialize the same user.

This is the remediation companion to session lock contention. It assumes you have already confirmed the symptom: the slow log pointing at session_start(), multiple FPM workers waiting on the same sess_* file, or AJAX endpoints that queue per user. The focus is choosing the right fix, applying it safely, and confirming the contention is gone.

Both fixes change how session state is observed and written, so each has trade-offs. session_write_close() is a small change with a sharp edge: any $_SESSION writes after the call are silently dropped. Redis (or Memcached) handlers change the storage backend, but their locking behavior is configurable and version-dependent, and getting it wrong can make sessions silently disappear instead of serialize.

A third factor, the serialization handler, often surfaces at the same time. With the default session.serialize_handler = php, session keys containing the pipe character (|) silently corrupt the encoded session and data is lost on the next read. This is not lock contention, but it shows up when teams move handlers or migrate to Redis and suddenly notice missing session data.

What this means

PHP’s default session handler opens the session file and acquires an exclusive lock (flock(LOCK_EX)) at session_start(). The lock is held until the request ends or session_write_close() is called. While the lock is held, any other request for the same session ID blocks at its own session_start() waiting for LOCK_EX. Even a request that only reads session data takes the exclusive lock; the file handler has no read-only mode.

The result is that concurrent requests from one browser session (typical for SPAs, dashboard widgets, polling endpoints, and parallel uploads) serialize end to end. Request B cannot begin until request A finishes. From the outside this looks like latency or worker exhaustion, but the FPM pool usually has idle workers. The bottleneck is the lock, not capacity.

Two mitigations address this directly:

  • Release the lock earlier. Call session_write_close() as soon as the request no longer needs to write to the session. Subsequent same-user requests can proceed in parallel.
  • Change the locking semantics. Move sessions to Redis or Memcached. The phpredis handler implements locking with SET NX PX (atomic set-if-not-exists with TTL) and you can tune or disable it independently of the request lifecycle.

Common causes

CauseWhat it looks likeFirst thing to check
File-based session lock held for the whole requestSlow log stack traces blocked at session_start(); multiple workers in lsof against the same sess_* filerequest_slowlog_timeout enabled and slow log path readable
session_write_close() never calledLong-running endpoints (uploads, external API calls, report generation) hold the lock until request endGrep application code for session_write_close and session_start
phpredis v6 upgrade regressionSessions “disappearing” after upgrade; session_start() returns false under contentionphpredis version (php --ri redis) and redis.session.locking_enabled
Serialization handler mismatch$_SESSION keys with `` cause data loss on read; sessions reset randomly

Quick checks

These are read-only and safe to run during an incident. Note that php -i shows CLI config; FPM often uses a different INI file. For FPM’s actual session settings, serve a temporary phpinfo() page through the web server or check the FPM pool’s loaded configuration with php-fpm -tt.

# Confirm file-based sessions are in use and find the save path
# NOTE: CLI config may differ from FPM -- verify via phpinfo() if uncertain
php -i 2>/dev/null | grep -E "session.save_handler|session.save_path|session.serialize_handler"

# Look for multiple processes blocked on the same session file
lsof /var/lib/php/sessions/sess_* 2>/dev/null | awk '{print $9}' | sort | uniq -c | sort -rn | head

# Slow log entries showing session_start blocking
grep -A5 "session_start" /var/log/php-fpm/slow.log | head -40

# Check phpredis version and locking configuration
php --ri redis | grep -i version
php -i 2>/dev/null | grep -E "redis.session"

# Per-worker request durations and the script being executed
curl -s "http://127.0.0.1/fpm-status?json&full" | python3 -c "
import sys, json
data = json.load(sys.stdin)
for proc in data['processes']:
    if proc['state'] == 'Running':
        print(f\"{proc['request duration']/1e6:.3f}s  {proc['request uri']}\")"

How to diagnose it

  1. Confirm the symptom is per-user serialization, not pool exhaustion. If active processes is well below pm.max_children and listen queue is zero but specific endpoints are slow, suspect session locking. If the pool is at capacity, address that first.
  2. Enable request_slowlog_timeout if not already set (for example 5s). The slow log is the only signal that names the blocking function. Look for stack traces whose top frames are session_start or flock.
  3. Identify the session file with multiple waiters. lsof on session files in the save path shows which sess_* files have more than one PHP-FPM worker attached.
  4. Confirm the request pattern. AJAX-heavy pages, polling endpoints, and SPAs that fire parallel requests for the same logged-in user are the typical trigger. The same endpoints called sequentially do not reproduce the issue.
  5. Rule out serialization-handler data loss separately. If sessions are randomly resetting, check whether any $_SESSION keys contain |. The default php serialize handler cannot encode pipe characters in keys.
flowchart td
  A[Same-user requests serialize] --> B{Slow log shows session_start?}
  B -- Yes --> C{Pool has idle workers?}
  C -- Yes --> D[Session lock contention]
  C -- No --> E[Fix worker exhaustion first]
  D --> F{App can release session early?}
  F -- Yes --> G[session_write_close
or read_and_close] F -- No --> H[Move to Redis handler] H --> I{Sessions missing after move?} I -- Yes --> J[Check phpredis version
and serialize_handler] I -- No --> K[Contention resolved] G --> K

Metrics and signals to monitor

SignalWhy it mattersWarning sign
Slow log entries at session_startDirect evidence of session lock waitsSustained non-zero rate during normal traffic
Active vs idle workersDistinguishes lock contention from pool exhaustionIdle workers available while endpoints are slow
Per-worker request duration (full status)Shows bimodal latency on session-heavy endpointsSubset of workers stuck well past p95
phpredis redis.session.locking_enabledDetermines whether Redis sessions lock at allSet to 1 with default retry budget on slow pages
Redis connected clientsSessions are now network calls to RedisClient count climbing in step with FPM workers
FPM worker RSS post-migrationCatch leaks introduced by a new session handlerUpward trend after handler change

Fixes

Release the lock early with session_write_close()

The smallest, lowest-risk change is to release the session lock as soon as the request no longer needs to write. All modern PHP versions support this. The function writes the current session data, releases LOCK_EX, and leaves $_SESSION populated and readable. Any later writes to $_SESSION are silently discarded.

// Read whatever the request needs from the session
$userId = $_SESSION['user_id'] ?? null;

// Do any final session write for this request
$_SESSION['last_activity'] = time();

// Release the lock. $_SESSION stays readable; further writes are lost.
session_write_close();

// Long-running work that no longer needs the session:
// external API call, file upload, report generation, polling
$response = $httpClient->get('/slow/endpoint');

Two common traps:

  • Late writes disappear. If application code writes to $_SESSION after session_write_close() (in a destructor, a middleware terminator, a framework shutdown handler), the write goes nowhere and there is no warning. Audit the request lifecycle before adding the call.
  • Session re-opened after close. A destructor or shutdown handler that calls session_start() again re-acquires the lock and holds it until request end. This defeats the purpose.

For requests that never need to write the session at all, use the read-and-close shorthand added in PHP 7.0:

session_start(['read_and_close' => true]);

This opens the session, reads the data, and immediately releases the lock without writing. It is the right default for read-only endpoints that previously held the exclusive lock for the whole request. Note that session.lazy_write = 1 (the default since PHP 7.0) reduces write I/O but does not release the lock early, so it is not a substitute for session_write_close().

This fix is appropriate when you control the code and the write pattern is well-understood. It does not help when the session is genuinely needed for the full duration of a long-running request.

Move sessions to Redis

Switching to Redis changes the locking model. With the phpredis handler, locking is opt-in and uses SET NX PX (atomic set-if-not-exists with TTL) instead of flock. When locking is disabled, parallel same-user requests do not block at all: they read independently and the last writer wins on close.

Configure the handler via the DSN in session.save_path:

session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379?auth=secret&database=1&timeout=2&read_timeout=5"

Always set read_timeout to a finite value. The default read_timeout=0 means infinite, so a Redis connectivity issue will hang FPM workers indefinitely.

Locking-related INI settings:

redis.session.locking_enabled = 0      ; default; no cross-request locking
; redis.session.locking_enabled = 1    ; opt in for explicit lock
redis.session.lock_retries = 100       ; <!-- TODO: verify v6 default. Believed 100 in v6, 10 in v5 -->
redis.session.lock_wait_time = 20000   ; microseconds; <!-- TODO: verify v6 default. Believed 20000 in v6, 2000 in v5 -->
redis.session.lock_expire = 0          ; 0 = follow max_execution_time

With the v6 defaults (lock_retries=100, lock_wait_time=20000us), the handler waits roughly two seconds total before giving up on a lock. That is fine for fast pages but low for anything that legitimately holds a session for longer. For production with mixed request durations, raise both: lock_retries=2000 and lock_wait_time=50000 gives roughly 100 seconds of total wait.

Two important constraints on Redis session locking:

  • Cluster and array mode are not supported. phpredis session locking only works against a single Redis master (including Sentinel-managed setups). RedisCluster and RedisArray do not implement it.
  • PHP 8.4 and session_set_save_handler(). If you have a custom handler built on the old callback signature, migrate to SessionHandlerInterface before upgrading.

Memcached is a reasonable alternative with similar mechanics, but its locking behavior is configured differently and is outside the scope of this article.

The phpredis v6 lock-failure regression

If you enable locking and then upgrade phpredis from v5 to v6, sessions can appear to disappear under contention. In v5, lock acquisition failure silently degraded to a read-only session. In v6.0.0 this changed: when locking is enabled and the lock cannot be acquired, session_start() returns false and $_SESSION is not populated. Applications that do not check the return value see an empty session.

Two remediation paths:

  • Upgrade to phpredis v6.3.0+ and set redis.session.lock_failure_readonly=1. This restores the v5 behavior of falling back to a read-only session when the lock cannot be acquired. PR #2665 (merged July 10, 2025) added the setting.
  • If you cannot upgrade, tune the lock budget. Raising lock_retries and lock_wait_time reduces the probability of lock failure on slow pages. Disabling locking (redis.session.locking_enabled = 0) eliminates the failure mode entirely but gives up cross-request mutual exclusion.

This is a behavior change, not a bug in your code. It bites teams on upgrade because the symptom (sessions vanishing under load) does not obviously point at the session handler.

Fix the serialization handler

If you are changing handlers and session data is going missing, check session.serialize_handler. The default php handler uses an internal format where | separates the key name from the serialized value. When a key itself contains |, the encoded string becomes ambiguous and session_decode() misparses it on the next read, resulting in an empty or corrupted $_SESSION.

session.serialize_handler = php_serialize

php_serialize uses serialize() directly and has no character restrictions. It is the safe default for new deployments. The php_binary handler exists but has its own quirks. The wddx handler was deprecated in PHP 8.1 and removed in PHP 8.4, so it is unavailable in current builds.

Two forward-compatibility notes:

  • For PHP versions before 8.5, data loss from pipe characters in keys is silent.
  • Mixing handlers between requests is unsafe. A session written under php and read under php_serialize (or vice versa) will be corrupted. Change the handler once and clear existing sessions if you cannot guarantee compatibility.

Confirming the contention is gone

After applying the fix, verify with the same signals that identified the problem:

  • The slow log no longer shows stack traces blocked at session_start() (or at the Redis lock acquisition path).
  • lsof against the session save path no longer shows multiple workers per sess_* file (only relevant while file sessions are still in use during a migration).
  • Per-worker request durations on previously serialized endpoints drop to their natural p50 and p95; the bimodal distribution flattens.
  • The PHP-FPM pool shows the expected relationship between active workers and request rate: more concurrency on session-heavy endpoints without a corresponding spike in active processes.

For Redis-backed sessions, also confirm the Redis side is healthy: client count tracks FPM worker count, INFO clients shows no abnormal growth, and there are no connection errors during traffic peaks.

Prevention

  • Treat sessions as read-mostly. Open them, copy out what you need, and close them. session_write_close() belongs in the standard request lifecycle, not just on slow endpoints.
  • Use session_start(['read_and_close' => true]) as the default for any endpoint that does not write the session.
  • Standardize on session.serialize_handler = php_serialize to avoid pipe-key data loss.
  • Pin the phpredis version in your deployment pipeline and test session behavior under load before upgrading across the v5 to v6 boundary.
  • Document the lock budget (lock_retries, lock_wait_time, lock_expire) wherever you document the Redis DSN. Defaults are not safe for slow pages.

How Netdata helps

  • Per-second PHP-FPM status metrics (active processes, idle processes, listen queue, slow requests) let you distinguish per-session serialization from pool-wide exhaustion.
  • Per-worker request duration from the full status page correlates with slow-log session_start blocking and confirms when it stops.
  • Redis metrics (connected clients, command latency, memory, persistence fork events) surface new bottlenecks introduced by moving sessions to Redis.
  • Per-process and cgroup memory metrics catch leaks introduced by a handler or serialization change.
  • Anomaly detection on slow-request rate and per-worker duration flags regressions after a phpredis upgrade.