Skip to lesson

Spring @Cacheable and Redis as a shared cache

ShopLite now runs on several servers and every product page still hits MySQL. Writing cache code inside each service method is repetitive and easy to get wrong. Spring can add it for you.

Your turn: caching for three servers

ShopLite's Spring Boot API runs on three servers behind a load balancer. Before reading on, sketch how you would add caching to the service methods. Nothing is graded.

  • How could you add the cache-aside steps to findById without copying the same lines into every service method?
  • If each server keeps its own cache and an admin changes a price on server 1, what do shoppers on servers 2 and 3 see?
  • What must be true about the objects you store, and which objects should you never store?

One good design: @Cacheable, @CachePut and @CacheEvict

@Cacheable is a Spring annotation that looks in the cache before a method runs and stores the result after it, so a hit skips the method.

Turn caching on once with @EnableCaching. Three annotations then describe what each service method does to a named cache such as products.

CacheConfig.javaJava
@Configuration@EnableCachingpublic class CacheConfig {}

Example 1 · src/main/java/com/shoplite/product/ProductService.java

Runs in: the shoplite-api Spring Boot project with caching enabled

ProductService.javaJava
package com.shoplite.product;
import com.shoplite.common.ResourceNotFoundException;import java.math.BigDecimal;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.cache.annotation.CacheEvict;import org.springframework.cache.annotation.CachePut;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
@Servicepublic class ProductService {
    private static final Logger log = LoggerFactory.getLogger(ProductService.class);    private final ProductRepository repository;
    public ProductService(ProductRepository repository) {        this.repository = repository;    }
    // Read: return the cached copy if there is one; otherwise run the method and cache the result    @Cacheable(cacheNames = "products", key = "#id")    @Transactional(readOnly = true)    public ProductResponse findById(Integer id) {        log.info("Loading product {} from the database", id);        return repository.findById(id)                .map(ProductResponse::from)                .orElseThrow(() -> new ResourceNotFoundException("product", id));    }
    // Create: always run the method, then store the result under the new id    @CachePut(cacheNames = "products", key = "#result.id()")    @Transactional    public ProductResponse create(CreateProductRequest request) {        Product saved = repository.save(request.toEntity());        log.info("Created product {}", saved.getId());        return ProductResponse.from(saved);    }
    // Update: change the database, then delete the cached copy (the next read reloads it)    @CacheEvict(cacheNames = "products", key = "#id")    @Transactional    public void changePrice(Integer id, BigDecimal price) {        Product product = repository.findById(id)                .orElseThrow(() -> new ResourceNotFoundException("product", id));        product.setPrice(price);        log.info("Price of product {} changed to {}", id, price);    }}
Sample output
2026-10-16T10:15:02.114+05:30  INFO 18244 --- [shoplite-api] [nio-8080-exec-1] c.shoplite.product.ProductService        : Loading product 1 from the database
2026-10-16T10:15:31.552+05:30  INFO 18244 --- [shoplite-api] [nio-8080-exec-3] c.shoplite.product.ProductService        : Price of product 1 changed to 16999.00
2026-10-16T10:15:40.208+05:30  INFO 18244 --- [shoplite-api] [nio-8080-exec-4] c.shoplite.product.ProductService        : Loading product 1 from the database

What this code does

