Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 119 ยท Spring Boot

Caching and Data with Redis

Use Redis from Spring Boot as a cache and data store, from how the protocol works to RedisTemplate and @Cacheable with TTL, plus serialization and common pitfalls.

The in-memory cache from Scheduling, Caching and Async Tasks lives inside one JVM. That is fast and simple, but it has two limits: every application instance has its own copy (so a change on one instance is invisible to the others), and the cache disappears whenever the application restarts. When you run several instances behind a load balancer, you want a cache they can share.

Redis is the most common answer. It is a server that keeps data in memory and answers simple commands over the network in well under a millisecond. It is far more than a key-value cache: it offers hashes, lists, sets, sorted sets and streams, supports expiration times on every key, and executes each command atomically. Teams use it for caches, login sessions, counters, rate limiters, leaderboards, queues and short-lived locks. This lesson explains how Redis works, runs a few real commands against a tiny server, and shows how Spring Boot connects to Redis through RedisTemplate and the cache abstraction.

What Redis stores

Every Redis entry has a key (a string) and a value of one of several types, each with its own commands:

Type What it holds Typical use Example commands
String Text, number or bytes Cached JSON, counters SET, GET, INCR
Hash Field-value pairs A small object, a session HSET, HGET, HGETALL
List Ordered values Simple queues, recent items LPUSH, RPOP, LRANGE
Set Unique values Tags, "who liked this" SADD, SISMEMBER
Sorted set Unique values with a score Leaderboards, delayed jobs ZADD, ZRANGE, ZRANK
Stream Append-only log Event processing XADD, XREADGROUP

Any key can get a time to live (TTL) with EXPIRE or SET ... EX. When it runs out, Redis deletes the key by itself, which is exactly what a cache needs. Because Redis runs commands one at a time on its main thread, INCR is atomic: a thousand clients incrementing one counter never lose an update, with no locks on your side.

Redis is not a replacement for your relational database. Data lives in RAM, so capacity is limited and you should treat the contents as rebuildable unless you have configured persistence and understand its guarantees.

The cache-aside pattern

The standard way to use Redis as a cache is cache-aside: the application checks the cache first and only goes to the database when the key is missing.

flowchart TD
  R["Request for book 42"] --> C{"Key books::42 in Redis?"}
  C -->|"hit"| H["Return cached value"]
  C -->|"miss"| D["Query the database"]
  D --> S["SET books::42 with TTL"]
  S --> H
  W["Book 42 is updated"] --> E["DEL books::42"]

Reads fill the cache on a miss; writes remove the entry so the next read loads fresh data.

Spring's @Cacheable implements exactly this, as you will see below.

The wire protocol

Redis speaks a very simple text-based protocol called RESP. A command is an array of bulk strings: *3 means three elements, $3 means "the next string has 3 bytes". Replies start with a type byte: + for a simple string, : for an integer, $ for a bulk string ($-1 means null), - for an error. Client libraries such as Lettuce (the default in Spring Boot) speak this language for you, but it is worth seeing once. The example below starts a miniature Redis-like server on a loopback socket, then talks to it with raw RESP bytes:

Java Talking RESP to a tiny Redis-like server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A real Redis server also supports pipelining (send many commands without waiting), pub/sub, transactions and scripts, but the framing is the same. Because the protocol is this simple, a round trip costs almost nothing; what costs time is the network, so avoid chatty code that makes hundreds of calls in a loop where one pipelined or batched call would do.

Connecting from Spring Boot

Add spring-boot-starter-data-redis. It brings Spring Data Redis and the Lettuce client, and auto-configures a connection factory from properties:

PROPERTIES
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.password=${REDIS_PASSWORD:}
spring.data.redis.timeout=2s
spring.data.redis.ssl.enabled=false

Never leave the timeout unset: a slow Redis must not freeze every request thread. Spring then provides two ready-made beans. StringRedisTemplate works with string keys and values and is the right default. RedisTemplate<Object, Object> is the generic one, where the serializers decide how objects become bytes.

Java
@Service
class VisitService {

    private final StringRedisTemplate redis;

    VisitService(StringRedisTemplate redis) { this.redis = redis; }

    long countVisit(String page) {
        String key = "visits:" + page;
        Long total = redis.opsForValue().increment(key);        // INCR, atomic
        return total == null ? 0 : total;
    }

    void rememberSession(String sessionId, String userId) {
        redis.opsForValue().set("session:" + sessionId, userId, Duration.ofMinutes(30));   // SET ... EX
    }

    void saveProfile(String userId, Map<String, String> fields) {
        redis.opsForHash().putAll("user:" + userId, fields);                               // HSET
        redis.expire("user:" + userId, Duration.ofHours(1));
    }

    void addScore(String player, double points) {
        redis.opsForZSet().incrementScore("leaderboard", player, points);                  // ZINCRBY
    }

    Set<String> topPlayers(int n) {
        return redis.opsForZSet().reverseRange("leaderboard", 0, n - 1);                   // ZREVRANGE
    }
}

The opsFor... methods are grouped by data type and map almost one-to-one to Redis commands, so the Redis documentation is also your Spring documentation. A fixed-window rate limiter is just INCR plus EXPIRE: increment rate:{user}:{minute}, set a 60-second TTL when the result is 1, and reject the request when the count exceeds the limit. If you need locks, leader election or complex scripts, a library such as Redisson adds ready-made, correct implementations.

Serialization and key design

A template converts keys and values to bytes with serializers. For RedisTemplate<Object, Object> the default is Java's built-in serialization, which is a bad choice: the bytes are unreadable in redis-cli, tied to your exact class version (a deploy that changes a field breaks old entries) and a security risk when you read untrusted data. Prefer plain strings or JSON:

