Performance Boosters: Caching Strategies
7 min read
Before we write a single line of code, let us address the elephant in the room: Speed. Modern applications need to be fast. If a user has to wait more than a few seconds for a page to load, they will leave.
The Problem: Querying a database, running heavy mathematical computations, or calling a third-party API takes time. It consumes network bandwidth, CPU cycles, and disk I/O. If 10,000 users ask your application for the exact same daily menu, your server will query the database 10,000 times. That is highly inefficient and a great way to crash your database.
The Solution: Caching. Caching is the process of storing copies of frequently accessed data in a temporary, high-speed storage layer (usually RAM). When a request comes in, the system checks this temporary storage first. If the data is there, it is returned instantly, completely bypassing the heavy database query or computation.
Let's explore how to implement this in Spring Boot, progressively moving from the core concepts to industry-standard distributed setups.
1. The Caching Concept: Why compute the same thing twice? 🧠
Imagine you are running a pizza shop (the server). You have customers (requests) coming in constantly. If you, the chef, forget where you put the cheese every time a new customer walks in, you are going to have a bad time. You need a way to remember things—ingredients, recipes, and the cash register—while handling hundreds of orders at once.
If ten customers in a row order a "Margherita Pizza," you do not need to look up the recipe in your massive, heavy cookbook (the database) ten separate times. You look it up once, memorize it (the cache), and instantly serve the next nine customers.
In software engineering, computing the same deterministic result multiple times is a waste of resources.
What happens under the hood?
When you introduce caching, your system workflow changes from a direct read to a "Look-Aside" read:
- Request arrives: "Get me user profile #101".
- Check Cache: The application checks RAM.
- Cache Miss: If the data is missing, the application queries the database, retrieves the data, saves a copy in the cache, and returns it to the user.
- Cache Hit: If the next user asks for profile #101, the application fetches it directly from the cache in milliseconds. The database is never touched.
Interesting Fact: RAM is astronomically faster than a standard hard drive or SSD. Fetching data from an in-memory cache often takes less than a millisecond, compared to 10–100 milliseconds for a network database call. Over millions of requests, this saves hours of compute time!
2. Enabling Spring Cache: @EnableCaching and @Cacheable 🛠️
Spring Boot makes caching incredibly simple by providing an abstraction layer. You do not need to write complex boilerplate code to check if data exists in memory; you just use annotations.
Step 1: The Dependency
To use Spring's default caching mechanism, add the cache starter to your pom.xml or build.gradle.
Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>Step 2: Enable Caching
You must explicitly tell Spring to enable caching. This is done by adding the @EnableCaching annotation to your main application class or a configuration class.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching // Flips the switch to enable cache processing
public class PizzaApplication {
public static void main(String[] args) {
SpringApplication.run(PizzaApplication.class, args);
}
}Note: Without a specific provider configured, Spring defaults to ConcurrentMapCacheManager, which just stores data in a simple Java ConcurrentHashMap (local memory). Perfect for getting started!
Step 3: Use @Cacheable
The @Cacheable annotation is placed on a method. It tells Spring: "Before executing this method, check the cache. If the value is there, return it immediately. If not, run the method and store the result."
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class MenuService {
// "pizzas" is the name of the cache "bucket".
// "#id" tells Spring to use the method parameter as the cache key.
@Cacheable(value = "pizzas", key = "#id")
public Pizza getPizzaById(Long id) {
System.out.println("Executing heavy database query for pizza " + id + "...");
return database.findById(id);
}
}How Spring handles this (Under the hood):
Spring creates a Proxy around MenuService. When another class calls getPizzaById(1), the Proxy intercepts the call. It checks the map pizzas for the key 1. If found, the actual method is entirely skipped.
3. Cache Maintenance: Eviction and Updating with @CacheEvict and @CachePut 🧹
"There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton
The Problem: Stale Data.
If we cache the price of a Margherita pizza as 12, the cache still holds $10. Customers will keep buying it at the old price, and the pizza shop goes bankrupt. We need to synchronize the cache with the database.
The @CachePut Annotation (Updating)
@CachePut is used to update the cache without skipping the method execution. It always runs the method and places the returned result into the cache. We use this on update/save operations.
import org.springframework.cache.annotation.CachePut;
@Service
public class MenuService {
@CachePut(value = "pizzas", key = "#pizza.id")
public Pizza updatePizza(Pizza pizza) {
System.out.println("Updating database and cache for pizza " + pizza.getId());
return database.save(pizza); // Returns the updated pizza, which is then cached!
}
}Crucial Rule: Never put @Cacheable and @CachePut on the exact same method. They have conflicting behaviors! @Cacheable skips execution if data exists; @CachePut forces execution.
The @CacheEvict Annotation (Deleting)
@CacheEvict removes data from the cache. We use this when a record is deleted, or when we want to wipe the entire cache clean.
import org.springframework.cache.annotation.CacheEvict;
@Service
public class MenuService {
// Evicts a single item by its key
@CacheEvict(value = "pizzas", key = "#id")
public void deletePizza(Long id) {
database.deleteById(id);
}
// Wipes the entire "pizzas" cache bucket.
// Useful for massive bulk updates or daily resets.
@CacheEvict(value = "pizzas", allEntries = true)
public void resetMenuCache() {
System.out.println("All pizza caches have been destroyed! 🧨");
}
}4. Scaling Up: Moving from Local Caching to Distributed Redis 🌐
The Problem: The default ConcurrentHashMap cache lives in the RAM of your running Java application.
If your application becomes popular, you will run multiple instances of it behind a Load Balancer (e.g., App Server A, App Server B, App Server C).
If a user asks Server A for Pizza #1, Server A caches it locally. If the next user asks Server B for Pizza #1, Server B does not know about Server A's cache and has to hit the database anyway! Furthermore, if Server A updates the price, Server B still has the old price. Chaos ensues.
The Solution: Distributed Caching.
Distributed caching stores the cache data on a completely separate, centralized server. All instances of your Spring Boot application connect to this central cache. Redis (Remote Dictionary Server) is the absolute industry standard for this.
Step 1: Add Redis Dependencies
Replace or append to your cache starter with the Spring Data Redis starter.
Gradle:
implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'Step 2: Configure Application Properties
Tell Spring Boot where your Redis server is located. (Assuming you have Redis running locally via Docker or natively on port 6379).
application.yml:
spring:
cache:
type: redis
data:
redis:
host: localhost
port: 6379Spring Boot Auto-configuration is pure magic here. Just by adding the dependency and spring.cache.type=redis, Spring immediately swaps out the local Map cache for a RedisCacheManager.
Step 3: Industry Standard - Setting a TTL (Time-To-Live)
If you never clear Redis, it will eventually run out of RAM and crash. Industry standard dictates that cached data must have an expiration time (TTL).
You can configure the RedisCacheManager behavior using a configuration bean:
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)) // Data expires after 10 minutes ⏰
.disableCachingNullValues() // Prevent caching nulls to save space
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
}
}Now, whenever your @Cacheable methods run, the returned objects are converted to JSON, shipped over the network to your Redis server, and set to self-destruct after 10 minutes. Absolute perfection!
📚 References and Further Reading
Challenge
You are tasked with optimizing the performance of an e-commerce application's ProductService. Your goal is to implement a comprehensive caching strategy using Spring Boot and a distributed Redis cache.
Part 1: Service Layer Caching
Apply the correct Spring Cache annotations to the methods in the ProductService class to achieve the following behavior:
getProductById(Long id): This method should be cacheable. When called, it should first check for the product in a cache namedproducts. The cache key should be theidof the product.updateProductPrice(Long id, double newPrice): This method updates a product's price. After its execution, it must update the corresponding entry in theproductscache with the new product details. The method should always execute and not be skipped, even if a cached value exists. The cache key should be the productid.deleteProduct(Long id): This method should remove a specific product from theproductscache, identified by itsid.deleteAllProducts(): This method should completely clear all entries from theproductscache.
Part 2: Distributed Redis Cache Configuration
Create a Java configuration class named CacheConfig to configure Redis as the caching provider. This class must define a RedisCacheConfiguration bean with the following specific settings:
- The default Time-To-Live (TTL) for all cache entries must be set to 10 minutes.
- The configuration must explicitly disable the caching of
nullvalues. - Values stored in the cache must be serialized to JSON format using the
GenericJackson2JsonRedisSerializer.
Complete the provided ProductService and CacheConfig classes to meet these requirements.
Expected result
Your solution should consist of the two completed Java classes. The ProductService methods should be correctly annotated, and the CacheConfig class should be fully implemented to provide the required Redis cache configuration bean.
Correct ProductService.java
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
// Assume a ProductRepository is injected and used by these methods.
@Cacheable(value = "products", key = "#id")
public Product getProductById(Long id) {
System.out.println("Fetching product " + id + " from DB");
return new Product();
}
@CachePut(value = "products", key = "#id")
public Product updateProductPrice(Long id, double newPrice) {
System.out.println("Updating product " + id + " in DB");
return new Product();
}
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
System.out.println("Deleting product " + id + " from DB");
}
@CacheEvict(value = "products", allEntries = true)
public void deleteAllProducts() {
System.out.println("Deleting all products from DB");
}
}Correct CacheConfig.java
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
}
}