Caching with Redis
Cache hot reads and choose expiry and invalidation strategies.
By Invicly Tech, , in Backend Java Development. About 11 minutes to read.
In short
Redis is an in-memory key-value store, often used as a cache in front of a database. Caching hot reads cuts latency and database load, but you must decide when cached data expires or is invalidated.
Explained simply
A database keeps data safely on disk, but every query costs time. Redis keeps data in memory (RAM), so reading a value usually takes well under a millisecond. Teams put Redis in front of the database as a cache: a short-term copy of answers that are asked for again and again, like a product page or a list of open rooms.
Think of a cache as a sticky note on your desk. Looking at the note is faster than walking to the filing cabinet. The danger is that the note can go out of date. So every cache needs two rules: when does a note expire on its own, and who throws it away when the real data changes?
Redis is more than a simple key and value store. A key can hold a string, a hash (a small map of fields), a list, a set, a sorted set (a set ordered by a score, great for leaderboards) or a stream. You talk to it with short commands such as SET, GET, EXPIRE and DEL.
In Spring Boot you rarely type those commands yourself. You add the Redis starter, turn on caching, and put @Cacheable on a method. Spring then checks Redis before running the method and saves the result afterwards. Your job is to pick what to cache, for how long, and when to remove it.
Press Play on a diagram to walk through it one step at a time.
- App to Redis: GET product:421GET product:42
- Redis to App: miss2miss
- App to Database: SELECT product 423SELECT product 42
- Database to App: row4row
- App to Redis: SET product:42 with 10 min TTL5SET product:42 with 10 min TTL
- App to Redis: next request: GET product:426next request: GET product:42
- Redis to App: hit, no database call7hit, no database call
- @CacheEvict after the update
- Next read reloads from the database
- Safest default
- One extra miss per change
- @CachePut stores the new value
- No miss after a change
- Risky if the transaction rolls back
- Method always runs
- No eviction code at all
- Data can be stale until expiry
- Fine for slow-changing data
- Pick a short TTL
In depth
Core data types and the commands behind them
Each Redis key has exactly one type, and each type has its own commands. Strings hold text, numbers or serialized JSON: SET page:home "..." EX 600 stores a value that expires in 600 seconds, and INCR views:42 adds one atomically, which makes simple counters and rate limiters safe under load. Hashes store fields inside one key (HSET user:7 name Ana plan pro), so you can read or change one field without rewriting the whole object.
Lists (LPUSH, RPOP) work as simple queues. Sets (SADD, SISMEMBER) keep unique members, like the tags on a post. Sorted sets (ZADD, ZRANGE with REV) keep members ordered by a score, which is how leaderboards and "top 10" lists are built. Most commands on one key run in O(1) or O(log n) time, but commands like KEYS * scan everything and can freeze a busy server.
- TTL key shows seconds left; -1 means no expiry, -2 means the key is gone
- Use SCAN instead of KEYS in production
- Name keys with colons: app:product:42
- Redis runs commands one at a time, so each command is atomic
How Spring caching talks to Redis
@EnableCaching makes Spring wrap your beans in a proxy. When a caller invokes a @Cacheable method, the proxy builds a key (by default from the method arguments), asks the cache, and only calls the real method on a miss. With the Redis cache manager the stored key looks like products::42: the cache name, two colons, then the key.
By default the value is stored with Java serialization, which is fragile when classes change and unreadable in redis-cli. Most teams configure a JSON serializer such as GenericJackson2JsonRedisSerializer in a RedisCacheConfiguration bean. That bean is also where you set a TTL per cache, so product data can live 10 minutes while exchange rates live 30 seconds.
Because it is a proxy, a call from one method to another inside the same class skips the cache. Put cached methods on a separate bean when this matters.
- 1Caller invokes find(42)
The call goes to the Spring proxy, not the bean
- 2Build the key
Cache name plus key, e.g. products::42
- 3Ask Redis
GET on the full key
- 4Hit: return it
The method body never runs
- 5Miss: run method
Query the database, then SET with the TTL
TTLs and what happens when memory is full
A TTL (time to live) is a safety net: even if you forget to evict a key, it disappears on its own. Pick it from how stale the data may be. A product description can be 10 minutes old; a bank balance should not be cached at all.
Redis also needs a rule for a full memory. You set a limit with maxmemory and choose a policy with maxmemory-policy. The default, noeviction, refuses new writes with an error. For a pure cache, allkeys-lru (drop the least recently used keys) or allkeys-lfu (drop the least frequently used) is the usual choice. The volatile-* variants only remove keys that have a TTL, which suits a Redis that holds both cache data and data you must keep.
If many hot keys expire at the same second, the database gets a burst of misses. Add a little random jitter to TTLs to spread them out.
- noeviction: writes fail when full (default)
- allkeys-lru / allkeys-lfu: typical for caches
- volatile-ttl: evict keys closest to expiry first
- INFO memory shows used_memory and the policy in use
Keeping the cache correct on writes
There are three common write strategies. Evict on write: after updating the database, delete the cached key (@CacheEvict) so the next read reloads fresh data. Update on write: put the new value straight into the cache (@CachePut), which avoids one miss but risks caching a value from a transaction that later rolls back. Expiry only: rely on a short TTL and accept a little staleness.
Evict on write is the safest default. Do it after the database commit, not before, or a reader can reload the old row into the cache between your eviction and your commit. Spring helps here: building the cache manager with transactionAware() delays puts and evictions until the surrounding transaction commits.
For list caches, such as all products in a category, one change can affect many keys. @CacheEvict(allEntries = true) clears a whole cache, which is simple but heavy, so keep such caches small.
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Run Redis and learn core data types~1h
- 2Enable Spring caching with @Cacheable~1h
- 3Set TTLs and eviction policies~1h
- 4Invalidate caches on writes~1h
Key points
- @Cacheable returns the cached value if present, otherwise runs the method and stores it.
- @CacheEvict or @CachePut keep the cache consistent when data changes.
- Always set a TTL so stale entries eventually disappear.
- Cache data that is read often and changes rarely.
Key terms
Tap a card to flip it. 0/5 known
Examples
@EnableCaching
@SpringBootApplication
class App {}
@Service
class ProductService {
@Cacheable(value = "products", key = "#id")
public ProductDto find(Long id) { return repo.findById(id).map(mapper::toDto).orElseThrow(); }
@CacheEvict(value = "products", key = "#dto.id()")
public ProductDto update(ProductDto dto) { return mapper.toDto(repo.save(mapper.toEntity(dto))); }
}
// application.yml: spring.cache.redis.time-to-live: 10mTry the data types in redis-cli
Start Redis in Docker, open redis-cli inside the container, and try a string with a TTL, an atomic counter, a hash and a sorted set. Watch the TTL count down, and notice that INCR works on a value stored as text because Redis treats numeric strings as numbers.
docker run -d --name redis -p 6379:6379 redis:7
docker exec -it redis redis-cli
SET product:42 '{"name":"Mug"}' EX 600
TTL product:42 # (integer) 600, then counting down
INCR views:42 # (integer) 1
HSET user:7 name Ana plan pro
HGET user:7 plan # "pro"
ZADD scores 120 ana 95 bob
ZRANGE scores 0 -1 REV WITHSCORESPer-cache TTLs and JSON values in Spring Boot
The product cache should live 10 minutes and the rates cache 30 seconds, and values should be readable JSON. Step 1: add spring-boot-starter-data-redis and spring-boot-starter-cache, and set spring.data.redis.host. Step 2: define a default RedisCacheConfiguration with a JSON serializer. Step 3: give individual caches their own TTL with a builder customizer. Step 4: check with redis-cli GET "products::42".
@Configuration
@EnableCaching
class CacheConfig {
@Bean
RedisCacheConfiguration cacheDefaults() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
}
@Bean
RedisCacheManagerBuilderCustomizer perCacheTtl(RedisCacheConfiguration base) {
return b -> b.withCacheConfiguration("rates", base.entryTtl(Duration.ofSeconds(30)));
}
}Quick reference
- Default Redis port is 6379; check a server with redis-cli PING (answers PONG)
- SET key value EX 600 stores a value with a 10 minute TTL
- Spring Redis cache keys look like cacheName::key, for example products::42
- spring.cache.redis.time-to-live=10m sets one TTL for all caches
- maxmemory-policy allkeys-lru is the usual choice for a cache-only Redis
- Never run KEYS * on a busy server; use SCAN with a MATCH pattern
- @CacheEvict(allEntries = true) clears a whole cache
- Do not cache per-user data under a key that ignores the user
Common mistakes
- Caching without TTL or eviction, serving stale data forever.
- Caching per-user data under a shared key.
- Calling a @Cacheable method from the same class, bypassing the proxy.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
In redis-cli, store a session value that expires after 30 seconds, check its TTL, wait, and prove it is gone.
- Exercise 2medium
Add @Cacheable to a findById method and prove with logs that the second call does not hit the database.
- Exercise 3hard
Make updates evict the cache only after the transaction commits, and write a test that fails if an update is followed by a stale read.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is Redis a database or a cache?
- It can be both. It keeps data in memory but can also save it to disk with snapshots (RDB) or an append-only file (AOF). Most backends use it as a cache, a session store or a rate limiter.
- What is Valkey?
- Valkey is an open-source fork of Redis started in 2024 after Redis changed its license. It speaks the same protocol, so Spring Data Redis and redis-cli work with it.
- What should I cache first?
- Measure first. Cache the endpoint that is read most often and changes rarely, then compare latency and database load before and after.
- Should I cache JPA entities directly?
- Usually no. Cache small DTOs instead. Entities can carry lazy-loaded relations that fail to serialize or pull in far more data than you meant.