DEV Community

Cover image for Redis
Gouranga Das Samrat
Gouranga Das Samrat

Posted on

Redis

One-liner: An in-memory data structure store used as a cache, message broker, session store, rate limiter, and much more β€” blazing fast because everything lives in RAM.


πŸ“Œ Why Redis?

  • Speed: In-memory β†’ sub-millisecond latency (< 1ms)
  • Rich data types: Not just key-value β€” lists, sets, hashes, sorted sets, streams
  • Persistence: Optional β€” can snapshot to disk (RDB) or log every write (AOF)
  • Pub/Sub: Built-in message broker
  • Expiry: TTL on any key
  • Atomic operations: All commands are atomic

πŸ—ƒοΈ Redis Data Types

String β€” The Basic Type

SET user:42:name "Rahul"
GET user:42:name      β†’ "Rahul"
INCR page:views       β†’ 1, 2, 3 (atomic counter)
SETEX session:abc 3600 "userId=42"  (with TTL)
Enter fullscreen mode Exit fullscreen mode

Hash β€” Object/Map

HSET user:42 name "Rahul" age 25 city "Delhi"
HGET user:42 name      β†’ "Rahul"
HGETALL user:42        β†’ { name: Rahul, age: 25, city: Delhi }
Enter fullscreen mode Exit fullscreen mode

Best for: User profiles, product data, config

List β€” Ordered, Allows Duplicates

LPUSH notifications:42 "You got a like!"  (push to left)
RPUSH notifications:42 "New follower!"    (push to right)
LRANGE notifications:42 0 9               (get first 10)
LPOP notifications:42                     (remove from left)
Enter fullscreen mode Exit fullscreen mode

Best for: Activity feeds, queues (FIFO/LIFO), recent items

Set β€” Unordered, Unique Values

SADD followers:42 101 102 103
SMEMBERS followers:42    β†’ {101, 102, 103}
SISMEMBER followers:42 102 β†’ 1 (yes)
SCARD followers:42          β†’ 3 (count)
SINTER followers:42 followers:99  β†’ mutual followers (intersection)
Enter fullscreen mode Exit fullscreen mode

Best for: Tags, unique visitors, friend lists

Sorted Set (ZSet) β€” Ranked/Scored Set

ZADD leaderboard 9500 "player_alice"
ZADD leaderboard 8700 "player_bob"
ZADD leaderboard 9900 "player_charlie"
ZRANGE leaderboard 0 2 WITHSCORES REV  β†’ charlie(9900), alice(9500), bob(8700)
ZRANK leaderboard "player_alice"         β†’ 1 (0-indexed rank)
Enter fullscreen mode Exit fullscreen mode

Best for: Leaderboards, rate limiting, priority queues, trending topics

Stream β€” Append-only Log

XADD events * userId 42 action "purchase" amount 999
XREAD COUNT 10 STREAMS events 0
Enter fullscreen mode Exit fullscreen mode

Best for: Event sourcing, activity logs, message queues (like Kafka-lite)


πŸ—οΈ Common Redis Use Cases

1. Session Store

// Login
redis.setex(`session:${token}`, 3600, JSON.stringify({ userId: 42 }));

// Per-request auth
const session = redis.get(`session:${token}`);
Enter fullscreen mode Exit fullscreen mode

2. Cache (Cache-Aside)

const cached = await redis.get(`user:${userId}`);
if (!cached) {
  const user = await db.findUser(userId);
  await redis.setex(`user:${userId}`, 300, JSON.stringify(user));
}
Enter fullscreen mode Exit fullscreen mode

3. Rate Limiting (Sliding Window)

const key = `rate:${userId}:${Math.floor(Date.now() / 60000)}`;
const count = await redis.incr(key);
await redis.expire(key, 60);
if (count > 100) throw new Error("Rate limit exceeded");
Enter fullscreen mode Exit fullscreen mode

4. Pub/Sub Messaging

// Publisher
redis.publish(
  "notifications",
  JSON.stringify({ userId: 42, msg: "New order!" }),
);

// Subscriber
redis.subscribe("notifications", (message) => {
  const { userId, msg } = JSON.parse(message);
  sendPushNotification(userId, msg);
});
Enter fullscreen mode Exit fullscreen mode

5. Distributed Lock

const lock = await redis.set("lock:resource", "1", "NX", "EX", 10);
if (!lock) throw new Error("Resource locked by another process");
// ... do work ...
redis.del("lock:resource");
Enter fullscreen mode Exit fullscreen mode

NX = set only if Not eXists | EX 10 = expire in 10 seconds

6. Leaderboard

// Add/update score
redis.zadd("game:leaderboard", score, userId);

// Top 10
redis.zrange("game:leaderboard", 0, 9, "REV", "WITHSCORES");

// User's rank
redis.zrevrank("game:leaderboard", userId);
Enter fullscreen mode Exit fullscreen mode

πŸ”„ Redis Persistence

Mode How Data Safety Performance
No persistence Pure in-memory Data lost on restart Fastest
RDB (Snapshot) Periodic snapshot to disk Up to minutes of data loss Fast
AOF (Append Only File) Log every write to disk Nearly no data loss Slower
RDB + AOF Both Best safety Moderate
# redis.conf
save 900 1      # Save if 1 key changed in 900 seconds
save 300 10     # Save if 10 keys changed in 300 seconds
appendonly yes  # Enable AOF
Enter fullscreen mode Exit fullscreen mode

πŸ—οΈ Redis Cluster vs Sentinel

Redis Sentinel (High Availability)

[Sentinel 1] [Sentinel 2] [Sentinel 3]  ← monitors
      β”‚
[Primary] ──replicates──► [Replica 1]
                         [Replica 2]
Enter fullscreen mode Exit fullscreen mode
  • Automatic failover β€” promotes replica to primary
  • No sharding β€” all data on primary
  • Use for: HA without massive scale

Redis Cluster (Scale + HA)

[Node 1: slots 0-5460]     [Replica 1a] [Replica 1b]
[Node 2: slots 5461-10922] [Replica 2a] [Replica 2b]
[Node 3: slots 10923-16383][Replica 3a] [Replica 3b]
Enter fullscreen mode Exit fullscreen mode
  • 16,384 hash slots distributed across nodes
  • Built-in sharding + HA
  • Use for: Data larger than single machine's RAM

🎨 Diagram

The diagram shows:

  • Redis data types illustrated with examples
  • Cache-aside pattern
  • Redis Sentinel failover
  • Redis Cluster slot distribution

πŸ”‘ Key Takeaways

  • Redis is not just a cache β€” it's a data structure server
  • Sorted Sets for leaderboards/rankings are a killer feature
  • Always set TTLs β€” unbounded memory growth will kill your Redis
  • Use Sentinel for HA, Cluster for scale beyond single-machine RAM

Top comments (0)