Overview
Redis is an in-memory data store used for caching, sessions, real-time features, and message queues. Learn common patterns for optimal performance.
Key Patterns
- Cache Aside: Check cache, fallback to database
- Write-Through: Update cache and database together
- Cache Invalidation: Strategies for keeping cache fresh
- Distributed Locking: Prevent race conditions
- Rate Limiting: Throttle API requests
Cache Aside Pattern
import redis from 'redis'
const client = redis.createClient()
async function getUser(userId: number) {
// Check cache
const cached = await client.get(`user:${userId}`)
if (cached) return JSON.parse(cached)
// Fallback to database
const user = await db.users.findById(userId)
// Store in cache (expire after 1 hour)
await client.setEx(
`user:${userId}`,
3600,
JSON.stringify(user)
)
return user
}
Session Storage
// Store session data
await client.setEx(
`session:${sessionId}`,
86400, // 24 hours
JSON.stringify({ userId: 123, role: 'admin' })
)
// Retrieve session
const session = JSON.parse(await client.get(`session:${sessionId}`))
Rate Limiting
async function isRateLimited(userId: string): Promise<boolean> {
const key = `ratelimit:${userId}`
const count = await client.incr(key)
if (count === 1) {
await client.expire(key, 60) // 1 minute window
}
return count > 100 // 100 requests per minute
}
Pub/Sub Messaging
// Publisher
await client.publish('notifications', JSON.stringify({
userId: 123,
message: 'New message from Alice'
}))
// Subscriber
const subscriber = client.duplicate()
await subscriber.subscribe('notifications', (message) => {
console.log('Received:', JSON.parse(message))
})
Redis can handle millions of operations per second with sub-millisecond latency.