Spring Cache and Redis for faster Java applications

Caching keeps frequently requested data in memory so a Java service can answer without querying the database every time. Redis suits distributed Spring applications because several instances can access the same cached values.

How to implement caching with Spring Cache abstraction and Redis starts with an explicit boundary around expensive reads. The annotation-based API keeps application code independent of the store, while Redis gives every instance access to the same values.

The payoff is strongest for reference data and repeated lookups, not changing records or one-off requests. Sensible expiry rules and safe failure behaviour matter more than caching every method.

Understand the cache abstraction

Add spring-boot-starter-cache and spring-boot-starter-data-redis to the build. @EnableCaching activates a proxy that intercepts supported method calls and stores their results through a CacheManager.

@Cacheable fits reads, @CachePut replaces an entry after a write, and @CacheEvict removes one. A local ConcurrentMapCacheManager provides a development fallback, but its entries are not shared between instances, so test the Redis-backed path too.

Configure Redis and cache policies

Point the application at Redis with spring.data.redis.host, spring.data.redis.port and the appropriate authentication or TLS settings. Many Australian deployments run in the Sydney ap-southeast-2 region, so nearby Redis can reduce round trips for application servers in eastern Australia.

Use a RedisCacheManager when you need distinct time-to-live values or explicit serialization:

@Bean
RedisCacheManager cacheManager(RedisConnectionFactory factory) {
    RedisCacheConfiguration defaults = RedisCacheConfiguration.defaultCacheConfig()
        .entryTtl(Duration.ofMinutes(10))
        .disableCachingNullValues()
        .computePrefixWith(name -> "javawhizz:" + name + ":")
        .serializeValuesWith(SerializationPair.fromSerializer(
            new GenericJackson2JsonRedisSerializer()));

    return RedisCacheManager.builder(factory)
        .cacheDefaults(defaults)
        .withCacheConfiguration("products",
            defaults.entryTtl(Duration.ofHours(1)))
        .build();
}

The prefix prevents collisions with other applications. Null values remain uncached, and per-cache policies give short-lived catalogue data a shorter lifetime than stable reference data.

Choose cache keys, scope and expiry

Cache data that is expensive to compute or fetch and safe to reuse. Product definitions and pricing reference data are good candidates; personalised balances and one-time tokens are poor ones. An annotation such as @Cacheable(cacheNames = "products", key = "#id", unless = "#result == null") gives each product a predictable entry.

The key must identify the same business value on every call. Include a tenant identifier when records span tenants, and avoid raw personal data because Redis tooling often displays keys. Match expiry to freshness: during Australia’s Boxing Day sales, a catalogue might tolerate a short delay, while a stock reservation must not be cached.

Apply caching to service methods

Place annotations on public methods invoked through the Spring proxy. Keep the domain operation separate from cache policy so tests can clear or bypass entries.

@Service
public class ProductService {
    private final ProductRepository repository;

    public ProductService(ProductRepository repository) {
        this.repository = repository;
    }

    @Cacheable(cacheNames = "products", key = "#id",
             unless = "#result == null")
    public Product findById(Long id) {
        return repository.findById(id).orElseThrow();
    }

    @CachePut(cacheNames = "products", key = "#product.id")
    public Product save(Product product) {
        return repository.save(product);
    }

    @CacheEvict(cacheNames = "products", key = "#id")
    public void delete(Long id) {
        repository.deleteById(id);
    }
}

Spring’s proxy does not intercept self-invocation, so move a call to another bean. For bulk changes, @Caching can combine eviction operations, including allEntries = true. Compile with parameter metadata when using #id, or use positional expressions such as #p0.

Handle failures and serialization

A cache outage should not become an application outage. Implement CacheErrorHandler to log cache-specific exceptions, and use a circuit breaker or explicit fallback where recovery matters. Keep application exceptions visible. For a support workflow, this simple contact form guide covers the form basics; submissions should bypass caching, while reusable reference data can be cached.

Store immutable data transfer objects or records instead of entities with lazy associations. The default JDK serializer requires Serializable and produces brittle payloads; a Jackson-based serializer is easier to inspect. Because type metadata can enable unsafe deserialisation, restrict Redis access and configure the serializer deliberately.

Protect data and manage invalidation

Expiry provides a backstop, but Redis memory policies may evict entries early and explicit eviction keeps reads accurate after a write. When one operation changes both a record and a search list, evict each affected cache. @Caching supports multiple eviction entries, and allEntries = true helps after a catalogue import while entries rebuild.

Treat Redis as a data store containing sensitive business information. Australian privacy expectations and the Privacy Act 1988 make data minimisation and limited retention important, so avoid caching identity documents. Use authentication, TLS in transit and encryption at rest through the hosting provider, plus restricted network access and environment-specific key prefixes.

Measure impact and roll out safely

Expose cache metrics through Spring Boot Actuator and Micrometer, then compare hits, misses, puts and evictions for each cache name. Pair those counters with application latency and Redis memory usage; a high hit rate can still hide slow network calls. When a Melbourne support team asks for a squiz during the arvo, logs should show the cache, a hashed key and the outcome without exposing customer details.

Start with one read-heavy endpoint and compare database load, p95 response time and Redis memory before expanding. Replay representative traffic, warm the cache and guard against hot keys rebuilding one missing entry concurrently, using request coalescing or a distributed lock where needed. A measured rollout limits the blast radius of a faulty key, serializer or expiry policy.