Skip to content
Knowledge Hub

Cache & Redis Basic

Adding a cache is often the fastest way to take load off a database. In exchange, the system gains a second copy of the data.

Every hard question revolves around that copy: when it gets updated, who is responsible when it is wrong, and what happens when it disappears at peak load.

The articles and the questions they answer

Section titled “The articles and the questions they answer”
Question Article Key conclusion
Which pattern does the application use to read/write the cache? Cache-aside Write the DB first, delete the key second; a race can still leave a stale value in cache until the TTL expires.
What happens when a hot key expires? Cache stampede Many requests miss at once and all hit the DB; coalesce requests, use a token lock, or refresh early.
Did the key vanish because it expired or because memory ran out? Expiration and eviction Compare expired_keys with evicted_keys before touching TTLs.
How does Redis execute commands? Event loop and I/O threads Commands run sequentially on one thread; one slow command makes other clients’ PING wait.
Which type should store the data? Redis data structures Choose by operation: sorted set for rankings, HyperLogLog for unique counts, hash for objects.
How much is lost on restart or kill -9? Persistence: RDB and AOF By default only RDB is on: every write after the last snapshot is lost; AOF everysec loses about 1 s when the machine crashes.
Is batching several commands atomic? Pipelining, MULTI and Lua A pipeline only cuts round trips; check-then-write needs Lua or WATCH.
Does a Redis lock guarantee only one party runs? Distributed lock A lock with a TTL can still have two owners at times; the target resource needs a fencing token.
The cache is there, yet the DB is still overloaded? Cache penetration & avalanche Nonexistent ids pierce the cache; many keys expire at once; use a bloom filter and TTL jitter.

These four problems are independent: correct cache-aside can still collapse from a stampede, and avoiding stampedes can still leave a bad p99 because a reporting job hogs the command thread.

Current situation Read in this order
Just starting to use Redis as a cache Cache-aside → Event loop
p99 jumps suddenly while request volume is unchanged Event loop → check SLOWLOG and key sizes
The database gets slammed every time the cache expires Cache stampede
Hit rate drops, keys vanish early, or Redis runs out of RAM Expiration and eviction
Cached data drifts from the database Cache-aside, the race and invalidation sections
Overselling stock when decrementing in Redis Pipelining, MULTI and Lua
A cron job runs twice across pods despite a lock Distributed lock
DB load spikes periodically or bots request garbage ids Cache penetration & avalanche
Sessions are lost after a Redis restart Persistence: RDB and AOF