Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Fundamentals › Architecture and operations

Caches

What is a cache, and what do you gain and lose by using one?

Why it exists — If something that takes time, such as a database query or a call to another server, is done again for every request even though the same answer is known to come out, the user waits every time and the same work piles up on the original source. A cache keeps an answer, once obtained, in a place from which it can be fetched quickly and reuses it, so that slow work is not repeated. In return, when the original changes, you have to separately take care of when to discard the value in the cache.

Where it's used today — Things that are read often but change rarely, such as product information, category lists, and settings, are put in a cache. In Spring, you write @EnableCaching on a configuration class, @Cacheable on a method that looks something up, and @CacheEvict on a method that changes the value. Where the cache is kept is chosen with a CacheManager bean, and the same annotations work from the memory of a single server to Redis, which several servers look at together. Things that must always have the current value, such as remaining stock or an account balance, are not put in a cache, or the value in the cache is deleted immediately when the value changes.

A cache is a device that writes down a result that took a long time to get, in a place close by, and hands out what it wrote down when the same thing is asked for again, without going to the source. A cache is not the source. It is a copy of the value from the moment it was read from the source, so after the source changes, it can hand out an old value. In Spring you do not write the cache yourself. You write annotations that Spring provides. In the code on the screen, @EnableCaching on the CacheConfig class turns the caching feature on, and the ConcurrentMapCacheManager registered with @Bean (a class provided by Spring) keeps a cache named product in memory. If you write @Cacheable("product") above the find method of ProductService (an example class we made), Spring looks at the product cache around the call to find and writes down the result. The body of find reads the value from the source (a Map that stands in for a database) and counts the reads from the source with loadCount. The lab does not measure real time. It shows "how many times the slow work was done" by the number of reads from the source. Caller (an example class we made) looks up product 1 twice with the ProductService bean that Spring supplied. You can remove the @Cacheable line, change the source with rename between the two lookups, or write @CacheEvict above rename, and you see how many times the source is read and whether the second value you receive is the same as the source. The last question compares what @Cacheable does with a version written by hand with a Map.

Checked against real execution · Compiled nine combinations with the same source as the screen on Spring Framework 7.0.9 (spring-context, @EnableCaching + ConcurrentMapCacheManager) and JDK 21, ran them, and checked the output, whether a proxy exists, and the values written in the cache at each step

Concepts in this lab

Cache
Storing frequently used data or computed results ahead of time in a place that can be accessed quickly, and reusing them. Responses get faster and the load on the source drops, because the source (usually a database) is not queried every time. In return, you must manage the problem of stale values that remain when the source changes.
Cache hits and misses
When you look for a value in a cache, one of two things happens. If what you look for is already written in the cache, it is called a hit (cache hit), and the written-down value is returned as it is without going to the source. If it is not written, it is called a miss (cache miss), and the value is read from the source, written in the cache, and returned. The cache abstraction of Spring works in the same order: if the method was already called with the same arguments, it returns the cached result without executing the method, and otherwise it executes the method and puts the result in the cache and returns it. The first lookup is always a miss, and the more hits there are, the less slow work goes all the way to the source.
@Cacheable
This annotation stores the result of a method in a cache so that, when the method is called again with the same arguments, the value in the cache is returned without running the body. A proxy receives the call and looks up the cache first, and only when the value is not there does it run the body and then store the result. By default, the cache key is the arguments of the method, and cacheNames sets which cache the result goes into. If you write a condition in unless, a result for which the condition is true is not stored (for example, when the result is null). Because this is the work of a proxy, it is not applied when the method is called with this from within the same class.
@CacheEvict and @CachePut
Why it exists — If you put code that deletes or fixes the cache directly into every method that changes data, code that handles the cache store gets mixed with business code, and it is easy to miss. @CacheEvict and @CachePut let you do this with only the cache name and key written above the method.
Where it's used today — A common use is to put @CacheEvict on a method that edits or deletes product information. When a single key cannot point to the entries, as with a list cache, you empty that cache entirely with allEntries = true.
These are two annotations used to keep the values in a cache in step with the source data. @CacheEvict removes the value for the given key from the cache when the method is called, so that the next lookup runs the body again. Unlike @Cacheable, @CachePut does not skip the body. It always runs the body and puts the returned value in the cache, overwriting the existing value. If neither of them is on a method that changes data, the value from before the change remains in the cache, and the code that looks it up receives the stale value.
@EnableCaching and CacheManager
Why it exists — So that the code that uses a cache is not tied to the kind of store, the switch that turns the cache on (@EnableCaching) and the place where the store is chosen (CacheManager) were separated. Even if you change the store from memory to Redis, the methods that have @Cacheable are not changed.
Where it's used today — Write @EnableCaching once on a configuration class of a Spring application, and register as a bean the CacheManager of a store such as a memory cache for a single server, or Redis when several servers must see the same values.
@EnableCaching is an annotation that you write on a configuration class to turn on the caching feature of Spring. Only with it does Spring look for methods that have cache annotations such as @Cacheable and @CacheEvict, put a proxy in front of that bean, and insert the work of looking at the cache and writing to it. If you remove the @EnableCaching line, no proxy is created even if you write @Cacheable, and the method body runs every time it is called. CacheManager is a Spring interface that hands out caches by name, and where the values are actually kept is decided by which implementation you register as a bean. ConcurrentMapCacheManager, provided by spring-context, keeps one ConcurrentHashMap in memory for each name, and it has no setting for the validity time of a written-down value.
Stale data in a cache
Stale data in a cache is a value that stays in the cache after the value in the source has changed, so that it differs from the source. The side that uses the cache does not look at the source when there is a hit, so it receives the old value without knowing that it changed. If you also erase the value written in the cache when you change the source, the next lookup is a miss and reads the changed value again (only that one lookup is slow). Another way is to give a written-down value a validity time. The HTTP caching specification (RFC 9111, section 4.2) calls a stored response stale when it is past its determined freshness lifetime, and this word is the term of the specification for a response whose time has passed.

