Redis: Cache and Data Structures
Redis is an in-memory data-structure server used for caching, counters, coordination hints and streams; its role must be explicit in the source-of-truth model.
Redis: Cache and Data Structures
Redis is an in-memory data-structure server used for caching, counters, coordination hints and streams; its role must be explicit in the source-of-truth model. Strings support values and counters; hashes represent fields; sets and sorted sets support membership and ranking; streams support consumer-group processing. TTL controls expiry; eviction reclaims memory. Replication and Sentinel/Cluster solve different availability and sharding needs. Lua makes selected Redis operations atomic, not transactions across Redis and a relational database.
Mechanism and worked example
A rate limiter can atomically refill and consume tokens in a script. Cache-aside product lookup may tolerate short staleness. Inventory reservation should remain in a transactional authoritative store unless Redis is deliberately engineered to meet durability and recovery requirements.
| Feature | Useful for | Caution |
|---|---|---|
| TTL/eviction | Bound cache lifetime and memory | Expiry and eviction differ |
| Replication | Read copies and failover | Recent writes may be absent |
| Cluster | Horizontal key distribution | Hot keys and cross-slot operations |
| Lua | Atomic local transition | No cross-database transaction |
| Streams | Consumer groups | Retention and pending recovery |
Failure modes and operations
Eviction can remove keys before TTL. Async replication may lose recent writes during failover. Cluster resharding changes key placement; multi-key operations may require same-slot keys. Hot keys overload one shard. Cache outages can stampede the database.
Trade-offs and design boundary
Redis offers low-latency primitives but memory cost, persistence, replication lag and topology matter. Memcached may be simpler for pure cache workloads. Durable business invariants should remain in a database unless Redis is explicitly the authority.
Interview transfer exercise
Why is a Redis lock with TTL insufficient if an expired owner can resume? The protected destination needs a monotonically increasing fencing token and must reject stale owners.
Read the diagram
Application checks Redis primitive → Cache miss reads authoritative database → Source write commits then cache invalidates → Failover and eviction are expected events
Why is a Redis lock with TTL insufficient if an expired owner can resume? The protected destination needs a monotonically increasing fencing token and must reject stale owners.
Your design draft
Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.
Self-review checklist
Self-guided practice. Automated AI feedback and code execution are not connected.