API performance Level 2 This level · 16 of 20
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.

Could you say this in an interview?

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 patternlearn.microsoft.com
  2. Redis: Caching solutionsredis.io
  3. Redis: Client-side cachingredis.io
  4. Redis EXPIREredis.io
Previous
Next