Skip to main content
PreparationZone Logo
PrepZone

Spring Cache + Redis

@Cacheable, cache eviction and Redis as a distributed cache backend.

Pass checkpoint below

Why this matters

  • Catalog lookups by ISBN dominate BookStore traffic — caching bestseller lists and book details cuts database load by orders of magnitude.
  • A local in-memory cache per JVM goes stale when inventory changes on another node; Redis gives every instance the same view.
  • @Cacheable keeps caching logic out of business code — the service method looks like a plain database read until you inspect the annotations.

@Cacheable

L1 · Fresher

Cache method results by key — BookStore catalog lookups avoid hitting Postgres on every request.

Cache eviction

L2 · Intermediate

@CacheEvict on updates keeps Redis in sync when prices change; define TTLs for stale reads you can tolerate.

Cache stampede

L3 · Advanced

Use locking or early expiration to prevent thundering herd when hot keys expire together.

Distributed cache consistency

L4 · Expert

Cache-aside vs write-through — document which BookStore endpoints are eventually consistent for readers.

Cache-aside with ElastiCache

1. GET2. miss3. SET+TTLCOMPUTE
EKS API podstreamhub-api
DATABASE
RDS Postgressource of truth
DATABASE
ElastiCachesub-ms reads
App checks Redis first; on miss loads RDS and populates cache with TTL.

Cache abstraction pieces

  • @EnableCaching — activates Spring's cache infrastructure and AOP proxies.
  • @Cacheable — stores the method return value; subsequent calls with the same key skip execution.
  • @CacheEvict — removes entries when data changes.
  • @CachePut — always runs the method and updates the cache with the fresh result.
  • RedisCacheManager — maps cache names to Redis keys with optional TTL per cache.

Enable caching with Redis

Java
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 2 sections

  • Cache reads, evict on writes
  • Programmatic cache access

Test yourself

Answer these before moving on — recall is what makes it stick.