Definition
- @Cacheable marks a method whose return value should be stored in a cache; on the first call Spring executes the method and caches the result, on subsequent calls with the same key it returns the cached value without executing the method.
- @CachePut marks a method that always executes and updates the cache with its return value; use it for save or update operations that should refresh the cached data.
- @CacheEvict marks a method that removes one or all entries from the cache; use it when data changes and the cached value is no longer valid.
- Cache key is the identifier used to store and retrieve a cached value; by default it is generated from all method parameters, but you can customize it with a SpEL expression.
- TTL (Time To Live) is the duration after which a cached entry expires and is removed automatically; Spring Cache abstraction does not define TTL directly, so you configure it on the cache provider (Redis, Caffeine).
- Self-invocation problem is the issue where calling a @Cacheable method from another method in the same class bypasses the proxy and the cache is never consulted.
Think of the National Bank of India customer service desk. When Priya calls to ask her account balance, the agent (your method) looks it up in the core banking system (database). The agent writes the balance on a sticky note and pins it to the board (cache). When Priya calls again 2 minutes later, the agent checks the board first, finds the sticky note, and reads the balance immediately without querying the core system. If Priya makes a deposit (data change), the agent removes the sticky note (@CacheEvict) so the next inquiry gets the fresh balance. The sticky notes are removed every 10 minutes automatically (TTL) because balances can change.
Understanding the Concepts
What is @Cacheable and how does it work?
@Cacheable is placed on a method to tell Spring: "Before executing this method, check if the result for these arguments is already in the cache. If yes, return the cached value. If no, execute the method, cache the result, and return it."
Spring implements this using an AOP proxy. When another bean calls your @Cacheable method, the call goes through the proxy, which checks the cache before invoking the real method. This is the same proxy mechanism used by @Transactional.
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class AccountService {
private final AccountRepository accountRepository;
public AccountService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
@Cacheable(value = "accounts", key = "#accountNumber")
public Account getAccount(String accountNumber) {
System.out.println(" DB QUERY for account: " + accountNumber);
return accountRepository.findByAccountNumber(accountNumber)
.orElseThrow(() -> new RuntimeException("Account not found: " + accountNumber));
}
}
package com.bank;
import com.bank.service.AccountService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class CacheDemo implements CommandLineRunner {
private final AccountService accountService;
public CacheDemo(AccountService accountService) {
this.accountService = accountService;
}
@Override
public void run(String... args) {
System.out.println("Call 1 (cache miss):");
var account1 = accountService.getAccount("SAV2001");
System.out.println(" Result: " + account1.getHolderName());
System.out.println("Call 2 (cache hit, no DB query):");
var account2 = accountService.getAccount("SAV2001");
System.out.println(" Result: " + account2.getHolderName());
System.out.println("Call 3 (different key, cache miss):");
var account3 = accountService.getAccount("CUR3001");
System.out.println(" Result: " + account3.getHolderName());
}
}
Expected output:
Call 1 (cache miss):
DB QUERY for account: SAV2001
Result: Priya Sharma
Call 2 (cache hit, no DB query):
Result: Priya Sharma
Call 3 (different key, cache miss):
DB QUERY for account: CUR3001
Result: Rajesh Kumar
What is the difference between @Cacheable, @CachePut, and @CacheEvict?
These three annotations serve different purposes in the caching lifecycle.
| Annotation | Executes method? | Updates cache? | Use case |
|---|---|---|---|
| @Cacheable | Only on cache miss | Yes (on miss) | Read operations: get balance, get profile |
| @CachePut | Always | Always | Write operations: update balance, update profile |
| @CacheEvict | Always | Removes entry | Delete or invalidation: close account, deposit |
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
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;
import java.math.BigDecimal;
@Service
public class CachingAccountService {
private final AccountRepository accountRepository;
public CachingAccountService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
@Cacheable(value = "accounts", key = "#accountNumber")
public Account getAccount(String accountNumber) {
System.out.println(" DB QUERY: getAccount(" + accountNumber + ")");
return accountRepository.findByAccountNumber(accountNumber).orElseThrow();
}
@CachePut(value = "accounts", key = "#account.accountNumber")
@Transactional
public Account updateAccount(Account account) {
System.out.println(" DB UPDATE: updateAccount(" + account.getAccountNumber() + ")");
return accountRepository.save(account);
}
@CacheEvict(value = "accounts", key = "#accountNumber")
@Transactional
public void closeAccount(String accountNumber) {
System.out.println(" DB DELETE: closeAccount(" + accountNumber + ")");
accountRepository.deleteByAccountNumber(accountNumber);
}
@CacheEvict(value = "accounts", allEntries = true)
public void clearAllCaches() {
System.out.println(" CLEARED all entries from 'accounts' cache");
}
}
package com.bank;
import com.bank.service.CachingAccountService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class CachingAnnotationDemo implements CommandLineRunner {
private final CachingAccountService service;
public CachingAnnotationDemo(CachingAccountService service) {
this.service = service;
}
@Override
public void run(String... args) {
System.out.println("@Cacheable (first call, cache miss):");
service.getAccount("SAV2001");
System.out.println("@Cacheable (second call, cache hit):");
service.getAccount("SAV2001");
System.out.println("@CachePut (always executes, updates cache):");
var account = service.getAccount("SAV2001");
service.updateAccount(account);
System.out.println("@CacheEvict (removes from cache):");
service.closeAccount("SAV2001");
System.out.println("@Cacheable (after eviction, cache miss again):");
// This would throw since account was deleted, but demonstrates the point
}
}
Expected output:
@Cacheable (first call, cache miss):
DB QUERY: getAccount(SAV2001)
@Cacheable (second call, cache hit):
@CachePut (always executes, updates cache):
DB UPDATE: updateAccount(SAV2001)
@CacheEvict (removes from cache):
DB DELETE: closeAccount(SAV2001)
@Cacheable (after eviction, cache miss again):
How do cache keys work?
By default, Spring generates the cache key from all method parameters. If the method has one parameter, that parameter is the key. If it has multiple parameters, Spring creates a SimpleKey from all of them. You can customize the key using SpEL (Spring Expression Language) in the key attribute.
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CacheKeyDemoService {
private final AccountRepository accountRepository;
public CacheKeyDemoService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
// Key = accountNumber (single param, used as key directly)
@Cacheable(value = "accounts", key = "#accountNumber")
public Account getByNumber(String accountNumber) {
System.out.println(" DB QUERY: getByNumber(" + accountNumber + ")");
return accountRepository.findByAccountNumber(accountNumber).orElseThrow();
}
// Key = composite of status + holderName
@Cacheable(value = "accountList", key = "#status + ':' + #holderName")
public List<Account> search(String status, String holderName) {
System.out.println(" DB QUERY: search(" + status + ", " + holderName + ")");
return accountRepository.findByStatusAndHolderName(status, holderName);
}
// Key = object field using SpEL
@Cacheable(value = "accounts", key = "#request.accountNumber()")
public Account getByRequest(AccountLookupRequest request) {
System.out.println(" DB QUERY: getByRequest(" + request.accountNumber() + ")");
return accountRepository.findByAccountNumber(request.accountNumber()).orElseThrow();
}
}
package com.bank.service;
// Java 25 record for the lookup request
public record AccountLookupRequest(String accountNumber, boolean includeTransactions) {}
package com.bank;
import com.bank.service.AccountLookupRequest;
import com.bank.service.CacheKeyDemoService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class CacheKeyDemo implements CommandLineRunner {
private final CacheKeyDemoService service;
public CacheKeyDemo(CacheKeyDemoService service) {
this.service = service;
}
@Override
public void run(String... args) {
System.out.println("Key = single param:");
service.getByNumber("SAV2001");
service.getByNumber("SAV2001"); // cache hit
System.out.println("Key = composite:");
service.search("ACTIVE", "Priya Sharma");
service.search("ACTIVE", "Priya Sharma"); // cache hit
service.search("ACTIVE", "Rajesh Kumar"); // cache miss (different key)
System.out.println("Key = record field:");
service.getByRequest(new AccountLookupRequest("SAV2001", true));
service.getByRequest(new AccountLookupRequest("SAV2001", false)); // cache hit (key is only accountNumber)
}
}
Expected output:
Key = single param:
DB QUERY: getByNumber(SAV2001)
Key = composite:
DB QUERY: search(ACTIVE, Priya Sharma)
DB QUERY: search(ACTIVE, Rajesh Kumar)
Key = record field:
DB QUERY: getByRequest(SAV2001)
How do you configure TTL (Time To Live) for cached entries?
Spring Cache abstraction does not have a built-in TTL property on @Cacheable. TTL is configured on the cache provider. For Caffeine (in-memory), you set it in application.properties. For Redis, you configure it through RedisCacheConfiguration.
# application.properties with Caffeine cache and TTL
spring.cache.type=caffeine
spring.cache.caffeine.spec=maximumSize=1000,expireAfterWrite=300s
package com.bank.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.time.Duration;
@Configuration
public class CaffeineCacheConfig {
@Bean
public CacheManager cacheManager() {
var manager = new CaffeineCacheManager();
manager.setCaffeine(Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(Duration.ofMinutes(5))
.recordStats());
System.out.println("Caffeine cache configured: maxSize=1000, TTL=5min");
return manager;
}
}
package com.bank.config;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import java.time.Duration;
import java.util.Map;
@Configuration
public class RedisCacheConfig {
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
// Default TTL for all caches
var defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.disableCachingNullValues();
// Per-cache TTL overrides
var cacheConfigs = Map.of(
"accounts", defaultConfig.entryTtl(Duration.ofMinutes(5)),
"balances", defaultConfig.entryTtl(Duration.ofMinutes(1)),
"exchangeRates", defaultConfig.entryTtl(Duration.ofSeconds(30))
);
System.out.println("Redis cache configured:");
cacheConfigs.forEach((name, config) ->
System.out.println(" " + name + ": TTL=" + config.getTtl()));
return RedisCacheManager.builder(factory)
.cacheDefaults(defaultConfig)
.withInitialCacheConfigurations(cacheConfigs)
.build();
}
}
Expected output:
Redis cache configured:
accounts: TTL=PT5M
balances: TTL=PT1M
exchangeRates: TTL=PT30S
Why does @Cacheable not work with self-invocation?
This is the same proxy bypass problem as @Transactional. Spring implements @Cacheable through an AOP proxy. When you call a @Cacheable method from within the same class using this.method(), the call goes directly to the real method, bypassing the proxy. The cache is never checked.
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class BrokenCacheService {
private final AccountRepository accountRepository;
public BrokenCacheService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
// WRONG: calling a @Cacheable method from within the same class
public BigDecimal getBalanceForDisplay(String accountNumber) {
// this.getAccount() bypasses the proxy -> cache is never checked
Account account = getAccount(accountNumber);
return account.getBalance();
}
@Cacheable(value = "accounts", key = "#accountNumber")
public Account getAccount(String accountNumber) {
System.out.println(" DB QUERY: getAccount(" + accountNumber + ")");
return accountRepository.findByAccountNumber(accountNumber).orElseThrow();
}
}
package com.bank;
import com.bank.service.BrokenCacheService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class SelfInvocationDemo implements CommandLineRunner {
private final BrokenCacheService service;
public SelfInvocationDemo(BrokenCacheService service) {
this.service = service;
}
@Override
public void run(String... args) {
System.out.println("Call 1 via getBalanceForDisplay (self-invocation):");
service.getBalanceForDisplay("SAV2001");
System.out.println("Call 2 via getBalanceForDisplay (self-invocation):");
service.getBalanceForDisplay("SAV2001");
// DB QUERY runs BOTH times because cache is bypassed
System.out.println("Call 3 via getAccount directly (through proxy):");
service.getAccount("SAV2001");
System.out.println("Call 4 via getAccount directly (cache hit):");
service.getAccount("SAV2001");
}
}
Expected output:
Call 1 via getBalanceForDisplay (self-invocation):
DB QUERY: getAccount(SAV2001)
Call 2 via getBalanceForDisplay (self-invocation):
DB QUERY: getAccount(SAV2001)
Call 3 via getAccount directly (through proxy):
DB QUERY: getAccount(SAV2001)
Call 4 via getAccount directly (cache hit):
The fix is to extract the cached method into a separate bean.
package com.bank.service;
import com.bank.model.Account;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class FixedDisplayService {
private final CachingAccountService cachingAccountService;
public FixedDisplayService(CachingAccountService cachingAccountService) {
this.cachingAccountService = cachingAccountService;
}
public BigDecimal getBalanceForDisplay(String accountNumber) {
// Calls through the proxy of CachingAccountService -> cache works
Account account = cachingAccountService.getAccount(accountNumber);
return account.getBalance();
}
}
Expected output (after fix):
Call 1 via getBalanceForDisplay:
DB QUERY: getAccount(SAV2001)
Call 2 via getBalanceForDisplay:
(no DB query, cache hit through CachingAccountService proxy)
What is a complete banking project with @Cacheable and Redis?
This project implements account balance caching for National Bank of India using Spring Boot 3.4 and Redis.
Project structure
account-cache-service/
├── pom.xml
└── src/
├── main/
│ ├── java/
│ │ └── com/
│ │ └── bank/
│ │ ├── AccountCacheApp.java
│ │ ├── config/
│ │ │ └── CacheConfig.java
│ │ ├── model/
│ │ │ └── Account.java
│ │ ├── dto/
│ │ │ └── BalanceResponse.java
│ │ ├── repository/
│ │ │ └── AccountRepository.java
│ │ └── service/
│ │ └── AccountService.java
│ └── resources/
│ └── application.properties
└── test/
└── java/
└── com/
└── bank/
└── service/
└── AccountServiceCacheTest.java
pom.xml
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>
syn-kw"><parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
syn-kw"></parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>account-cache-servicesyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>
syn-kw"><propertiessyn-kw">>
syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
syn-kw"></propertiessyn-kw">>
syn-kw"><dependenciessyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-data-jpasyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-data-redissyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-cachesyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>com.h2databasesyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>h2syn-kw"></artifactIdsyn-kw">>
syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>
BalanceResponse.java (Java 25 record)
package com.bank.dto;
import java.io.Serializable;
import java.math.BigDecimal;
public record BalanceResponse(
String accountNumber,
String holderName,
BigDecimal balance,
String source
) implements Serializable {}
AccountService.java
package com.bank.service;
import com.bank.dto.BalanceResponse;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
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;
import java.math.BigDecimal;
@Service
public class AccountService {
private final AccountRepository accountRepository;
public AccountService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
@Cacheable(value = "balances", key = "#accountNumber")
public BalanceResponse getBalance(String accountNumber) {
System.out.println(" DB QUERY: getBalance(" + accountNumber + ")");
Account account = accountRepository.findByAccountNumber(accountNumber)
.orElseThrow(() -> new RuntimeException("Account not found"));
return new BalanceResponse(
account.getAccountNumber(),
account.getHolderName(),
account.getBalance(),
"database"
);
}
@CacheEvict(value = "balances", key = "#accountNumber")
@Transactional
public void deposit(String accountNumber, BigDecimal amount) {
System.out.println(" DB UPDATE: deposit " + amount + " to " + accountNumber);
Account account = accountRepository.findByAccountNumber(accountNumber).orElseThrow();
account.setBalance(account.getBalance().add(amount));
accountRepository.save(account);
}
@Transactional
public Account openAccount(String accountNumber, String holderName, BigDecimal initialDeposit) {
return accountRepository.save(new Account(accountNumber, holderName, initialDeposit, "ACTIVE"));
}
}
AccountServiceCacheTest.java
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringBootTest
class AccountServiceCacheTest {
@Autowired private AccountService accountService;
@Autowired private AccountRepository accountRepository;
@Autowired private CacheManager cacheManager;
@BeforeEach
void setUp() {
cacheManager.getCache("balances").clear();
accountRepository.deleteAll();
accountRepository.save(new Account("SAV2001", "Priya Sharma", new BigDecimal("50000"), "ACTIVE"));
}
@Test
void getBalance_returnsCachedValueOnSecondCall() {
var first = accountService.getBalance("SAV2001");
var second = accountService.getBalance("SAV2001");
assertEquals(first.balance(), second.balance());
// DB QUERY printed only once (first call)
System.out.println("PASS: second call returned cached value");
}
@Test
void deposit_evictsCache() {
accountService.getBalance("SAV2001"); // populate cache
accountService.deposit("SAV2001", new BigDecimal("10000")); // evicts cache
var refreshed = accountService.getBalance("SAV2001"); // cache miss, DB query
assertEquals(new BigDecimal("60000"), refreshed.balance());
System.out.println("PASS: deposit evicted cache, new balance = " + refreshed.balance());
}
}
Expected output:
DB QUERY: getBalance(SAV2001)
PASS: second call returned cached value
DB QUERY: getBalance(SAV2001)
DB UPDATE: deposit 10000 to SAV2001
DB QUERY: getBalance(SAV2001)
PASS: deposit evicted cache, new balance = 60000
What are common mistakes with @Cacheable?
Wrong: caching mutable objects
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class MutableCacheBug {
private final AccountRepository accountRepository;
public MutableCacheBug(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
// WRONG: returns a mutable JPA entity that is cached
@Cacheable(value = "accounts", key = "#accountNumber")
public Account getAccount(String accountNumber) {
return accountRepository.findByAccountNumber(accountNumber).orElseThrow();
}
}
package com.bank;
import com.bank.service.MutableCacheBug;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
@Component
public class MutableCacheDemo implements CommandLineRunner {
private final MutableCacheBug service;
public MutableCacheDemo(MutableCacheBug service) {
this.service = service;
}
@Override
public void run(String... args) {
var account = service.getAccount("SAV2001");
System.out.println("Original balance: " + account.getBalance());
// Caller modifies the returned object (which is the cached reference!)
account.setBalance(BigDecimal.ZERO);
// Next caller gets the MODIFIED cached object
var account2 = service.getAccount("SAV2001");
System.out.println("Second call balance: " + account2.getBalance());
System.out.println("BUG: cached balance was corrupted by the first caller!");
}
}
Expected output:
Original balance: 50000
Second call balance: 0
BUG: cached balance was corrupted by the first caller!
Correct: cache an immutable record instead
package com.bank.service;
import com.bank.dto.BalanceResponse;
import com.bank.repository.AccountRepository;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class ImmutableCacheService {
private final AccountRepository accountRepository;
public ImmutableCacheService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
// CORRECT: return an immutable record
@Cacheable(value = "balances", key = "#accountNumber")
public BalanceResponse getBalance(String accountNumber) {
var account = accountRepository.findByAccountNumber(accountNumber).orElseThrow();
return new BalanceResponse(
account.getAccountNumber(),
account.getHolderName(),
account.getBalance(),
"database"
);
}
}
Expected output:
Original balance: 50000
Second call balance: 50000
Record is immutable. Cached value cannot be corrupted.
What should a senior or principal engineer know?
At the senior level, you should know when caching helps and when it hurts. Caching is effective for data that is read frequently and changes infrequently (exchange rates, account metadata, configuration). Caching is dangerous for data that changes often or where stale data causes business errors (account balances in a high-frequency trading system).
At the principal level, think about:
- Cache consistency: in a multi-instance deployment, each instance has its own local cache (ConcurrentMapCacheManager, Caffeine). Instance A updates the database and evicts its cache, but instance B still has the stale cached value. Use Redis as a shared cache to solve this.
- Cache stampede: when a popular key expires, hundreds of concurrent requests all miss the cache and hit the database simultaneously. Use @Cacheable with sync=true to let only one thread populate the cache while others wait.
- Cache warming: on application startup, pre-populate frequently accessed caches to avoid a flood of cache misses.
- Two-level caching: use a local Caffeine cache (L1) in front of a Redis cache (L2). L1 is faster but per-instance. L2 is shared but requires a network call.
- Monitoring: track cache hit rate, miss rate, and eviction count. A hit rate below 80% means the cache is not effective for that data.
package com.bank.service;
import com.bank.dto.BalanceResponse;
import com.bank.repository.AccountRepository;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class StampedeSafeService {
private final AccountRepository accountRepository;
public StampedeSafeService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
// sync=true prevents cache stampede: only one thread populates the cache
@Cacheable(value = "balances", key = "#accountNumber", sync = true)
public BalanceResponse getBalance(String accountNumber) {
System.out.println(" DB QUERY (only one thread enters): " + accountNumber);
var account = accountRepository.findByAccountNumber(accountNumber).orElseThrow();
return new BalanceResponse(
account.getAccountNumber(),
account.getHolderName(),
account.getBalance(),
"database"
);
}
}
Expected output (100 concurrent requests for SAV2001 after TTL expiry):
DB QUERY (only one thread enters): SAV2001
(99 other threads waited and got the cached result)
What are common interview follow-up questions?
- Can @Cacheable cache null values? (By default yes, which can cause issues. Use the unless attribute: @Cacheable(value="accounts", key="#id", unless="#result == null") to prevent caching nulls.)
- What happens if Redis is down? (The application throws an exception on cache operations. Use CacheErrorHandler to gracefully fall back to the database when the cache is unavailable.)
- Can you use @Cacheable on a private method? (No. Spring AOP creates proxies that intercept public method calls. Private methods are called directly and bypass the proxy.)
- How do you cache method results with no parameters? (The key defaults to SimpleKey.EMPTY. You can also set key = "'fixedKey'" for clarity.)
- What is the difference between @Cacheable and Spring Data Redis Template? (The @Cacheable abstraction works through annotations and is cache-provider agnostic. RedisTemplate gives you direct Redis operations: SET, GET, HSET, EXPIRE, pub/sub. Use @Cacheable for simple method caching, RedisTemplate for advanced Redis features.)
- Can you combine @Cacheable and @Transactional on the same method? (Yes, but the order matters. By default @Cacheable runs before @Transactional, so the cache check happens outside the transaction. This is usually the correct behavior.)
Visual Overview
@Cacheable Proxy Flow
=======================
┌──────────────────────┐
│ Controller calls │
│ service.getBalance() │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ CGLIB / JDK Proxy │
│ (CacheInterceptor) │
│ │
│ 1. Generate cache key│
│ key = "SAV2001" │
│ │
│ 2. Check cache │
│ cache.get(key) │
└──────────┬───────────┘
│
┌──────┴──────┐
│ │
HIT? MISS?
│ │
▼ ▼
┌────────┐ ┌──────────────────┐
│ Return │ │ Execute method │
│ cached │ │ (DB query) │
│ value │ │ │
└────────┘ │ Cache the result │
│ cache.put(key,v) │
│ │
│ Return result │
└──────────────────┘
Cache Lifecycle with @CacheEvict
=================================
getBalance("SAV2001") deposit("SAV2001", 10000) getBalance("SAV2001")
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ MISS │ │ EVICT │ │ MISS │
│ DB query │ │ DB update│ │ DB query │
│ Cache=50k│ │ Cache=-- │ │ Cache=60k│
└──────────┘ └──────────┘ └──────────┘
Key Takeaway
@Cacheable is Spring's declarative way to add caching to your service methods. You annotate a method, and Spring's AOP proxy intercepts calls to check the cache before executing the method. On a cache miss, the method runs and the result is stored. On a cache hit, the cached value is returned immediately without touching the database. Combined with @CachePut for updates and @CacheEvict for invalidation, you get a complete caching lifecycle.
The biggest trap is the self-invocation problem. Because @Cacheable relies on the same AOP proxy mechanism as @Transactional, calling a @Cacheable method from within the same class bypasses the proxy and the cache is never consulted. The fix is always the same: extract the cached method into a separate bean so the call goes through the proxy. The second trap is caching mutable objects. If you cache a JPA entity and a caller modifies it, the cached reference is corrupted. Use immutable Java records for cached return values.
In our National Bank of India account-cache-service, we cached balance lookups with a Redis backend and per-cache TTL configuration. Account balances were cached for 1 minute, exchange rates for 30 seconds. When a deposit occurred, @CacheEvict removed the stale balance, and the next lookup fetched the fresh value from the database. The test verified that the second call did not trigger a database query and that a deposit properly invalidated the cache.
At the senior level, understand that local caches (Caffeine, ConcurrentMap) are per-instance and cause inconsistency in multi-instance deployments. Use Redis as a shared cache. At the principal level, protect against cache stampedes with sync=true, implement two-level caching (Caffeine + Redis) for latency-sensitive services, and monitor hit rates to verify that caching is helping.
Remember one sentence: @Cacheable intercepts method calls through an AOP proxy, returning cached values on hits and populating the cache on misses, but it only works when the call goes through the proxy, not on self-invocation.
---