Why Redis?
Redis is the world's most popular in-memory data store. It handles caching, session storage, real-time leaderboards, pub/sub messaging, and rate limiting — all with sub-millisecond latency.
Redis Cloud free tier: 30 MB storage, 30 connections. Perfect for caching, sessions, and small real-time apps.
Getting Started
Option 1: Redis Cloud (Free)
Sign up at redis.com — free forever tier, no credit card.
Option 2: Local (Docker)
docker run -d --name redis -p 6379:6379 redis:latest
Python Examples
Basic Caching
import redis
import json
import time
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
def get_user(user_id):
# Check cache first
cached = r.get(f"user:{user_id}")
if cached:
print("Cache HIT")
return json.loads(cached)
# Simulate database query
print("Cache MISS — fetching from DB")
user = {"id": user_id, "name": "Alice", "email": "alice@example.com"}
# Cache for 1 hour
r.setex(f"user:{user_id}", 3600, json.dumps(user))
return user
print(get_user(1)) # Cache MISS
print(get_user(1)) # Cache HIT — instant!
Real-Time Leaderboard
# Add scores
r.zadd("leaderboard", {"alice": 1500, "bob": 2200, "charlie": 1800, "diana": 2500})
# Top 3 players
top3 = r.zrevrange("leaderboard", 0, 2, withscores=True)
for rank, (player, score) in enumerate(top3, 1):
print(f"#{rank} {player}: {int(score)} pts")
# Player rank
rank = r.zrevrank("leaderboard", "charlie")
print(f"Charlie is rank #{rank + 1}")
Rate Limiter
def is_rate_limited(ip, max_requests=10, window=60):
key = f"rate:{ip}"
current = r.get(key)
if current and int(current) >= max_requests:
return True
pipe = r.pipeline()
pipe.incr(key)
pipe.expire(key, window)
pipe.execute()
return False
for i in range(12):
limited = is_rate_limited("192.168.1.1")
print(f"Request {i+1}: {'BLOCKED' if limited else 'OK'}")
Node.js Examples
Session Store (Express)
const express = require("express");
const session = require("express-session");
const RedisStore = require("connect-redis").default;
const { createClient } = require("redis");
const redisClient = createClient({ url: "redis://localhost:6379" });
await redisClient.connect();
const app = express();
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: "your-secret",
resave: false,
saveUninitialized: false,
cookie: { maxAge: 86400000 }
}));
Pub/Sub (Real-Time Notifications)
const { createClient } = require("redis");
// Publisher
const pub = createClient();
await pub.connect();
await pub.publish("notifications", JSON.stringify({
type: "order_shipped",
userId: "user123",
orderId: "order456"
}));
// Subscriber
const sub = createClient();
await sub.connect();
await sub.subscribe("notifications", (message) => {
const data = JSON.parse(message);
console.log(`Notification: ${data.type} for ${data.userId}`);
});
Redis Data Structures Cheat Sheet
| Structure | Use Case | Commands |
|---|---|---|
| String | Caching, counters | GET, SET, INCR |
| Hash | User profiles, settings | HGET, HSET, HGETALL |
| List | Queues, feeds | LPUSH, RPOP, LRANGE |
| Set | Tags, unique items | SADD, SMEMBERS, SINTER |
| Sorted Set | Leaderboards, rankings | ZADD, ZRANGE, ZRANK |
| Stream | Event logs, messaging | XADD, XREAD, XRANGE |
Need to scrape data and cache results with Redis? I build production-ready scrapers with built-in caching. Check out my Apify actors or email spinov001@gmail.com for custom solutions.
What's your favorite Redis use case? Share below!
Top comments (0)