Redis in Practice

Use Redis data structures for caches, counters, leaderboards, rate limits and locks, and understand persistence, replication and clustering.

Intermediate · about 4 hours · difficulty 3/5

Learn first: Cache Strategies, Eviction and Invalidation

Redis is the most common building block in system design answers, and for good reason: an in-memory store with rich data structures and sub-millisecond latency.

Data structures and what they solve

  • Strings: cached JSON, counters with INCR, simple flags.
  • Hashes: objects with fields (a user session).
  • Lists: simple queues, recent items.
  • Sets: unique visitors, tags, "who liked this".
  • Sorted sets: leaderboards, top-K, priority queues, sliding window rate limits.
  • Streams: append-only logs with consumer groups for lightweight messaging.
  • HyperLogLog and bitmaps: approximate unique counts and daily active flags in tiny memory.
  • Geo: nearby drivers or restaurants by radius.

Operational basics

  • Persistence: RDB snapshots (compact, can lose recent writes) and AOF logs (more durable, bigger). Many caches run with persistence off.
  • Replication and Sentinel: replicas plus automatic failover.
  • Redis Cluster: data split into 16,384 hash slots across nodes; multi-key operations must stay in one slot (use hash tags).
  • Commands run on one main thread, so a single slow command (KEYS *, a huge set operation) blocks everyone.

Common patterns

Cache-aside caching, session storage, rate limiting with INCR and EXPIRE or Lua scripts, distributed locks with SET NX PX (understand their limits: a lock with a timeout is a lease, not a guarantee), pub/sub for fan-out, and idempotency key storage.

Pitfalls

  • Using KEYS in production instead of SCAN.
  • Huge "big keys" (a set with millions of members) that stall the server and break even sharding.
  • Relying on a Redis lock for correctness where a database constraint or fencing token is needed.

You are ready to move on when you can pick the right Redis structure for a cricket fantasy leaderboard, a per-user rate limiter and an online-users counter.

Key concepts

  • Strings, hashes, lists, sets
  • Sorted sets for leaderboards
  • Streams and pub/sub
  • HyperLogLog and bitmaps
  • RDB vs AOF persistence
  • Redis Cluster and hash slots
  • Distributed locks and their limits
  • Memcached as an alternative

Mini project

Build a fantasy cricket leaderboard service on Redis: sorted set for scores, a hash per user profile, HyperLogLog for unique daily players, and a sliding window rate limit on score updates. Load test it with 1 lakh simulated users.

Check yourself

Why can a Redis lock with an expiry still allow two workers to act on the same resource, and what is a fencing token?

Free resources