Kubernate

Thursday, November 13, 2025

Spring Boot - Caching - In case cache data changed by DB

In Spring Boot, when cached data is updated by the user, you should use cache eviction or update mechanisms like @CacheEvict, @CachePut, or a write-through strategy to ensure consistency between cache and database.

Here’s how to handle this effectively:


๐Ÿ”„ 1. Use @CacheEvict to Remove Stale Data

When a user updates data, you can evict the corresponding cache entry so that future reads fetch fresh data from the database.

@CacheEvict(value = "users", key = "#user.id")
public void updateUser(User user) {
    userRepository.save(user);
}
  • value: cache name
  • key: identifies the specific entry to evict
  • You can also use allEntries = true to clear the entire cache if needed.

๐Ÿ” 2. Use @CachePut to Update Cache After Write

If you want to update the cache immediately after modifying the data:

@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
    return userRepository.save(user);
}
  • This ensures the cache is updated with the latest data after the DB write.

๐Ÿง  3. Use Cache-Aside Strategy with Manual Invalidation

Let the application manage cache reads and writes explicitly:

public User getUser(Long id) {
    return cache.getOrElse(id, () -> userRepository.findById(id));
}

public void updateUser(User user) {
    userRepository.save(user);
    cache.remove(user.getId()); // or cache.put(user.getId(), user)
}
  • This gives you full control over cache lifecycle.

⚙️ 4. Write-Through Strategy with Redis or Caffeine

Use Spring Boot with Redis or Caffeine to automatically write to both cache and DB.

  • With Redis, you can configure TTL and use pub/sub for distributed invalidation.
  • With Caffeine, you can use refreshAfterWrite or expireAfterWrite for auto-refresh.

๐Ÿงช 5. Testing and Monitoring

  • Use Actuator endpoints to inspect cache state.
  • Log cache hits/misses to tune performance.
  • Consider using Spring Events or AOP to centralize cache invalidation logic.

Would you like a ready-to-use Spring Boot service layer example with Redis or Caffeine showing @Cacheable, @CacheEvict, and @CachePut in action?

No comments:

Post a Comment

Spring Boot - Bean LifeCycle

 Here is a clear, step-by-step lifecycle of a Spring Boot application , explained in a simple + interview-ready way. ๐Ÿ”„ Spring Boot Applica...

Kubernate