Redis vs. The File System: Scaling PHP Sessions in High-Load Environments
It starts with a creeping specific sluggishness. Your load average spikes, but your CPU is idling at 10%. You check top and see the real killer: %wa (iowait). Your disk is thrashing. If you are running a high-traffic Magento store or a busy forum on default PHP settings, you aren't CPU bound; you are locking yourself out of your own server because of how sessions are handled.
I recently audited a setup for a client in Oslo expecting heavy traffic for a seasonal campaign. They were running a standard LAMP stack on a decent mid-range server. As soon as concurrent users hit 500, the site crawled. The culprit? /var/lib/php/session. Thousands of tiny files being read and locked simultaneously. The disk heads couldn't keep up.
The solution in 2011 isn't throwing more spinning rust at the problem. It's moving state where it belongs: RAM. Specifically, using Redis.
Why Redis? (And why not Memcached?)
For years, Memcached was the go-to for offloading sessions. It's fast, but it's volatile. If your Memcached daemon restarts, every active user gets logged out instantly. In an e-commerce context, that means emptied shopping carts and lost revenue.
Redis (Remote Dictionary Server) has matured significantly with version 2.2. It gives us the speed of in-memory storage with the reliability of disk persistence. It supports structured data types, but for sessions, we care about two things: Atomic operations and Persistence.
Pro Tip: Unlike Memcached, Redis can be configured to persist data to disk asynchronously. You get the speed of RAM without the terror of total data loss during a service restart.
Implementation: Ditching Files for TCP
Let's get technical. Assuming you are running a CentOS 5 or Ubuntu 10.04 LTS environment, we need the Redis daemon and the PHP extension (phpredis).
1. Install Redis
If you are on Enterprise Linux (RHEL/CentOS), you'll need the EPEL repository enabled.
# Install Redis
yum install redis
# or for Debian/Ubuntu
apt-get install redis-server
# Start the daemon
/etc/init.d/redis start
2. The PHP Extension
We need to compile the PHP extension. Don't rely on old package repositories here; build it from source to match your PHP version (likely 5.3).
pecl install redis
Once installed, add the extension to your configuration:
# /etc/php5/conf.d/redis.ini
extension=redis.so
3. Configuring PHP to use Redis
This is where the magic happens. We tell PHP to stop writing files to the disk and start talking to the Redis port (6379).
Edit your php.ini or your specific virtual host configuration:
[Session]
; Default is files
; session.save_handler = files
; New handler
session.save_handler = redis
; Point to your local Redis instance
; You can also use a socket for even lower latency
session.save_path = "tcp://127.0.0.1:6379"
Optimizing Redis for Sessions
Out of the box, Redis is configured for general purpose. For session management, we need to tweak redis.conf to ensure we don't run out of memory and that we persist data intelligently.
Open /etc/redis/redis.conf:
# Snapshotting: Save to disk if 1 key changed in 900 seconds
# or 10 keys changed in 300 seconds
save 900 1
save 300 10
# Max Memory Policy
# This is crucial. If Redis fills up, we want it to evict old keys (expired sessions)
# rather than crashing or rejecting writes.
maxmemory 256mb
maxmemory-policy volatile-lru
The volatile-lru setting is vital. It tells Redis: "If you run out of RAM, remove the keys that have an expire set (sessions) and haven't been used recently." This keeps your active users online while cleaning up the dead weight.
The Hardware Factor: Latency & Virtualization
Even with Redis, your infrastructure matters. Redis is single-threaded. It is bound by the speed of your CPU core and your memory latency. This is where the "noisy neighbor" effect of cheap VPS hosting becomes a liability.
In older virtualization technologies like Virtuozzo or standard OpenVZ, you are often fighting for kernel locks with other tenants. If another container on the host is thrashing memory, your Redis instance stutters.
| Feature | Budget VPS (OpenVZ) | CoolVDS (KVM) |
|---|---|---|
| Memory Guarantee | Burstable (Shared) | Dedicated (Hard Reserved) |
| Kernel Access | Shared Kernel | Dedicated Kernel |
| Disk I/O | Often SATA 7.2k | Enterprise SSD / SAS 15k |
At CoolVDS, we utilize KVM (Kernel-based Virtual Machine). This ensures that the RAM you allocate to Redis is yours. It is not borrowed. Furthermore, our infrastructure in Oslo is directly peered at NIX (Norwegian Internet Exchange). If your target audience is in Norway, the round-trip time (RTT) is practically negligible. When every millisecond counts for database calls, network proximity is a physical advantage you cannot code around.
Data Privacy in Norway (Datatilsynet)
A quick note for the Pragmatic CTOs: Storing session data involves personal identifiers. Under the Norwegian Personal Data Act (Personopplysningsloven), you are responsible for securing this data. Redis keeps data in RAM, but if you enable persistence (writing to disk), that file must be on a secure partition.
By hosting on CoolVDS within Norway, you ensure that your data remains within the jurisdiction of Datatilsynet, avoiding complex legal gray areas associated with hosting data across the Atlantic.
Testing the Setup
After restarting Apache/PHP-FPM and Redis, verify it's working. Don't just hope. Check.
Then, inspect Redis via the command line:
$ redis-cli
redis 127.0.0.1:6379> keys *
1) "PHPREDIS_SESSION:j98234f98234..."
redis 127.0.0.1:6379> get "PHPREDIS_SESSION:j98234f98234..."
"hero|s:7:\"CoolVDS\";time|i:1310392000;"
If you see the key, you have successfully eliminated disk I/O from your session handling. Your application can now scale to thousands of concurrent users without the file system choking.
Don't let legacy configurations bottleneck your growth. High-performance hosting requires high-performance configuration.
Ready to test your new Redis configuration on real hardware? Deploy a KVM instance on CoolVDS today and feel the difference of local Norwegian peering and pure SSD performance.