What is Redis?
Redis is an in-memory data structure store, used as database, cache, and message broker.
Basic Setup
javascriptimport 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
javascriptasync 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
javascriptasync 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
javascriptawait redis.setex('key', 3600, 'value'); // Expires in 1 hour
Active Invalidation
javascriptasync function invalidateUser(id) { await redis.del(`user:${id}`); }
Best Practices
- 1Set appropriate TTL: Prevent stale data
- 2Use proper data structures: Choose the right one for your use case
- 3Handle connection errors: Implement retry logic
- 4Monitor memory usage: Set maxmemory policy
- 5Use connection pooling: For high-throughput applications
Performance Tips
- 1Pipeline multiple commands: Reduce round-trips
- 2Use Lua scripts: Execute complex operations atomically
- 3Enable compression: For large values
- 4Use Redis Cluster: For horizontal scaling
Conclusion
Redis is a powerful caching solution that can significantly improve application performance.