Caching with Redis
Hot Orders reads — product price snapshots, shipping quotes, session tokens — benefit from Redis sub-millisecond gets.
Introduction
Hot Orders reads — product price snapshots, shipping quotes, session tokens — benefit from Redis sub-millisecond gets.
Boot 3 uses spring-boot-starter-data-redis and spring.cache.type=redis with @EnableCaching, @Cacheable, and @CacheEvict.
Always set TTLs. Cache read models, not authoritative writes. Prefer JSON serialization over Java serialization for forward compatibility.
This lesson caches TechLearningPRO Orders read paths without serving stale prices after updates.
Purpose of this lesson
Add Redis caching to Orders read models with correct TTL and eviction on Boot 3.
Understanding the topic
Annotation caching delegates to Redis as a distributed CacheManager.
- @Cacheable: return cached value or compute and store.
- @CacheEvict / @CachePut: keep writes coherent.
- keys: stable SpEL keys from method args.
- TTL: per-cache configuration prevents unbounded growth.
- serialization: JSON for DTO caches across versions.
Step-by-step explanation
- Add Redis starter and point
spring.data.redis.hostat env placeholders. - Enable caching and configure a Redis
CacheManagerwith TTL fororder-view. - Annotate
OrderQueryService.getwith@Cacheable. - Evict on place/cancel/update paths.
Informative example
Redis-backed order view cache.
# application.ymlspring:data:redis:host: ${REDIS_HOST:localhost}port: ${REDIS_PORT:6379}cache:type: redisredis:time-to-live: 60s@Configuration@EnableCachingpublic class CacheConfig {@BeanRedisCacheConfiguration cacheConfiguration() {return RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(60)).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));}}@Servicepublic class OrderQueryService {private final OrderRepository orders;public OrderQueryService(OrderRepository orders) {this.orders = orders;}@Cacheable(cacheNames = "order-view", key = "#id")@Transactional(readOnly = true)public OrderView get(long id) {return orders.findById(id).map(OrderView::from).orElseThrow(() -> new OrderNotFoundException(id));}@CacheEvict(cacheNames = "order-view", key = "#id")public void evict(long id) { /* called from command service after mutations */ }}
Real-world use
Catalog price banners hit Postgres on every homepage refresh until Orders cached the quote DTO in Redis with a 60s TTL. CPU dropped sharply; eviction on price publish kept flash-sale amounts honest.
Security implications
Caches can amplify data exposure if keys are guessable or values are too rich.
- Do not cache responses that embed other customers' PII under a public key.
- Include tenant/customer in the cache key when data is private.
- Redis AUTH passwords via
${REDIS_PASSWORD}only.
Best practices
- Cache DTOs/records, not entities.
- Name caches per use case; set explicit TTLs.
- Monitor hit ratio and Redis memory as product metrics.
Common mistakes
- Caching JPA entities with lazy collections — serialization pain and leaks.
- No TTL → Redis memory growth until eviction storms.
- Forgetting eviction after cancel leaves customers seeing active orders.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhy set TTL on Redis caches?+
Answer
2IntermediateQuestionWhy cache DTOs instead of JPA entities?+
Answer
3IntermediateQuestionHow do you avoid serving stale cancelled orders?+
Answer
@CacheEvict/@CachePut) in the same use case that mutates state.Hands-on exercise
Lab. Cache OrderView by id with a short TTL. Call get twice and confirm one DB hit. Cancel the order and assert the next get refreshes after eviction.
Summary
Caching with Redis gives TechLearningPRO Orders fast reads when TTLs, DTO values, and eviction stay aligned with command-side updates.