Java
@Bean
RedisTemplate<String, Book> bookTemplate(RedisConnectionFactory factory) {
    var template = new RedisTemplate<String, Book>();
    template.setConnectionFactory(factory);
    template.setKeySerializer(RedisSerializer.string());
    template.setValueSerializer(RedisSerializer.json());     // JSON via Jackson
    return template;
}

The exact serializer class names changed with the Jackson upgrade in recent Spring Data Redis versions, so use the RedisSerializer.json() factory or check the reference for your version.

Name keys with a stable convention: app:entity:id, for example library:book:42. Prefixes make SCAN-based cleanup possible and keep several applications from colliding in one Redis instance. Never run KEYS * in production: it scans the whole keyspace on the single Redis thread and blocks everyone. Use SCAN with a pattern, or better, avoid needing it.

@Cacheable with Redis

The cache abstraction from the earlier lesson does not care which store sits behind it. Switching it to Redis takes a dependency, a property and @EnableCaching:

PROPERTIES
spring.cache.type=redis
spring.cache.redis.time-to-live=10m
spring.cache.redis.key-prefix=library::
spring.cache.redis.cache-null-values=false
Java
@Service
class BookService {

    private final BookRepository books;

    BookService(BookRepository books) { this.books = books; }

    @Cacheable(cacheNames = "books", key = "#id")
    public BookDto findById(long id) {
        return BookDto.from(books.findById(id).orElseThrow());     // runs only on a cache miss
    }

    @CacheEvict(cacheNames = "books", key = "#id")
    public void update(long id, BookUpdate update) {
        // change the entity; the cached copy is removed
    }
}

The entry is stored under a key like library::books::42, with a 10-minute TTL. Different caches often need different lifetimes (a price list for a minute, country names for a day), which you configure with a RedisCacheManager:

Java
@Bean
RedisCacheManagerBuilderCustomizer cacheTimeToLive() {
    return builder -> builder
            .withCacheConfiguration("books",
                    RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)).disableCachingNullValues())
            .withCacheConfiguration("countries",
                    RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1)));
}

Cache DTOs or records, not JPA entities: entities have lazy fields and proxies that do not serialize cleanly. The next example reproduces what that proxy-and-Redis combination does, using a map with expiry times and a virtual clock so the output is predictable. It stores books as JSON strings, like a real Redis cache with a JSON serializer:

Java Cache-aside with TTL, JSON values and eviction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Six lookups needed only four database reads: misses on first use, after expiry (t=61 s) and after the explicit eviction. This also shows the main design trade-off. A long TTL gives a better hit rate but allows stale data; evicting on every write gives freshness but requires that all write paths remember to do it.

Pitfalls and good practice

  • Stale data. Always combine a TTL with eviction on writes; the TTL is your safety net when an eviction is missed.
  • Stampede. When a popular key expires, many requests miss at once. Use @Cacheable(sync = true), add random jitter to TTLs, or refresh hot keys in the background.
  • Memory. Set maxmemory and an eviction policy (allkeys-lru suits a pure cache). Without one, Redis grows until the OS kills it, or starts refusing writes.
  • Big keys. A multi-megabyte value or a list with millions of entries blocks the single thread while it moves. Keep values small and split large collections.
  • Availability. A cache should be an optimization, not a hard dependency. Configure a CacheErrorHandler so that a Redis outage means slower responses instead of failed requests, and give every call a timeout.
  • Security. Never expose Redis to the internet. Require a password or ACL users, enable TLS between networks and keep it in a private network, as in Docker for Java Developers.
  • Observability. Track hit ratio, latency and memory in Actuator; a cache you do not measure is a guess.
  • Testing. Mock the cache in unit tests and run real Redis in integration tests with Testcontainers.

Redis can also push messages. Pub/sub (convertAndSend on a StringRedisTemplate, and a RedisMessageListenerContainer on the receiving side) broadcasts a message to every instance, which is a simple way to make WebSocket servers behind a load balancer see each other's events. Pub/sub does not store messages: a subscriber that is offline misses them, so use streams when delivery matters (see Messaging).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is an in-process cache (a map inside the application) a problem with three application instances?

    A shared cache such as Redis gives all instances one consistent view. In-process caches are still fine for data that rarely changes.
  2. 2. Why can several clients call INCR on the same Redis key at the same time without losing counts?

    Commands run sequentially on Redis's main thread, so a read-modify-write command such as INCR is atomic.
  3. 3. What does the cache-aside pattern do when the key is not in the cache?

    The application owns the logic; Redis only stores values. @Cacheable implements this for you.
  4. 4. Why should you avoid the default Java serialization for RedisTemplate values?

    Use string or JSON serializers so that values stay readable and survive deployments that change a class.
  5. 5. Why is running KEYS * on a production Redis a bad idea?

    Use SCAN, which iterates in small steps, or design key names so you never need to list everything.

Summary

  • Redis is an in-memory server for strings, hashes, lists, sets, sorted sets and streams, with per-key TTL and atomic commands; clients talk to it with the simple RESP protocol.
  • Use cache-aside: read the cache, load on a miss, store with a TTL, evict on writes.
  • Spring Boot's spring-boot-starter-data-redis provides StringRedisTemplate and RedisTemplate; prefer string or JSON serializers and consistent key prefixes.
  • spring.cache.type=redis plus @Cacheable and @CacheEvict caches method results; configure TTLs per cache and cache DTOs rather than entities.
  • Plan for stale data, stampedes, memory limits, big keys, outages, security and monitoring; use SCAN, never KEYS.

Next: Layered Architecture: Controllers, Services and Repositories shows where all these pieces belong in a well-structured application.