Top 5 Redis Use Cases
Summary of Top 5 Redis Use Cases from ByteByteGo · Published 2023-02-16 · Views: 266,052
This note was generated automatically from the video transcript.
TL;DR
Redis’s in‑memory data structures make it ideal for high‑speed caching, session storage, distributed locks, rate limiting, and gaming leaderboards. Deploying Redis as a distributed cache or lock requires careful TTL, sharding, and replication strategies to avoid thundering‑herd and availability pitfalls.
Key Insights
- Cache: Redis stores hot objects in memory, reducing DB load; sharding spreads load across a cluster.
- Session Store: Stateless web servers read/write session data via a session‑ID cookie; replication provides fast failover, while persistence (RDB/AOF) is too slow for most session workloads.
- Distributed Lock:
SETNX/SET … NX EXgive atomic lock acquisition with a timeout; client libraries are recommended for fault‑tolerant implementations. - Rate Limiter: Simple counters (
INCR+EXPIRE) enforce per‑IP/user limits; more advanced algorithms (leaky bucket) can also be built on top of Redis. - Leaderboard: Sorted Sets (
ZADD,ZRANGE) deliver O(log N) insert and O(log N + M) range queries, perfect for real‑time game rankings. - Operational Concerns: Proper TTL, handling thundering‑herd on cache miss, and using replication for high availability are critical for production reliability.
Detailed Breakdown
1. Caching Objects
- Goal: Serve frequently requested data from memory to cut latency and DB load.
- Pattern:
- Web server checks Redis for key.
- If hit → return cached value.
- If miss → load from DB, write to Redis with a TTL, then return.
- Scaling: A Redis cluster shards keys across multiple nodes, balancing load.
- Operational Tips:
- Choose an appropriate TTL to keep data fresh and avoid stale reads.
- Guard against a thundering herd on cold start by using “lazy” or “early‑expiration” strategies (e.g., staggered TTLs or background refresh).
flowchart LR
web["Web Server"] -->|GET key| redis["Redis Cluster"]
redis -->|HIT| web
redis -->|MISS| db["Database"]
db -->|value| redis
redis -->|store+TTL| redis
redis -->|value| web
2. Session Store
- Workflow:
- User logs in → server creates session object, stores it in Redis with a unique session ID, returns cookie.
- Subsequent requests include the cookie; server fetches session data by ID from Redis.
- Durability:
- Redis is in‑memory; a restart clears data.
- Persistence (RDB snapshots, AOF) is too slow for session recovery.
- Production setups use replication: a primary and one or more replicas; on primary failure, a replica is promoted.
- Considerations: Session TTL must be short enough to free memory but long enough for user experience.
sequenceDiagram
participant Client
participant Web as "Web Server"
participant Redis
Client->>Web: POST /login (credentials)
Web->>Redis: SET sessionID data EX ttl
Redis-->>Web: OK
Web-->>Client: Set-Cookie: sessionID
Client->>Web: GET /resource (Cookie)
Web->>Redis: GET sessionID
Redis-->>Web: session data
Web-->>Client: response
3. Distributed Lock
- Primitive:
SET key value NX EX seconds(or olderSETNX+EXPIRE). - Acquisition:
- Client generates a unique token (e.g., UUID).
- Executes
SET lock "token" NX EX 3. - If return = OK → lock held; else retry after back‑off.
- Release: Delete only if token matches (to avoid releasing another client’s lock).
- Limitations: Simple
SETNXlacks safety against client crashes or clock drift; production libraries (e.g., Redlock) add quorum checks and automatic renewal.
flowchart LR
client1["Client 1"] -->|SETNX lock "token" EX 3| redis["Redis"]
redis -->|1 (OK)| client1
client1 -->|work| client1
client1 -->|DEL lock| redis
client2["Client 2"] -->|SETNX lock "token2" EX 3| redis
redis -->|0 (FAIL)| client2
4. Rate Limiter
- Simple Counter:
- Key =
rate:<IP>orrate:<userID>. INCR key→ count.EXPIRE key 60(seconds) to reset each minute.- If count ≤ limit → allow; else reject.
- Key =
- Advanced: Leaky bucket or token bucket can be modeled with a sorted set storing timestamps, then trimming old entries.
flowchart LR
api["API Gateway"] -->|INCR rate:key| redis["Redis"]
redis -->|count| api
api -->|allow/reject| client["Client"]
5. Gaming Leaderboard
- Data Structure: Sorted Set (
ZADD playerID score). - Operations:
ZADD leaderboard playerID score– O(log N).ZRANGE leaderboard 0 9 WITHSCORES– top‑10 players, O(log N + M).ZREVRANK leaderboard playerID– player’s rank, O(log N).
- Use Cases: Global high scores, per‑region leaderboards, time‑windowed rankings.
flowchart LR
game["Game Server"] -->|ZADD leaderboard player score| redis["Redis"]
redis -->|ZREVRANK player| game
game -->|display rank| client["Player"]
Trade-offs and Gotchas
- Memory Cost: All data lives in RAM; large datasets require scaling out or eviction policies.
- Persistence Latency: RDB snapshots and AOF can cause pause‑times; not suitable for low‑latency session data.
- TTL Misconfiguration: Too short → frequent cache misses; too long → stale data and memory pressure.
- Thundering Herd: Simultaneous cache miss spikes can overload the DB; mitigate with request coalescing or early refresh.
- Lock Safety: Simple
SETNXlacks fault tolerance; use vetted libraries (e.g., Redlock) for critical sections. - Cluster Sharding: Requires client‑side key hashing; cross‑slot operations (e.g., multi‑key transactions) are limited.
- Replication Lag: In asynchronous replication, a replica may be slightly behind; acceptable for sessions but not for strict consistency needs.
Takeaways
- Use Redis as a cache for hot data, but always pair it with a sensible TTL and herd‑mitigation strategy.
- For session storage, rely on replication for HA; persistence is generally unnecessary.
- Implement distributed locks with the atomic
SET … NX EXpattern and a battle‑tested client library. - Build rate limiters with simple counters; upgrade to token/leaky bucket only when needed.
- Leverage Sorted Sets for real‑time leaderboards, benefiting from logarithmic insert and range query performance.
Glossary
- TTL (Time‑to‑Live): Expiration time after which a key is automatically deleted.
- Sharding: Distributing data across multiple nodes based on a hash of the key.
- Thundering Herd: A surge of requests hitting the backing store when a cached entry expires.
- AOF (Append‑Only File): Redis persistence mode that logs every write operation.
- RDB (Redis Database): Snapshot‑based persistence that writes the entire dataset to disk at intervals.
- Redlock: A distributed lock algorithm that uses multiple Redis instances to achieve higher safety guarantees.
- Sorted Set: Redis data type that stores unique members with a floating‑point score, kept in order by score.
Leave a comment