Redis on VPS: Configuration, Persistence, Caching, Sessions, and Queue Setup

Redis on VPS: Configuration, Persistence, Caching, Sessions, and Queue Setup

Redis is an in-memory data store that accelerates web applications in three distinct ways: object caching (stores database query results and computed values so PHP doesn’t recompute them), session storage (faster than file-based sessions, works across multiple servers), and job queues (Laravel queues, BullMQ, Sidekiq all use Redis as the backend). A single Redis instance handles all three roles simultaneously on a VPS.

Install Redis

sudo apt update
sudo apt install -y redis-server

# Verify installation
redis-cli ping   # Should return: PONG

sudo systemctl enable redis-server
sudo systemctl status redis-server

Core Configuration

sudo nano /etc/redis/redis.conf

Network — Bind to Localhost Only

# SECURITY: only accept local connections (never expose Redis to internet)
bind 127.0.0.1 ::1

# Disable protected mode (we're binding to localhost — redundant but explicit)
protected-mode yes

# Default port
port 6379

Memory Limits and Eviction

# Set memory limit — prevents Redis from consuming all VPS RAM
# Rule of thumb: 10–20% of total RAM for cache workloads
# 1 GB VPS: maxmemory 128mb
# 2 GB VPS: maxmemory 256mb
# 4 GB VPS: maxmemory 512mb
maxmemory 256mb

# Eviction policy — what happens when memory is full:
# volatile-lru  : evict keys with TTL, least-recently-used first (good for caches)
# allkeys-lru   : evict any key LRU (best for pure cache use)
# noeviction    : return error when memory full (use for queues/sessions where data loss is unacceptable)
# allkeys-lfu   : evict least-frequently-used (better for uneven access patterns)
maxmemory-policy allkeys-lru

Persistence Options

# RDB snapshots: periodic point-in-time backup to disk
# Format: save SECONDS CHANGES
save 900 1     # Save if 1 change in 900 seconds (15 min)
save 300 10    # Save if 10 changes in 300 seconds (5 min)
save 60 10000  # Save if 10,000 changes in 60 seconds

# RDB file location
dir /var/lib/redis
dbfilename dump.rdb

# AOF (Append Only File): logs every write — more durable but uses more disk
# Enable only for queues/sessions where durability matters
# appendonly yes
# appendfsync everysec

Security — Password Authentication

# Generate a strong password
openssl rand -base64 32

# Set in redis.conf:
requirepass YourVeryStrongRedisPassword!
sudo systemctl restart redis-server

# Test password authentication
redis-cli AUTH YourVeryStrongRedisPassword! ping   # Should return PONG

Use Case 1: WordPress Object Caching

Install the Redis Object Cache plugin in WordPress, then configure the connection:

# Add to wp-config.php:
define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_PORT', 6379);
define('WP_REDIS_PASSWORD', 'YourVeryStrongRedisPassword!');
define('WP_REDIS_DATABASE', 0);   # Use DB 0 for WordPress
define('WP_REDIS_PREFIX', 'wp_yoursite_');  # Prefix if multiple WP sites
define('WP_CACHE', true);

After activation, WordPress stores query results and computed values in Redis. Re-rendering the same page uses cached data instead of running database queries.

# Monitor WordPress cache hit rate
redis-cli -a YourVeryStrongRedisPassword! INFO stats | grep -E "keyspace_hits|keyspace_misses"
# High hit rate (>80%) means cache is working effectively

Use Case 2: PHP Session Storage

Store PHP sessions in Redis instead of files — faster and works across multiple web servers:

sudo apt install -y php8.2-redis

sudo nano /etc/php/8.2/fpm/php.ini
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379?auth=YourVeryStrongRedisPassword!&database=1"

; Session lifetime in seconds (24 hours)
session.gc_maxlifetime = 86400
sudo systemctl restart php8.2-fpm

Use Case 3: Laravel Queue Backend

# .env
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=YourVeryStrongRedisPassword!
REDIS_PORT=6379
REDIS_QUEUE_DB=2   # Use DB 2 for queues
# config/database.php — multiple Redis connections:
'redis' => [
    'client' => env('REDIS_CLIENT', 'phpredis'),
    'default' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD'),
        'port' => env('REDIS_PORT', '6379'),
        'database' => 0,   # Cache
    ],
    'cache' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD'),
        'port' => env('REDIS_PORT', '6379'),
        'database' => 0,
    ],
    'queues' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD'),
        'port' => env('REDIS_PORT', '6379'),
        'database' => 2,   # Queues on DB 2 (isolated)
    ],
]
# Dispatch a job
php artisan make:job ProcessOrder
php artisan queue:work redis --queue=default --tries=3 --backoff=60

Use Case 4: Node.js / BullMQ Queue

npm install bullmq ioredis
// queue.js
import { Queue, Worker } from 'bullmq';
import { Redis } from 'ioredis';

const connection = new Redis({
    host: '127.0.0.1',
    port: 6379,
    password: 'YourVeryStrongRedisPassword!',
    db: 2,
});

// Create queue
const emailQueue = new Queue('emails', { connection });

// Add job
await emailQueue.add('send-welcome', {
    userId: 123,
    email: 'user@example.com',
});

// Process jobs
const worker = new Worker('emails', async (job) => {
    console.log(`Processing ${job.name}:`, job.data);
    // await sendEmail(job.data.email);
}, { connection });

Monitoring Redis

# Real-time statistics
redis-cli -a YourVeryStrongRedisPassword! INFO all | grep -E "used_memory_human|connected_clients|keyspace_hits|keyspace_misses|total_commands_processed"

# Live command monitor (shows every command in real time — use briefly)
redis-cli -a YourVeryStrongRedisPassword! MONITOR

# Database key counts
redis-cli -a YourVeryStrongRedisPassword! INFO keyspace

# Slow query log (commands taking >10ms)
redis-cli -a YourVeryStrongRedisPassword! SLOWLOG GET 10

# Memory usage analysis
redis-cli -a YourVeryStrongRedisPassword! MEMORY USAGE mykey
redis-cli -a YourVeryStrongRedisPassword! MEMORY DOCTOR

Getting Started

Redis is one of the most impactful additions to a WordPress or PHP application stack. On a 2 GB Ubuntu VPS at VPS.DO, allocating 256 MB to Redis leaves 1.75 GB for the application stack while delivering database query caching that reduces PHP response time by 50–80% for typical WordPress workloads.

Conclusion

A single Redis instance handles object caching, session storage, and job queues simultaneously — three high-value use cases from one lightweight service using 50–150 MB RAM at typical load. Bind Redis to localhost, set a strong password, configure maxmemory to prevent runaway RAM usage, and choose an eviction policy appropriate for each use case. For pure caching, allkeys-lru is the right choice; for queues and sessions where data loss is unacceptable, disable eviction and enable AOF persistence.

Fast • Reliable • Affordable VPS - DO It Now!

Get top VPS hosting with VPS.DO’s fast, low-cost plans. Try risk-free with our 7-day no-questions-asked refund and start today!