Card 04/ 07

ConceptDifficulty: Advanced1 min

Caching Strategies: Cache-Aside vs Write-Through

Whether a write invalidates the cache or updates it decides how often reads miss.

A caching strategy is the rule for how reads and writes keep a cache and a database in step. The two most common are cache-aside, where writes go to the database and remove the cached entry, and write-through, where writes update the database and the cache together. Spring's annotations can express either, so the choice should be made on purpose.

A fare changes twice a day and is read thousands of times an hour. Either strategy keeps it correct; they differ in what happens just after each change.

Cache-aside compared with write-through
StrategyOn a readOn a write
Cache-asideCheck the cache; on a miss, read the database and store the resultWrite the database, then remove or update the cache entry separately
Write-throughCheck the cache; misses are rare, because writes keep it currentWrite the cache and the database together, in the same call

@Cacheable (serve the stored result if there is one) on the read plus @CacheEvict (remove the entry) on the write is cache-aside: after each change, the next read misses and reloads from the database. @Cacheable plus @CachePut on the same key is close to write-through: the write stores the new value itself, so the next read is already a hit.

So cache-aside is the simpler default, and costs one slow read after each change. Write-through saves that read, and requires the write method to return exactly what the read would have produced.