Stage 11: Spring Boot, lesson 7 of 8

Caching with Spring and Redis

Intermediate3 min read@since 17Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

Caching stores the results of expensive calls so repeated requests are fast.

Spring's cache support works with annotations:

  • @EnableCaching on 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

Java
@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
    }
}
application.yml with Redis (add spring-boot-starter-data-redis)
spring:
  cache:
    type: redis
    redis:
      time-to-live: 10m
  data:
    redis:
      host: localhost
      port: 6379

Common 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

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.