Topic 10.8
Redis
In one line
The de-facto cache/state store: in-memory, single-threaded, rich data types, lua/RDB/AOF, and clustering.
Think of it like this
A very fast personal assistant who never forgets anything they were told in the last few minutes (in-memory), and who's brilliant at quick lookups, counters, and short to-do lists, but isn't meant to be your permanent filing cabinet.
Key ideas
- 01
Single-threaded event loop → atomic commands per key without locks; throughput ~100k ops/s.
- 02
Data types that matter: STRING, HASH, LIST, SET, ZSET (sorted — leaderboards), STREAM (log/queue), BITMAP.
- 03
Durability options: RDB snapshots (fast, may lose recent) vs AOF (append log, replays) — Redis is a cache first, durable store second.
- 04
Atomicity: MULTI/EXEC, Lua scripts, or single commands (INCR, SETNX) — the arsenal for rate limits and locks.
- 05
Redis Cluster = consistent-hash slot sharding + replicas; Redis Sentinel = failover manager.
- 06
Interview: 'Redis with TTLs and the right type (ZSET for feeds, INCR for counters, SETNX for locks)' — specific beats generic.
Java / Spring map
- →
Spring Data Redis: RedisTemplate<String,Object>, @Cacheable with RedisCacheManager, Bucket4j for limits.
Code & diagrams
The five Redis usage patterns that appear in every HLD.
// 1) counter (rate limit / like counts)
redis.opsForValue().increment("like:post:" + postId);
// 2) sorted set → news feed / leaderboard
redis.opsForZSet().add("feed:user:" + userId, postJson, timestamp);
// 3) SETNX → distributed lock
Boolean locked = redis.opsForValue().setIfAbsent("lock:order:" + orderId, "1", Duration.ofSeconds(10));
// 4) stream → light queue (or use Kafka — see messaging topics)
redis.opsForStream().add("order-events", Map.of("orderId", orderId));
// 5) TTL session / cache
redis.opsForValue().set("session:" + token, userId, Duration.ofHours(8));Explain without notes
Why is the single-threaded model the reason Redis commands are atomic — and what's the caveat about long scripts?
Practice
Design: like-counter (string), top-10 feed (zset), daily limit (increment+expire) — all in Redis, with eviction policy.
Trade-offs
- ↔
Memory is expensive; everything Redis holds is RAM you pay for. Size the working set, not the dataset.
Run it in production
You've designed it. Now build, operate, and break the same idea hands-on in the DevOps courses:
Stateful · Redis & caching patterns
Cache-aside with a stampede lock, TTLs, rate limiting, and sessions in Redis.
Stateful · Redis memory, eviction & persistence
maxmemory policies, big and hot keys, RDB/AOF, and slow commands.
Stateful · Redis Sentinel, Cluster & locks
Hash slots, failover, and why distributed locks need fencing.
Completion checklist
I can pick a Redis structure per pattern and configure eviction + durability for the answer.