Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 56

    Caching with Redis

    Hot Orders reads — product price snapshots, shipping quotes, session tokens — benefit from Redis sub-millisecond gets.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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

    1. Add Redis starter and point spring.data.redis.host at env placeholders.
    2. Enable caching and configure a Redis CacheManager with TTL for order-view.
    3. Annotate OrderQueryService.get with @Cacheable.
    4. Evict on place/cancel/update paths.

    Informative example

    Redis-backed order view cache.

    java
    # application.yml
    spring:
    data:
    redis:
    host: ${REDIS_HOST:localhost}
    port: ${REDIS_PORT:6379}
    cache:
    type: redis
    redis:
    time-to-live: 60s
    @Configuration
    @EnableCaching
    public class CacheConfig {
    @Bean
    RedisCacheConfiguration cacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig()
    .entryTtl(Duration.ofSeconds(60))
    .serializeValuesWith(RedisSerializationContext.SerializationPair
    .fromSerializer(new GenericJackson2JsonRedisSerializer()));
    }
    }
    @Service
    public 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.

    3 questions
    1BeginnerQuestionWhy set TTL on Redis caches?+

    Answer

    Without TTL, entries accumulate and memory grows; TTL also bounds how stale a forgotten eviction can be.
    2IntermediateQuestionWhy cache DTOs instead of JPA entities?+

    Answer

    Entities carry persistence proxies and associations that serialize poorly and can leak fields; DTOs are stable read models.
    3IntermediateQuestionHow do you avoid serving stale cancelled orders?+

    Answer

    Evict or update the cache on the command path (@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.

    Ready to mark this lesson complete?Track your journey across the entire course.