  • The log comes from four requests: GET /api/v1/products/1, the same GET again, a price PATCH, then the GET once more. The second GET printed nothing: the proxy answered from the cache and findById never ran.
  • changePrice has @CacheEvict, so after the update the entry products::1 is gone and the next GET loads the new price. @CachePut on create stores the new product under #result.id(), the id the database just generated.

Example 2 · What the proxy does, as a runnable program

CachingProxyDemo.javaJava
import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import java.util.Arrays;import java.util.HashMap;import java.util.Map;
@Retention(RetentionPolicy.RUNTIME)@interface Cached { }                          // our own stand-in for @Cacheable
interface ProductLookup {    @Cached    String findById(int id);}
class DatabaseProductLookup implements ProductLookup {    public String findById(int id) {        System.out.println("    database query for product " + id);        return id == 1 ? "Redmi Note 13 5G" : "Samsung Galaxy M35";    }}
class CachingHandler implements InvocationHandler {    private final Object target;    private final Map<String, Object> cache = new HashMap<>();
    CachingHandler(Object target) {        this.target = target;    }
    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Exception {        if (!method.isAnnotationPresent(Cached.class)) {            return method.invoke(target, args);                 // not cached: just pass through        }        String key = method.getName() + Arrays.toString(args);  // like Spring's default key from the arguments        if (cache.containsKey(key)) {            System.out.println("    proxy: hit " + key);            return cache.get(key);        }        Object result = method.invoke(target, args);        cache.put(key, result);        return result;    }}
public class CachingProxyDemo {    public static void main(String[] args) {        ProductLookup real = new DatabaseProductLookup();        ProductLookup proxy = (ProductLookup) Proxy.newProxyInstance(                ProductLookup.class.getClassLoader(),                new Class<?>[] {ProductLookup.class},                new CachingHandler(real));
        for (int id : new int[] {1, 1, 2, 1}) {            System.out.println("findById(" + id + ") -> " + proxy.findById(id));        }    }}
Output
    database query for product 1
findById(1) -> Redmi Note 13 5G
    proxy: hit findById[1]
findById(1) -> Redmi Note 13 5G
    database query for product 2
findById(2) -> Samsung Galaxy M35
    proxy: hit findById[1]
findById(1) -> Redmi Note 13 5G

What this code does

  • Proxy.newProxyInstance builds an object that implements ProductLookup and sends every call to CachingHandler.invoke. Our @Cached annotation plays the role of @Cacheable.
  • The handler builds a key from the method name and arguments, returns the stored result on a hit and calls the real method only on a miss. Spring's proxy is usually a generated subclass rather than a JDK interface proxy, but it works the same way.

What each annotation does:

  • @Cacheable: on a hit, return the copy and do not run the method; on a miss, run it and store the result.
  • @CachePut: always run the method, then store its result. Good for a newly created item.
  • @CacheEvict: run the method, then remove the entry (or all entries with allEntries = true). This is the cache-aside update rule.

Spring does this with a proxy: the object other beans receive is a wrapper around your service. The wrapper runs the cache logic and calls your method only when needed. If the method throws an exception, nothing is cached.

Predict the output

How many database queries?

Count the queries that findById sends to MySQL.

Round 1 of 3

Three calls on a service whose findById is annotated with @Cacheable("products").

service.findById(1);
service.findById(1);
service.findById(2);

Cache keys, conditions and the self-invocation trap

Self-invocation is a method calling another method of the same class with this; the call skips the proxy, so @Cacheable is silently ignored.

The cache key decides which calls share an entry. By default Spring builds it from the method arguments, and key = "#id" names one parameter with SpEL, Spring's small expression language.

Java
@Cacheable(cacheNames = "products",           key = "#id",                       // one entry per product id           condition = "#id > 0",             // checked before the call           unless = "#result == null",        // checked after the call           sync = true)                       // one loader per missing keypublic ProductResponse findById(Integer id) { ... }

Example 3 · The self-invocation trap, and one fix

SelfInvocationDemo.javaJava
import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;
@Retention(RetentionPolicy.RUNTIME)@interface Cached { }
interface Catalogue {    @Cached    String findById(int id);
    List<String> cartView(int... ids);           // not cached itself}
class CatalogueImpl implements Catalogue {    Catalogue self = this;                       // the fix sets this to the proxy
    public String findById(int id) {        System.out.println("    database query for product " + id);        return "product " + id;    }
    public List<String> cartView(int... ids) {        return Arrays.stream(ids).mapToObj(id -> self.findById(id)).toList();    }}
class CachingHandler implements InvocationHandler {    private final Object target;    private final Map<String, Object> cache = new HashMap<>();
    CachingHandler(Object target) {        this.target = target;    }
    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Exception {        if (!method.isAnnotationPresent(Cached.class)) {            return method.invoke(target, args);        }        String key = method.getName() + Arrays.toString(args);        if (!cache.containsKey(key)) {            cache.put(key, method.invoke(target, args));        }        return cache.get(key);    }}
public class SelfInvocationDemo {    static Catalogue proxyFor(CatalogueImpl impl) {        return (Catalogue) Proxy.newProxyInstance(Catalogue.class.getClassLoader(),                new Class<?>[] {Catalogue.class}, new CachingHandler(impl));    }
    public static void main(String[] args) {        CatalogueImpl impl = new CatalogueImpl();        Catalogue catalogue = proxyFor(impl);        System.out.println("Inner call through 'this' (cache skipped):");        catalogue.cartView(1, 1, 1);
        CatalogueImpl impl2 = new CatalogueImpl();        Catalogue catalogue2 = proxyFor(impl2);        impl2.self = catalogue2;                 // inner calls now go through the proxy        System.out.println("Inner call through the proxy (cache used):");        catalogue2.cartView(1, 1, 1);    }}
Output
Inner call through 'this' (cache skipped):
    database query for product 1
    database query for product 1
    database query for product 1
Inner call through the proxy (cache used):
    database query for product 1

What this code does

  • cartView calls self.findById, and self is the plain object, so the three inner calls skip the proxy and hit the database three times.
  • Once self points to the proxy, the inner calls pass through the cache and the database is queried once. In Spring the cleaner fix is to put the cached method in a separate bean and inject it.

condition decides before the call whether to use the cache at all; unless decides after the call whether to store the result. sync = true lets only one thread load a missing key, which helps against a stampede.

The classic pitfall is self-invocation: this.findById(id) never passes through the proxy. Call the cached method from another bean, or move it into its own small service.

Fix the error

Fix the cache annotation trap

Each service misbehaves. Pick the line that fixes it.

Round 1 of 2

The database is queried for every invoice line, although productName is cached.

public String invoiceLine(int id, int qty) {
String name = productName(id);
return qty + " x " + name;
}

Error

products cache stays empty; MySQL is queried on every call.
#id needs the parameter names in the compiled class. Spring Boot's Maven parent compiles with -parameters, so it works out of the box; without it, use #p0 (the first argument).

In-memory cache per server vs a shared cache

A shared cache is one cache server that every app server reads and writes, so a single eviction is seen by all of them.

The program below keeps one local cache on each of three servers, changes a price on server-1, and compares it with one shared cache.

Example 4 · Local caches disagree after an update; a shared cache does not

LocalVsSharedDemo.javaJava
import java.util.HashMap;import java.util.List;import java.util.Map;
class AppServer {    final String name;    final Map<Integer, Integer> cache;               // local or shared, passed in    final Map<Integer, Integer> db;
    AppServer(String name, Map<Integer, Integer> cache, Map<Integer, Integer> db) {        this.name = name;        this.cache = cache;        this.db = db;    }
    int price(int id) {        return cache.computeIfAbsent(id, db::get);    }
    void changePrice(int id, int price) {        db.put(id, price);        cache.remove(id);                             // evicts only in the cache this server sees    }}
public class LocalVsSharedDemo {    static void run(String title, List<AppServer> servers) {        System.out.println(title);        for (AppServer s : servers) {            s.price(3);                               // every server has read the iPhone price        }        servers.get(0).changePrice(3, 64900);        for (AppServer s : servers) {            System.out.println("  " + s.name + " shows Rs " + s.price(3));        }    }
    public static void main(String[] args) {        Map<Integer, Integer> db = new HashMap<>(Map.of(3, 69900));        run("Local cache in each server:", List.of(                new AppServer("server-1", new HashMap<>(), db),                new AppServer("server-2", new HashMap<>(), db),                new AppServer("server-3", new HashMap<>(), db)));
        Map<Integer, Integer> db2 = new HashMap<>(Map.of(3, 69900));        Map<Integer, Integer> shared = new HashMap<>();        run("One shared cache:", List.of(                new AppServer("server-1", shared, db2),                new AppServer("server-2", shared, db2),                new AppServer("server-3", shared, db2)));    }}
Output
Local cache in each server:
  server-1 shows Rs 64900
  server-2 shows Rs 69900
  server-3 shows Rs 69900
One shared cache:
  server-1 shows Rs 64900
  server-2 shows Rs 64900
  server-3 shows Rs 64900

What this code does

  • With a local map per server, the eviction on server-1 leaves the old price 69900 in server-2 and server-3. Which price a user sees depends on which server the load balancer picks.
  • With one shared map (standing in for Redis), the single eviction is seen by all three servers.

With no extra setup, Spring Boot uses a simple in-memory cache (a ConcurrentHashMap) inside each server. That is fine for one server. With three servers behind a load balancer, @CacheEvict on server-1 removes only server-1's copy, and users routed to server-2 still see the old price.

A shared cache fixes this: a new server starts with a warm cache and the copies do not use app memory. The cost is a network hop (about a millisecond) on every cache read.

Predict the output

What does server-2 show?

The price changes from 1999 to 1799 on server-1. All caches held 1999 before.

Round 1 of 2

Each server has its own in-memory cache. A shopper is routed to server-2.

server-1: changePrice(1, 1799) -> @CacheEvict removes its local copy
server-2: local cache still holds 1999
shopper -> server-2: findById(1)

Redis as the shared cache

Redis is an in-memory key-value store: each key holds a value and can have a TTL. It is the usual shared cache for Spring applications.

Spring's cache uses only a few basic Redis commands. The session below runs them in redis-cli.

Example 5 · Redis commands in redis-cli

Runs in: a terminal with redis-cli and a running Redis server

Terminal
redis-cli SET product:1 '{"id":1,"price":17999.00}' EX 600redis-cli GET product:1redis-cli TTL product:1redis-cli DEL product:1redis-cli GET product:1
Sample output
OK
"{\"id\":1,\"price\":17999.00}"
(integer) 597
(integer) 1
(nil)

What this code does

  • SET ... EX 600 stores the JSON with a 600-second TTL; TTL shows the seconds left (the exact number depends on how fast you type).
  • After DEL, GET returns (nil), which is a miss. These are the same operations Spring performs for @Cacheable and @CacheEvict.

The commands behind Spring's cache:

  • SET key value EX 600: store a value that expires in 600 seconds.
  • GET key: read it; (nil) means a miss.
  • DEL key: remove it (what @CacheEvict does).
  • TTL key: seconds left; -1 means no expiry, -2 means the key does not exist.
Spring's Redis cache stores an entry under cacheName::key, so findById(1) lives at products::1.

Configuring the Redis cache: spring.cache.type=redis

Serialization is turning a Java object into bytes so it can be stored in Redis or sent over a network.

With the spring-boot-starter-data-redis and spring-boot-starter-cache starters on the classpath, a few properties switch the cache to Redis and give every entry a TTL.

Properties
spring.cache.type=redisspring.cache.cache-names=products,categoriesspring.cache.redis.time-to-live=10mspring.cache.redis.cache-null-values=falsespring.data.redis.host=${REDIS_HOST:localhost}spring.data.redis.port=6379

Example 6 · Why cached classes must be Serializable by default

SerializationDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;
record PlainView(int id, String name) { }
record CacheableView(int id, String name) implements Serializable { }
public class SerializationDemo {    static byte[] toBytes(Object value) throws IOException {        ByteArrayOutputStream bytes = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {            out.writeObject(value);                  // what the default Redis cache does        }        return bytes.toByteArray();    }
    static Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {            return in.readObject();        }    }
    public static void main(String[] args) throws Exception {        try {            toBytes(new PlainView(1, "Redmi Note 13 5G"));        } catch (java.io.NotSerializableException e) {            System.out.println("PlainView: " + e);        }
        byte[] data = toBytes(new CacheableView(1, "Redmi Note 13 5G"));        System.out.println("CacheableView: stored, read back as " + fromBytes(data));    }}
Output
PlainView: java.io.NotSerializableException: PlainView
CacheableView: stored, read back as CacheableView[id=1, name=Redmi Note 13 5G]

What this code does

  • ObjectOutputStream is Java serialization, which the default Redis cache serializer uses. A record without Serializable fails with NotSerializableException.
  • Adding implements Serializable lets the value be stored and read back. A JSON serializer avoids this rule and keeps the stored value readable.

By default Spring's Redis cache uses Java serialization, so every cached class (such as ProductResponse) must implement Serializable, and the stored value is unreadable binary.

Many teams configure a JSON serializer through a RedisCacheConfiguration bean instead: it is readable and survives class changes better. Cache DTOs, never JPA entities.

Order of execution

Switch ShopLite to Redis

Put the steps in a sensible order.

Next step

Check your understanding

11 quick questions