Redis Architecture and Patterns

Redis/Valkey data structures, persistence, replication and cluster mode, and patterns for caching, sessions, rate limiting, distributed locks, leaderboards and streams.

[!VERSION] Redis moved to source-available licences in 2024, prompting the Linux Foundation fork Valkey; Redis 8 added an AGPLv3 option in 2025. AWS, Google Cloud and others offer Valkey-based managed services; Azure offers Azure Managed Redis.

Data structures and uses

Structure Use
String Cache values, counters (INCR), flags
Hash Objects (session data), token buckets
List Simple queues (prefer Streams for reliability)
Set Unique members, tags
Sorted set Leaderboards, time-ordered indexes, sliding-window rate limits
Stream Append-only log with consumer groups
Geo Nearby search (GEOSEARCH)
Bitmap/HyperLogLog Compact flags, approximate unique counts

Deployment modes

flowchart LR
  subgraph Cluster mode [Redis Cluster: 16384 hash slots]
    M1[Primary 1<br/>slots 0-5460] --> R1[Replica]
    M2[Primary 2<br/>slots 5461-10922] --> R2[Replica]
    M3[Primary 3<br/>slots 10923-16383] --> R3[Replica]
  end
  APP[App with cluster-aware client] --> M1 & M2 & M3
  • Replication is asynchronous: a failover can lose acknowledged writes. Do not use Redis as the only copy of critical data.
  • Persistence: RDB snapshots and/or AOF; still not a substitute for a database for financial records.
  • Cluster: keys hashed into slots; multi-key operations require keys in the same slot (use hash tags {user:42}:cart).

Patterns in Java (Spring Data Redis)

// Cache-aside with Spring Cache
@Cacheable(cacheNames = "product", key = "#id")
public ProductView product(String id) { return repository.load(id); }

@CacheEvict(cacheNames = "product", key = "#cmd.id()")
public void update(UpdateProduct cmd) { repository.update(cmd); }
// Leaderboard
redis.opsForZSet().incrementScore("leaderboard:2026-11", playerId, points);
Set<String> top10 = redis.opsForZSet().reverseRange("leaderboard:2026-11", 0, 9);

Distributed locks: be careful

A simple lock is SET lock:key token NX PX 30000 and release with a compare-and-delete script. Because replication is asynchronous and processes can pause (GC), a lock holder may lose the lock without knowing. For correctness-critical mutual exclusion, use fencing tokens checked by the resource, or a consensus store (etcd, ZooKeeper) or database row locks. (See Martin Kleppmann's critique of Redlock.)

Interview questions and answers

Can Redis be your primary database?

For ephemeral or reconstructible data (sessions, caches, counters), yes. For durable business records, use a database with stronger durability guarantees; Redis persistence and async replication can lose recent writes.

How do you handle a hot key?

Replicate the value under several keys and pick one randomly, add a local in-process cache layer, or restructure (split counters). In cluster mode, a hot key sits on one shard regardless of cluster size.