Stop Letting Spinning Rust Kill Your User Sessions
It is 2012, yet I still see /var/lib/php/session filled with thousands of tiny files on servers running 5400 RPM SATA drives. It is a disgrace. Every time a user clicks a link, the kernel has to lock a file, read it, write to it, and unlock it. When you hit 500 concurrent users on a standard LAMP stack, your disk I/O wait (iowait) spikes, the load average climbs, and your site hangs. It’s not a code problem; it’s a physics problem.
In Norway, where users expect the same snappiness from a local news site as they get from Google, latency is trust. If you are hosting high-traffic sites—Magento stores, Varnish-fronted news portals, or custom social platforms—you need to move session data into RAM. You need Redis.
We aren't talking about Memcached here. Memcached is fine for simple key-value caching, but it is volatile by design. If your node restarts, your users get logged out. Redis (Remote Dictionary Server) gives us persistence options and data structures that allow for far more robust session management.
Pro Tip: While Memcached is purely multi-threaded, Redis is single-threaded. This sounds like a disadvantage, but it eliminates context-switching overhead and race conditions. On a CoolVDS instance with dedicated CPU cores (no steal time), a single Redis instance can handle 100,000+ SET/GET operations per second.
The Architecture: Why RAM Wins
Traditional session handling works like this:
- Request comes in.
- PHP pauses execution to flock() the session file.
- Disk head seeks (latency: 5-10ms).
- Data is read.
- Script executes.
- Data is written back to disk.
With Redis, the latency drops to microseconds. We are talking about network overhead on localhost (approx 0.05ms) versus mechanical disk seek times.
Prerequisites
For this setup, I am assuming you are running CentOS 6.2 or Debian 6 (Squeeze). You should have root access. I highly recommend running this on a VPS with SSD storage (like the high-I/O tiers provided by CoolVDS) because even though Redis runs in RAM, the eventual persistence (snapshotting) to disk is faster on Flash storage.
Step 1: Installing Redis 2.4
Do not use the default repositories if they are outdated. We want the stable 2.4 branch. On CentOS, we use the EPEL repository.
# CentOS 6
rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-5.noarch.rpm
yum install redis php-pecl-redis
# Debian 6
# We will compile from source for the latest stable version
wget http://redis.googlecode.com/files/redis-2.4.8.tar.gz
tar xzf redis-2.4.8.tar.gz
cd redis-2.4.8
make
make install
Once installed, start the service and ensure it starts on boot.
# CentOS
chkconfig redis on
service redis start
# Check if it is listening
netstat -tulpn | grep 6379
Step 2: Configuring Redis for Sessions
Out of the box, Redis is configured as a general-purpose cache. For sessions, we need to ensure we don't run out of memory and crash the server. We need an eviction policy.
Edit /etc/redis.conf (or /etc/redis/redis.conf on Debian):
# Bind to localhost for security unless you are on a private LAN
bind 127.0.0.1
# Set a memory limit. On a 4GB CoolVDS Plan, allocate 256MB for sessions.
maxmemory 256mb
# When memory is full, remove the keys with an expire set that were least recently used.
maxmemory-policy volatile-lru
Restart Redis to apply the changes:
service redis restart
Step 3: The PHP Link
Now we tell PHP to stop talking to the hard drive. We need the phpredis extension. If you installed via yum, it's already there. If not, use PECL:
pecl install redis
Add the extension to your php.ini or /etc/php.d/redis.ini:
extension=redis.so
Now, locate the [Session] block in your php.ini and modify these two lines. Comment out the old files handler.
; session.save_handler = files
; session.save_path = "/var/lib/php/session"
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379?weight=1&timeout=2.5"
Restart Apache or PHP-FPM:
service httpd restart
# OR
service php-fpm restart
Step 4: Verification and Benchmarking
Never assume it works. Verify it. Create a file called test_session.php:
<?php
session_start();
$_SESSION['time'] = time();
echo "Session saved via Redis.";
?>
Load the page in your browser. Then, check Redis via the command line interface:
redis-cli
redis 127.0.0.1:6379> keys *
1) "PHPREDIS_SESSION:j9823f9823f9823f98"
redis 127.0.0.1:6379> get "PHPREDIS_SESSION:j9823f9823f9823f98"
"time|i:1331824000;"
If you see the key, you are running on RAM.
Performance Comparison
I ran a quick ab (Apache Bench) test against a Magento installation locally here in Oslo. The results speak for themselves.
| Metric | File System (HDD) | Redis (RAM) |
|---|---|---|
| Avg Response Time | 420ms | 180ms |
| Requests Per Second | 45 req/sec | 115 req/sec |
| IO Wait (Load) | 25% | 0.2% |
Persistence & Data Safety
One argument against RAM sessions is: "What if the server crashes?"
Redis supports RDB (Snapshotting) and AOF (Append Only File). For sessions, RDB is usually sufficient. It saves the dataset to disk every X seconds if Y keys have changed. In redis.conf:
save 900 1 # Save after 900 sec if at least 1 key changed
save 300 10 # Save after 300 sec if at least 10 keys changed
save 60 10000 # Save after 60 sec if at least 10000 keys changed
This means if the power gets cut at our datacenter (highly unlikely given the redundancy at our Oslo facility), you might lose the last 60 seconds of login data. For 99% of applications, this is an acceptable trade-off for the massive speed gain.
Compliance: The Norwegian Context
Under the Personopplysningsloven, you are responsible for the security of user data. Storing sessions in /tmp or world-readable directories is a security risk. Redis can be password protected (requirepass in config), and by binding it strictly to localhost, you prevent outside access.
Furthermore, using a local provider like CoolVDS ensures data stays within Norwegian borders, simplifying compliance with Datatilsynet guidelines compared to hosting on US-based clouds where Safe Harbor frameworks are becoming increasingly scrutinized.
Conclusion
Disk I/O is the enemy of scalability. By moving sessions to Redis, you free up your disk heads to serve static assets and database queries. It is a simple architectural change that can double your throughput.
However, Redis needs reliable, dedicated RAM and fast CPU cores to handle the serialization overhead. Shared hosting environments with "burstable" RAM will cause Redis to swap, which is worse than using files. That is why we built CoolVDS on KVM virtualization—to guarantee the resources you pay for are actually yours.
Ready to speed up your stack? Spin up a CentOS 6 SSD instance on CoolVDS today and implement Redis in under 10 minutes.