Redis is the most versatile in-memory data store available — and on a Hong Kong VPS, a well-configured Redis instance serves as the performance backbone for multiple application subsystems simultaneously: object cache, session store, job queue, rate limiter, and pub/sub message broker. This guide covers production Redis configuration and the four most common application patterns.
Step 1: Install and Secure Redis
apt update && apt install -y redis-server
# Configure Redis for production
cat > /etc/redis/redis.conf << 'EOF'
# Bind to localhost only — never expose Redis publicly
bind 127.0.0.1 ::1
# Require authentication
requirepass GENERATE_STRONG_64_CHAR_PASSWORD
# Persistence — RDB snapshots + AOF for durability
save 900 1
save 300 10
save 60 10000
appendonly yes
appendfsync everysec
# Memory management
maxmemory 512mb
maxmemory-policy allkeys-lru
# Log level
loglevel notice
logfile /var/log/redis/redis-server.log
# Disable dangerous commands in production
rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command DEBUG ""
rename-command CONFIG "CONFIG_ADMIN_ONLY"
EOF
systemctl enable --now redis-server
# Verify
redis-cli -a YOUR_PASSWORD ping # Should return: PONG
Pattern 1: Object Cache (WordPress / Laravel)
# Test cache performance
redis-cli -a YOUR_PASSWORD << 'EOF'
SET cache:page:homepage "..." EX 3600
GET cache:page:homepage
TTL cache:page:homepage
EOF
PHP Redis Extension (for WordPress)
apt install php8.3-redis -y
systemctl restart php8.3-fpm
Laravel Cache Configuration
# In .env:
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=YOUR_PASSWORD
REDIS_PORT=6379
# In config/cache.php — Redis is now the default store
# Use:
Cache::put('key', 'value', 3600);
$value = Cache::get('key');
Cache::remember('expensive-query', 3600, fn() => DB::table('products')->get());
Node.js Caching with ioredis
npm install ioredis
const Redis = require('ioredis');
const redis = new Redis({ password: 'YOUR_PASSWORD' });
async function getProductWithCache(id) {
const cacheKey = `product:${id}`;
// Try cache first
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
// Cache miss — query database
const product = await db.query('SELECT * FROM products WHERE id = ?', [id]);
// Store in cache for 1 hour
await redis.setex(cacheKey, 3600, JSON.stringify(product));
return product;
}
Pattern 2: Session Storage
Storing sessions in Redis instead of files enables horizontal scaling (any server can read any session) and survives PHP-FPM restarts without logging users out.
# PHP session handler via Redis
# In /etc/php/8.3/fpm/php.ini:
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379?auth=YOUR_PASSWORD&prefix=sess_"
# Laravel session configuration
# In .env:
SESSION_DRIVER=redis
# Sessions now stored in Redis with automatic TTL management
# All app servers share the same session store → horizontal scaling ready
Session Key Patterns
<code">redis-cli -a YOUR_PASSWORD KEYS "sess_*" | wc -l # Count active sessions redis-cli -a YOUR_PASSWORD TTL "sess_abc123" # Check session expiry
Pattern 3: Job Queue Backend
Redis queues decouple time-consuming tasks (email sending, image processing, API calls) from web request handling, keeping response times fast.
Laravel Queues with Redis
# .env configuration
QUEUE_CONNECTION=redis
# Dispatch a job
ProcessVideoUpload::dispatch($videoId)->onQueue('media');
SendWelcomeEmail::dispatch($user)->onQueue('emails');
# Worker (run via Supervisor — see Laravel deployment guide)
php artisan queue:work redis --queue=media,emails --tries=3 --sleep=3
# Monitor queue depth
redis-cli -a YOUR_PASSWORD LLEN queues:media
redis-cli -a YOUR_PASSWORD LLEN queues:emails
Node.js Queue with BullMQ
npm install bullmq
const { Queue, Worker } = require('bullmq');
const connection = { host: '127.0.0.1', port: 6379, password: 'YOUR_PASSWORD' };
// Producer — add jobs
const emailQueue = new Queue('emails', { connection });
await emailQueue.add('welcome', { userId: 123, email: 'user@example.com' });
// Consumer — process jobs
const worker = new Worker('emails', async (job) => {
await sendEmail(job.data.email, 'Welcome!');
console.log(`Sent welcome email to ${job.data.email}`);
}, { connection });
worker.on('completed', job => console.log(`Job ${job.id} completed`));
worker.on('failed', (job, err) => console.error(`Job ${job.id} failed:`, err));
Pattern 4: Rate Limiting
Redis-based rate limiting is atomic and shared across all application servers — essential when running multiple Node.js processes or PHP-FPM workers.
Nginx + Redis Rate Limiting (via Lua)
<code"># For advanced rate limiting, use the redis-cell module or Lua scripts # Simpler: use Redis INCR with TTL in your application layer
Application-Level Rate Limiter (Node.js)
async function rateLimit(identifier, maxRequests, windowSeconds) {
const key = `ratelimit:${identifier}`;
const pipeline = redis.pipeline();
pipeline.incr(key);
pipeline.expire(key, windowSeconds);
const results = await pipeline.exec();
const count = results[0][1];
if (count > maxRequests) {
throw new Error(`Rate limit exceeded: ${count}/${maxRequests} requests`);
}
return { count, remaining: maxRequests - count };
}
// Usage in Express middleware
app.use('/api/', async (req, res, next) => {
try {
await rateLimit(req.ip, 100, 60); // 100 requests per minute per IP
next();
} catch (e) {
res.status(429).json({ error: 'Too many requests' });
}
});
Laravel Rate Limiting with Redis
<code">// In routes/api.php
Route::middleware(['throttle:api'])->group(function () {
Route::get('/products', [ProductController::class, 'index']);
});
// In App\Providers\RouteServiceProvider::boot()
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->ip());
});
// Laravel automatically uses Redis when CACHE_DRIVER=redis
Pattern 5: Pub/Sub Messaging
Redis pub/sub enables real-time event broadcasting between application components — useful for WebSocket notifications, cache invalidation across servers, and microservice event streaming.
<code">// Publisher (when an order is placed)
const { createClient } = require('redis');
const publisher = createClient({ password: 'YOUR_PASSWORD' });
await publisher.connect();
await publisher.publish('orders', JSON.stringify({
event: 'order_placed',
orderId: 12345,
userId: 678,
amount: 299.00
}));
// Subscriber (notification service)
const subscriber = createClient({ password: 'YOUR_PASSWORD' });
await subscriber.connect();
await subscriber.subscribe('orders', (message) => {
const event = JSON.parse(message);
if (event.event === 'order_placed') {
sendOrderConfirmationEmail(event.userId, event.orderId);
updateInventory(event.orderId);
notifyFulfillmentTeam(event.orderId);
}
});
Redis Monitoring
"# Real-time Redis stats
redis-cli -a YOUR_PASSWORD info stats | grep -E "total_commands|instantaneous_ops|keyspace_hits|keyspace_misses"
# Cache hit rate (aim for above 90%)
redis-cli -a YOUR_PASSWORD info stats | grep -E "keyspace_hits|keyspace_misses" | \
awk -F: 'BEGIN{h=0;m=0} /hits/{h=$2} /misses/{m=$2} END{printf "Hit rate: %.1f%%\n", h/(h+m)*100}'
# Memory usage
redis-cli -a YOUR_PASSWORD info memory | grep -E "used_memory_human|maxmemory_human"
# Slow query log (commands taking over 10ms)
redis-cli -a YOUR_PASSWORD slowlog get 10
# Monitor live commands (use sparingly in production)
redis-cli -a YOUR_PASSWORD monitor
Redis Sentinel for High Availability
For production environments where Redis downtime is unacceptable, Redis Sentinel provides automatic failover across multiple VPS instances:
<code"># On a second Hong Kong VPS — configure as Redis replica # In /etc/redis/redis.conf: replicaof MASTER_VPS_IP 6379 masterauth MASTER_PASSWORD requirepass REPLICA_PASSWORD # Redis Sentinel monitors master and promotes replica on failure apt install redis-sentinel -y cat > /etc/redis/sentinel.conf << 'EOF' sentinel monitor mymaster MASTER_VPS_IP 6379 2 sentinel auth-pass mymaster MASTER_PASSWORD sentinel down-after-milliseconds mymaster 5000 sentinel failover-timeout mymaster 60000 EOF
Conclusion
Redis on a Hong Kong VPS transforms your application’s performance across multiple dimensions simultaneously: caching eliminates redundant database queries, session storage enables horizontal scaling, job queues decouple slow operations from web requests, and rate limiting protects your APIs from abuse. A single well-configured Redis instance handles all four patterns with minimal memory overhead — 512 MB is sufficient for most applications handling tens of thousands of daily active users.
Optimise your stack: Browse Server.HK Hong Kong VPS plans — Redis runs alongside your application on any plan; allocate a dedicated VPS for Redis when your application grows to multiple app servers.