Redis Caching: Speed Up Your Applications
Redis is an in-memory data structure store used as a database, cache, and message broker. It supports strings, hashes, lists, sets, sorted sets, and more.
## Why Redis?
- Extremely fast (in-memory)
- Rich data types
- Persistence options
- Pub/Sub messaging
- Atomic operations
## Basic Commands
```bash
# Strings
SET user:1 "John"
GET user:1
# Expiration
SET session:abc "data" EX 3600
# Hashes
HSET user:1 name "John" email "john@example.com"
HGET user:1 name
# Lists
LPUSH queue "task1"
RPOP queue
# Sets
SADD tags "redis" "cache"
SMEMBERS tags
```
## Caching Patterns
### Cache-Aside
```javascript
async function getUser(id) {
let user = await redis.get(`user:${id}`);
if (!user) {
user = await db.getUser(id);
await redis.set(`user:${id}`, JSON.stringify(user), 'EX', 3600);
}
return JSON.parse(user);
}
```
### Write-Through
```javascript
async function updateUser(user) {
await db.updateUser(user);
await redis.set(`user:${user.id}`, JSON.stringify(user), 'EX', 3600);
}
```
## Best Practices
1. Set expiration on all cached data
2. Use consistent key naming
3. Handle cache misses gracefully
4. Monitor memory usage
5. Use pipelining for bulk operations
## Conclusion
Redis dramatically improves application performance. Use it for caching, sessions, leaderboards, and real-time features.
