Medium java backend

Redis cache-aside for read-often, change-rarely data

The 30 second answer

For data that is read often and changes rarely, I use cache-aside with Redis: read from the cache, and on a miss load from the database and store it with a time to live. On updates I write to the database and then delete the cache entry. The risks are stale data, a stampede when a hot key expires, and extra moving parts.

Cache-aside works like this: read from the cache; on a miss, read the database and write the value to the cache with a TTL; on update, write the database and delete the key. The TTL limits how stale data can get.

String v = redis.get(key);
if (v == null) { v = db.load(id); redis.setex(key, 300, v); }
Sources (4)
  1. Microsoft Azure Architecture: Cache-Aside pattern
  2. Redis: Caching solutions
  3. Redis: Client-side caching
  4. Redis EXPIRE