Redis on a VPS: Setting Up a Caching Layer for High-Traffic Applications
Database queries are expensive — they involve disk reads, connection overhead, and query parsing. Redis is an in-memory data store that caches query results in RAM. The difference: a cached response returns in under 1 millisecond vs. 20–100 milliseconds from a database.
Installation
sudo apt install redis-server
# Start and enable
sudo systemctl enable redis-server
sudo systemctl start redis-server
# Test
redis-cli ping
# Returns: PONG
Securing Redis
Redis by default binds to localhost and requires no password — fine for development, not for VPS:
# Edit /etc/redis/redis.conf
sudo nano /etc/redis/redis.conf
# Bind only to localhost (never expose Redis to internet)
bind 127.0.0.1
# Set a strong password
requirepass your_very_strong_password_here
# Limit memory (prevents Redis consuming all RAM)
maxmemory 512mb
maxmemory-policy allkeys-lru
sudo systemctl restart redis-server
Application Integration (Node.js)
const redis = require('redis');
const client = redis.createClient({
url: 'redis://default:your_password@127.0.0.1:6379'
});
await client.connect();
// Cache-aside pattern
async function getUserProfile(userId) {
// Check cache
const cached = await client.get(`user:${userId}`);
if (cached) return JSON.parse(cached);
// Miss: fetch from database
const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
// Store in cache for 5 minutes
await client.setEx(`user:${userId}`, 300, JSON.stringify(user.rows[0]));
return user.rows[0];
}
// Invalidate on update
async function updateUser(userId, data) {
await db.query('UPDATE users SET ... WHERE id = $1', [userId, ...data]);
await client.del(`user:${userId}`); // Remove stale cache
}
Redis for Session Storage
Store Express sessions in Redis instead of memory/database for better performance and persistence across restarts:
const session = require('express-session');
const RedisStore = require('connect-redis');
app.use(session({
store: new RedisStore({ client }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { secure: true, httpOnly: true, maxAge: 86400000 }
}));
Monitoring Redis
redis-cli info memory # Memory usage
redis-cli info stats # Hit/miss rates
redis-cli monitor # Live commands (use briefly, verbose)
A good cache hit rate is > 90%. Below 80% means your cache keys or TTLs need tuning.