Caching With Spring and Redis: Cache-Aside, a TTL per Kind of Data, Eviction on Edit and Stopping the Stampede
A 150 ms stats query goes behind Redis with @Cacheable: about 160 ms per call becomes 12 ms. Stats live 30 seconds, articles 10 minutes and an edit evicts them at once. Fifty simultaneous misses run 50 queries until sync = true and a locking cache writer make it one. Under k6, p95 falls from 160 ms to 19 and requests rise from 2,040 to 29,752.
What you will learn
- Put Redis in front of a slow query with @Cacheable (cache-aside)
- Choose a TTL per cache with RedisCacheManagerBuilderCustomizer and evict on edit with @CacheEvict
- Stop a cache stampede with sync = true and a locking Redis cache writer
- Decide what must never be cached
Before you start
- Spring Boot services and controllers
- Redis basics
Every cached item needs two answers: how long it lives, and what removes it. This article puts Redis in front of two kinds of data in a small Relay desk, CacheDesk: dashboard stats from a slow aggregate query, and help articles. A SlowDatabase class stands in for PostgreSQL, so each query costs real time and is counted.
Cache-aside with @Cacheable
@SpringBootApplication
@EnableCaching
public class CacheDeskApp { ... }
@Service
public class DeskService {
// cache-aside: look in Redis first; on a miss, query and store under stats::all
// sync = true: when many requests miss at once, one of them queries, the rest wait for it
@Cacheable(cacheNames = "stats", key = "'all'", sync = true)
public Stats stats() {
return db.countTickets();
}
@Cacheable(cacheNames = "articles", key = "#id")
public Article article(long id) {
return db.findArticle(id);
}
// an edit removes the cached copy, so the next read sees the new title
@CacheEvict(cacheNames = "articles", key = "#id")
public void renameArticle(long id, String title) {
db.renameArticle(id, title);
}
}
spring.cache.type: redis in the YAML picks Redis. countTickets() pauses 150 ms, like an aggregate over every ticket. On a hit the method does not run. On a miss it runs and the result is stored under stats::all. Each article gets its own key, articles::7. The cached records implement Serializable so they can be stored.
$ CACHE=none docker compose up -d --build # every read goes to the database
0.276719s
0.167842s
0.158979s
$ docker compose up -d app # with Redis
1.107004s
0.011872s
0.014298s
Without a cache every call takes about 160 ms. With Redis, the first call misses and also opens the connection; the next two take 12 and 14 ms.
One TTL per kind of data
@Bean
RedisCacheManagerBuilderCustomizer deskCaches(RedisConnectionFactory redis) {
// one TTL per kind of data: how stale may it be before someone notices?
// stats on a dashboard: 30 s old is fine
var stats = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(30));
// help articles change rarely, and an edit evicts them
var articles = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10));
// a short lock in Redis: sync = true loads once, for every copy of the app
var writer = RedisCacheWriter.lockingRedisCacheWriter(redis, Duration.ofMillis(20),
TtlFunction.just(Duration.ofSeconds(5)), BatchStrategies.keys());
return builder -> builder.cacheWriter(writer)
.withCacheConfiguration("stats", stats)
.withCacheConfiguration("articles", articles);
}
The question for each TTL is how stale the data may be before someone notices. Counts on a dashboard may be half a minute old. Articles rarely change, and an edit evicts them anyway. After a load run, Redis holds the keys you would expect:
$ docker compose exec redis redis-cli --scan | sort
articles::1
articles::2
articles::3
articles::4
articles::5
stats::all
$ docker compose exec redis redis-cli ttl stats::all
12
Evict on edit
$ curl -s localhost:18550/api/articles/7
{"id":7,"title":"Change the billing email"}
$ curl -s -X PUT -H "Content-Type: text/plain" -d "Update the billing email" localhost:18550/api/articles/7
{"id":7,"title":"Update the billing email"}
$ curl -s localhost:18550/api/articles/7
{"id":7,"title":"Update the billing email"}
The new title shows at once instead of after ten minutes, because @CacheEvict removed articles::7. The TTL is the safety net, not the plan.
The stampede
When a popular key expires, every request that arrives before it is refilled misses at the same moment, and every one of them runs the slow query. The /api/stats/unguarded endpoint caches the same query without sync. Fifty requests at once:
$ seq 50 | xargs -P 50 -I{} curl -s -o /dev/null localhost:18550/api/stats/unguarded; curl -s localhost:18550/api/queries
stats queries: 50, article queries: 0
$ seq 50 | xargs -P 50 -I{} curl -s -o /dev/null localhost:18550/api/stats; curl -s localhost:18550/api/queries
stats queries: 1, article queries: 0
A trap worth knowing: with Redis, sync = true needs the locking cache writer from the config. With the default writer, the first run in this lecture still showed 50 queries. The lock lives in Redis, so it holds across every copy of the app, not just one JVM.
Under load
A k6 script hits stats and articles for 10 seconds, first with CACHE=none, then with Redis:
without cache: stats p95 160 ms articles p95 50 ms requests 2,040
with Redis: stats p95 19 ms articles p95 19 ms requests 29,752
Only 21 of 29,755 reads reached the database: a hit ratio of 99.93 percent.
What not to cache
// the open ticket list is NOT cached: an agent must see a new ticket at once
@GetMapping("/api/tickets")
public List<String> openTickets() {
return db.openTickets();
}
Put @Cacheable("tickets") on this with no eviction and a new ticket stays invisible to agents until the TTL runs out. A cache trades freshness for speed. Some data cannot make that trade. For caches in AI apps, where a wrong hit costs more than a miss, see caching layers for AI apps.
Recap
| Data | Cached? | Lives | Removed by |
|---|---|---|---|
| Dashboard stats | Yes, sync = true | 30 s | TTL |
| Help articles | Yes | 10 min | @CacheEvict on edit, then TTL |
| Open ticket list | No | An agent must see a new ticket at once |
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
A one-line JpaRepository interface and a small @Service class save and read blog posts with no SQL. Follow one save and one read through every layer, then prove it with a test.
Entities and H2 in Spring Boot: a Post Class Becomes a Table
The blog's cards are typed into HTML. A Post class with @Entity and @Id becomes the POST table in an in-memory H2 database: three pom lines, a few YAML settings, and Hibernate writes the create table SQL at startup.
Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
SeedData, a CommandLineRunner, saves three posts when the POST table is empty. HomeController puts postService.getAll() into the Model, and one postCard inside th:each becomes three cards. Three inserts at startup, one select per visit.
Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
Eight posts, three to a page, newest first. HomeController turns ?page=1&sort=oldest into a PageRequest, PostService passes it to findAll(Pageable), H2 runs one select with an offset and one count, and the Page that comes back knows it is page 2 of 3.
