Skip to content
All essays
ArchitectureJanuary 21, 202511 min

Redis Caching: Complete Guide to Performance Optimization

Master Redis caching strategies. Learn data structures, caching patterns, and performance optimization techniques.

Ü
Ümit Uz
Mobile & Full Stack Developer

What is Redis?

Redis is an in-memory data structure store, used as database, cache, and message broker.

Basic Setup

javascript
import Redis from 'ioredis'; const redis = new Redis({ host: 'localhost', port: 6379 });

Data Structures

Strings

javascript
// Set await redis.set('user:1', JSON.stringify({ name: 'John' })); // Get const user = await redis.get('user:1'); // Set with expiration await redis.setex('session:123', 3600, 'active');

Hashes

javascript
// Set field await redis.hset('user:1', 'name', 'John'); await redis.hset('user:1', 'email', 'john@example.com'); // Get all fields const user = await redis.hgetall('user:1'); // Get specific field const name = await redis.hget('user:1', 'name');

Lists

javascript
// Push await redis.lpush('tasks', 'task1'); await redis.rpush('tasks', 'task2'); // Pop const task = await redis.lpop('tasks'); // Get range const tasks = await redis.lrange('tasks', 0, -1);

Sets

javascript
// Add members await redis.sadd('tags', 'javascript', 'nodejs', 'redis'); // Get all members const tags = await redis.smembers('tags'); // Check membership const exists = await redis.sismember('tags', 'javascript');

Caching Strategies

Cache-Aside

javascript
async function getUser(id) { // Check cache const cached = await redis.get(`user:${id}`); if (cached) return JSON.parse(cached); // Fetch from database const user = await db.findUser(id); // Store in cache await redis.setex(`user:${id}`, 3600, JSON.stringify(user)); return user; }

Write-Through

javascript
async function updateUser(id, data) { // Update database const user = await db.updateUser(id, data); // Update cache await redis.setex(`user:${id}`, 3600, JSON.stringify(user)); return user; }

Cache Invalidation

Time-Based Expiration

javascript
await redis.setex('key', 3600, 'value'); // Expires in 1 hour

Active Invalidation

javascript
async function invalidateUser(id) { await redis.del(`user:${id}`); }

Best Practices

  1. 1Set appropriate TTL: Prevent stale data
  2. 2Use proper data structures: Choose the right one for your use case
  3. 3Handle connection errors: Implement retry logic
  4. 4Monitor memory usage: Set maxmemory policy
  5. 5Use connection pooling: For high-throughput applications

Performance Tips

  1. 1Pipeline multiple commands: Reduce round-trips
  2. 2Use Lua scripts: Execute complex operations atomically
  3. 3Enable compression: For large values
  4. 4Use Redis Cluster: For horizontal scaling

Conclusion

Redis is a powerful caching solution that can significantly improve application performance.

Next essay
PostgreSQL & Prisma: Modern Database Development