Caching with Spring and Redis
Caching stores the results of expensive calls so repeated requests are fast.
Spring's cache support works with annotations:
@EnableCachingon a configuration class.@Cacheable("courses"): return the cached value if there is one; otherwise run the method and cache the result.@CacheEvict("courses"): remove stale entries when the data changes.@CachePut: always run the method and update the cache.
Pick a store:
- Caffeine: in memory, very fast, one copy per instance. Great for a single server or rarely changing data.
- Redis: shared by every instance and survives restarts. The usual choice once you run several servers.
Always set a time-to-live and a size limit. The hard parts are invalidation (when data changes) and keeping instances consistent.
Example
@Configuration
@EnableCaching
class CacheConfig {}
@Service
public class CourseService {
private final CourseRepository repo;
public CourseService(CourseRepository repo) { this.repo = repo; }
@Cacheable(value = "course", key = "#slug")
public CourseDto bySlug(String slug) { // hits the database only on a cache miss
return repo.findBySlug(slug).map(CourseDto::from).orElseThrow();
}
@CacheEvict(value = "course", key = "#cmd.slug()")
public void update(UpdateCourse cmd) { // keeps the cache fresh
// ... save the changes
}
}spring:
cache:
type: redis
redis:
time-to-live: 10m
data:
redis:
host: localhost
port: 6379Common mistake
Caching without expiry or eviction. Users see stale prices for hours, and memory grows until the app slows down.
Under the hood
Like @Transactional, caching works through a proxy, so calling a cached method from the same class skips the cache. Values stored in Redis must be serialisable; JSON serialisers survive redeployments better than Java serialisation. Watch out for cache stampedes: when a hot key expires, many requests hit the database at once; @Cacheable(sync = true) or early refresh helps.
Check yourself
Which annotation removes an entry from the cache?
How this connects
Know these first
Where this leads
You've reached the end of this thread. Try a learning path for what's next.
Part of Job-ready backend developer, Microservices and production.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.