Skip to content

PHP sessions with Redis: replacing disk sessions in production

Move PHP session storage from local disk to Redis to enable horizontal scaling, reduce I/O contention, and gain atomic session locking without changing application code.

PHP’s default session handler writes session data to files in /var/lib/php/sessions (or wherever session.save_path points). That works on a single server but immediately breaks on two: the second node has no knowledge of sessions written by the first. Even on a single server, disk-backed sessions create I/O contention under concurrent AJAX requests because PHP holds a file lock for the entire session duration. Switching to Redis eliminates both problems: sessions live in a shared in-memory store, and the Redis handler provides atomic locking with a configurable timeout.

How to verify

Check the current session handler and confirm Redis is reachable:

php -i | grep -E 'session.save_handler|session.save_path'
php -r "echo session_save_path() . PHP_EOL;"
# Check Redis connectivity
redis-cli -h 127.0.0.1 -p 6379 ping
# If using a password:
redis-cli -h 127.0.0.1 -p 6379 -a "$REDIS_PASSWORD" ping
# Confirm the phpredis or Predis extension is available
php -m | grep -i redis
# Count existing file-based sessions
ls /var/lib/php/sessions/ | wc -l

What’s happening

PHP’s session handling is pluggable via session.save_handler. The two relevant options for Redis are:

phpredis — the C extension (ext-redis). It implements the SessionHandlerInterface natively. Configure it by setting session.save_handler = redis and providing a Redis DSN in session.save_path. The extension handles locking, serialization, and TTL management internally. It is the correct choice for new installations.

Predis — a pure-PHP Redis client library. It requires a custom SessionHandlerInterface implementation in application code. Slower than phpredis due to PHP-level overhead, but has no C extension dependency. Useful in environments where installing PHP extensions is constrained (some PaaS platforms).

The phpredis session handler stores each session as a Redis string key with the pattern PHPREDIS_SESSION:SESSIONID (configurable via session.save_path options). The value is the serialized session data. The key TTL is set to session.gc_maxlifetime seconds and is refreshed on every session_write_close() call. Session locking is implemented using Redis’s SET key value NX PX timeout pattern — a Redis-native atomic compare-and-set that prevents concurrent requests from reading a half-written session.

The procedure

1. Install the phpredis extension.

# Ubuntu/Debian
sudo apt install php8.3-redis

# RHEL/CentOS via Remi repo
sudo dnf install php83-php-redis

# PECL (any platform)
sudo pecl install redis
echo "extension=redis.so" | sudo tee /etc/php/8.3/mods-available/redis.ini
sudo phpenmod redis

Verify:

php -m | grep redis
php --ri redis | grep -E 'Version|Redis'

2. Configure the session handler system-wide.

Edit /etc/php/8.3/fpm/php.ini (or a per-pool php_value override):

session.save_handler = redis
session.save_path    = "tcp://127.0.0.1:6379?auth=yourpassword&database=1&prefix=app_sess_&persistent=0"
session.gc_maxlifetime = 1440

DSN parameters:

ParameterDefaultDescription
authnoneRedis requirepass password
database0Redis DB index (use a dedicated index for sessions)
prefixPHPREDIS_SESSION:Key prefix in Redis
persistent0Whether to use a persistent connection (1 reduces handshake overhead)
timeout86400Connection timeout in seconds
read_timeout0 (no timeout)Read timeout — set to 5 for safety
retry_interval0MS between reconnect attempts
failovernoneerror or distribute for sentinel/cluster failover

3. Enable session locking (critical for correctness).

Locking prevents concurrent requests for the same session from corrupting data. It is enabled by default in phpredis sessions but requires a lock TTL:

; Maximum time to wait for a session lock, in ms (raise for slow pages)
redis.session.locking_enabled = 1
redis.session.lock_expire      = 5000
redis.session.lock_wait_time   = 100
redis.session.lock_retries     = 50

These can also be passed as DSN parameters: &locking_enabled=1&lock_expire=5000.

4. Set a dedicated Redis database for sessions.

Using database=1 (or any non-default index) prevents session keys from polluting the same keyspace as application cache keys. It also lets you flush all sessions with SELECT 1; FLUSHDB without touching cache.

5. Reload FPM and verify.

systemctl reload php8.3-fpm
# Create a test session
php -r '
session_start();
$_SESSION["test"] = "ok";
session_write_close();
echo session_id() . PHP_EOL;
'
# Check the key in Redis (replace SESSION_ID with output above)
redis-cli -n 1 KEYS "app_sess_*" | head -5
redis-cli -n 1 TTL "app_sess_SESSION_ID"

6. Migrate existing file sessions (optional).

For zero-disruption cutover, write a migration script that reads existing session files and writes them into Redis before switching the handler:

for f in /var/lib/php/sessions/sess_*; do
  id="${f##*/sess_}"
  data=$(cat "$f")
  redis-cli -n 1 SET "app_sess_${id}" "$data" EX 1440
done

Switch the handler, then clear the old files after a full gc_maxlifetime window has passed.

Common pitfalls

Not setting session.gc_maxlifetime to match application expectations. Redis uses the TTL as the session lifetime; PHP’s GC never runs for Redis sessions. If you previously relied on PHP’s GC (session.gc_probability / session.gc_divisor) to clean up old sessions, that mechanism is now irrelevant — the TTL takes over completely.

Using database 0 alongside application cache. If application cache (OPcache local shards, general app cache) also uses Redis database 0, a FLUSHDB to clear cache wipes all active sessions. Always isolate sessions to their own database index.

Not enabling locking for applications with concurrent AJAX calls. A typical page that fires 5 simultaneous authenticated AJAX requests will have 5 concurrent session reads. Without locking, the last writer wins and any session data written by the first 4 requests is silently discarded. Enable locking and tune lock_wait_time and lock_retries to avoid deadlocks on slow pages.

Using persistent = 1 without understanding connection limits. Persistent connections are reused across FPM requests within the same worker process. With 20 workers each holding a persistent connection, that’s 20 connections against Redis — manageable. But if pm.max_children = 100 and you have multiple pools, you can easily exceed Redis’s maxclients (default 10000 on modern Redis, but lower in constrained environments).

Not configuring read_timeout. The default read timeout of 0 (infinite) means a Redis connectivity problem causes FPM workers to hang indefinitely, eventually exhausting the pool. Set read_timeout=5 to fail fast and return a 500 rather than queue all workers behind a stalled Redis call.

For Redis session infrastructure — including replication, persistence configuration (appendonly, save directives), and monitoring for session-related latency — the Stack Harbor managed operations service handles the full data layer.