Try these

Running with the default settings

  1. When the program starts, Spring sees @EnableCaching on CacheConfig and turns the caching feature on, and it keeps the ConcurrentMapCacheManager returned by the cacheManager method as a bean. This CacheManager keeps a cache named product in memory, and the product cache is still empty. Because find in ProductService has @Cacheable, Spring does not use the ProductService object itself as the bean. It creates a proxy (an object of the class ProductService$SpringCGLIB$0) that receives calls first, and keeps that as the bean. The proxy holds a reference to the real ProductService object, and the productService field of Caller points to this proxy. The value for key 1 in the source is "keyboard".
  2. The run() method of the Caller bean is called, and the line productService.find(1L); runs. The proxy, which received the call first, looks in the product cache for key 1 before entering the find body. The cache is empty, so no value is written there. This case is called a miss.
  3. So the proxy runs the find body of the real ProductService object. The body increases loadCount to 1 and reads the value "keyboard" for key 1 from the source.
  4. When the body returns "keyboard", Spring writes that value into the product cache under key 1 and returns it to Caller. The line that writes it down is not in the code we wrote. It is what @Cacheable("product") told Spring to do.
  5. The line String second = productService.find(1L); runs. The proxy, which received the call first, looks in the product cache for key 1 and finds "keyboard" written there. This case is called a hit. The proxy does not run the find body and returns the written-down "keyboard". loadCount is still 1.
  6. The last line, System.out.println, prints the values of loadCount(), second, and source(1L) in that order. The output is "1 / keyboard / keyboard". The value you received is the same as the value in the source.

Result of this run

Code

// Turn the caching feature on: @Cacheable and @CacheEvict work only with this setting
@Configuration
@EnableCaching
class CacheConfig {
    // Where the cache is kept: ConcurrentMapCacheManager, provided by Spring (it uses a Map in memory)
    @Bean
    CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("product");
    }
}

// An example product service we made
@Service
class ProductService {
    // The source: the original values of product names (a Map that stands in for a database)
    private final Map<Long, String> db = new HashMap<>(Map.of(1L, "keyboard"));
    // How many times the source was read
    private int loadCount = 0;

    // Writes the result in the product cache by id. If called again with the same id, the body does not run
    @Cacheable("product")
    public String find(Long id) {
        // Read from the source (in real code, this is where slow work such as a database query goes)
        loadCount++;
        return db.get(id);
    }

    public void rename(Long id, String name) {
        db.put(id, name);
    }

    public int loadCount() {
        return loadCount;
    }

    public String source(Long id) {
        return db.get(id);
    }
}

// An example class we made that calls ProductService
@Component
class Caller {
    @Autowired
    ProductService productService;

    void run() {
        // Look up product 1 for the first time
        productService.find(1L);
        // Look up product 1 again
        String second = productService.find(1L);
        // Reads from the source / second value received / value in the source
        System.out.println(
            productService.loadCount() + " / " + second + " / " + productService.source(1L));
    }
}

Assumptions of this model

We checked Spring Framework 7.0.9 (spring-context) by running it on JDK 21.0.12.1. All nine combinations (three ways of putting a cache on find times three things that can happen between the two lookups) were checked in the same way. The source is the same as the code on the screen (only the package and import lines and measurement lines marked with PROBE at the end were added). It was compiled with javac (with -parameters turned on; the build settings of Spring Boot also turn this on), and a new Java process was started for each combination. The classes on the screen were found by AnnotationConfigApplicationContext through component scanning, and the checking program called run() of the Caller bean and captured the line that run() printed. What was compared is the three printed values (the number of reads from the source, the value the second find returned, and the value in the source). As facts that the step sentences rely on, we also checked the class of the ProductService bean (the ProductService$SpringCGLIB$0 proxy when find has @Cacheable or rename has @CacheEvict, and plain ProductService when neither is there or when the cache is written by hand), whether the object that Caller received is that bean, and loadCount and what was written in the cache after the first find, after rename, and at the end (for Spring, the product cache of the CacheManager, and for the hand-written version, the Map in the cache field). As a variation that is not on the screen, we also ran @CacheEvict("product") with no key above rename, and in that case the value for key 1 in the product cache was not erased and the second find received "keyboard" (because the key becomes both parameters used together). That ConcurrentMapCacheManager has no method that sets a validity time was checked by opening the public methods of this class with javap. Nothing was shortened in the code on the screen. This lab was run with only spring-context, without Spring Boot, and the setting with which Boot creates a CacheManager automatically was not verified. Reading from the source does not really take long and no time was measured, and "slow" is shown only by the number of reads from the source. For the documentation, we followed what we had confirmed earlier, and did not open it again this time: the Spring Framework Reference, Cache Abstraction section (https://docs.spring.io/spring-framework/reference/integration/cache/strategies.html; if the method was already called with the same arguments, it returns the cached result without executing the method) and RFC 9111 (HTTP Caching) section 4.2 (a stored response that is past its freshness lifetime is called stale). Not covered: calling find from inside the same class so that it does not pass through the proxy and the cache is not used, a null result, @CachePut, a cache that several threads write at the same time, what to throw away when the cache is full, the validity time (TTL), many requests rushing to the source when a popular value disappears all at once, the HTTP cache between a browser and a server (ETag), and Redis. These are covered in the in-depth labs "Cache abstraction", "Caching and TTL", "HTTP caching and ETag", and "Redis single-threaded execution".

Previous lab: Load balancers · Next lab: Message queues

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these