Redis
Backend
Database
Performance
Architecture
Ask anything about this article
Hi! I've read this article.
What would you like to know?
@farhan
Redis is the Swiss Army knife of backend engineering. It's an in-memory data store that can serve as a cache, message broker, session store, rate limiter, and real-time leaderboard — all with sub-millisecond latency.
Redis stores everything in RAM. While a typical database read takes 1-10ms (disk I/O), a Redis read takes 0.1ms (memory access). That's 10-100x faster.
Redis isn't just a key-value store. It supports rich data structures:
bashSET user:123:name "John Doe"
GET user:123:name # "John Doe"
# With expiration (TTL)
SET session:abc123 "user_data" EX 3600 # Expires in 1 hour
# Atomic counter
INCR page:home:views # 1, 2, 3, ...
bashHSET user:123 name "John" email "john@example.com" age 28
HGET user:123 name # "John"
HGETALL user:123 # Returns all fields
bashLPUSH queue:emails "email1" "email2" # Push to left
RPOP queue:emails # Pop from right (FIFO queue)
LRANGE queue:emails 0 -1 # Get all items
bashSADD online:users "user:123" "user:456"
SISMEMBER online:users "user:123" # true
SCARD online:users # 2 (count)
bashZADD leaderboard 1500 "player:1" 2300 "player:2" 1800 "player:3"
ZREVRANGE leaderboard 0 9 # Top 10 players
ZRANK leaderboard "player:1" # Player's rank
typescriptasync function getUser(userId: string) {
// Check cache first
const cached = await redis.get(`user:${userId}`);
if (cached) return JSON.parse(cached);
// Cache miss: query database
const user = await db.users.findOne({ id: userId });
// Store in cache with 1 hour TTL
await redis.set(`user:${userId}`, JSON.stringify(user), 'EX', 3600);
return user;
}
1. TTL-based: Set expiration, let it auto-expire
2. Write-through: Update cache on every write
3. Write-behind: Batch cache updates
4. Cache-aside: Application manages cache reads/writes
typescriptasync function rateLimit(ip: string, limit: number, windowSec: number) {
const key = `rate:${ip}`;
const current = await redis.incr(key);
if (current === 1) {
await redis.expire(key, windowSec);
}
if (current > limit) {
throw new Error('Rate limit exceeded');
}
}
// Usage: 100 requests per 15 minutes
await rateLimit(req.ip, 100, 900);
typescript// Store session
await redis.set(`session:${sessionId}`, JSON.stringify({
userId: user.id,
role: user.role,
loginAt: Date.now()
}), 'EX', 86400); // 24 hours
// Retrieve session
const session = JSON.parse(
await redis.get(`session:${sessionId}`)
);
typescript// Publisher
redis.publish('notifications', JSON.stringify({
userId: '123',
message: 'New comment on your post'
}));
// Subscriber
redis.subscribe('notifications', (message) => {
const notification = JSON.parse(message);
sendWebSocket(notification.userId, notification.message);
});
Redis is one of those tools that, once you learn it, you'll find uses for it everywhere. Every senior backend engineer should have Redis in their toolkit.