Video in progress

Explain the cache-aside pattern with code.

The application reads from the cache first; on a miss it loads from the DB, writes to the cache with a TTL and returns the value. On a write it updates the DB and removes the cache entry. All the cache handling lives in application code.

📖 Answer

This is the most common pattern, and @Cacheable does essentially this.

public ProductDto get(long id) {
    String key = "product:" + id;
    String cached = redis.opsForValue().get(key);
    if (cached != null) {
        return json.read(cached, ProductDto.class);
    }
    ProductDto dto = repo.findDto(id);                       // miss
    redis.opsForValue().set(key, json.write(dto), Duration.ofMinutes(10));
    return dto;
}

@Transactional
public void rename(long id, String name) {
    repo.rename(id, name);
    // delete after the commit, see below
    afterCommit(() -> redis.delete("product:" + id));
}

Why it's good: the application keeps working if the cache goes down (just slower), and the cache holds only what was actually requested.

Downsides:

  • the first request is always slow (cold start);
  • there's a short window of inconsistency between the DB and the cache;
  • when a popular key expires, many requests hit the DB at once (a stampede).

It's important to delete the cache entry after the commit, through @TransactionalEventListener(phase = AFTER_COMMIT) or TransactionSynchronization. Otherwise the cache is cleared even if the transaction rolls back, or someone re-caches the old value before the commit.