Redis in Spring Boot applications

Redis keeps data in memory and answers in well under a millisecond, which makes it the usual choice for caches, sessions, counters and short-lived locks. Spring Boot connects to it with almost no configuration, but the defaults decide how your objects are stored and what happens when Redis is down. This page runs those parts and shows the data-structure code for Spring Data Redis 4.

Contents

How Spring talks to Redis

Redis is a server that keeps keys and values in memory. A value is not just a string: it can be a hash, a list, a set, a sorted set or a stream, and each type has its own commands, such as HSET, LPUSH or ZADD. Redis executes commands one at a time on a single thread, so every command is atomic, and keys can expire on their own after a time to live. Data can be written to disk for restarts, but it must fit in memory, which is why Redis is mostly used for data that can be rebuilt: caches, sessions, rate-limit counters, leaderboards and locks.

Spring Data Redis stacks several layers on top of a client library:

The layers of Redis support in Spring Boot 4
LayerClassWhat it does
ClientLettuce 7 (default) or JedisSpeaks the Redis protocol over the network
Connection factoryLettuceConnectionFactoryCreates and shares connections, built from spring.data.redis.*
TemplateRedisTemplate, StringRedisTemplateCommands per data type, with serializers for keys and values
CacheRedisCacheManagerBacks @Cacheable with Redis, with a time to live
MessagingRedisMessageListenerContainerPublish/subscribe and stream consumers
Repositories@RedisHash, CrudRepositoryObjects stored as hashes, with secondary indexes

Adding spring-boot-starter-data-redis brings Spring Data Redis 4.1 and Lettuce, and Spring Boot auto-configures the connection factory, a RedisTemplate<Object, Object> and a StringRedisTemplate. With @EnableCaching, Redis also becomes the cache.

No Redis server is available where this page was built. The four programs shown running are the parts that work without one: the connection setup, the serializers, the cache configuration and the behaviour when Redis cannot be reached. The data-structure, lock and messaging examples are marked as not run; they were checked against the Spring Data Redis reference documentation and the Javadoc of the 4.1 jars.

Connecting, and what happens with no server

A single spring.data.redis.url property can carry the whole address. This program points it at a port where nothing listens, to show what is checked at start-up and what is not:

Java
package demo.redis.noserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

public class NoServer {

    @SpringBootApplication
    static class ShopApplication {
    }

    public static void main(String[] args) {
        // nothing listens on port 6390 on this machine
        try (var context = SpringApplication.run(ShopApplication.class,
                "--spring.main.banner-mode=off", "--logging.level.root=WARN",
                "--spring.data.redis.url=redis://shop:secret@localhost:6390/2",
                "--spring.data.redis.timeout=2s")) {
            System.out.println("Context started without contacting Redis");

            var factory = (LettuceConnectionFactory) context.getBean(RedisConnectionFactory.class);
            System.out.println("Client: Lettuce, host " + factory.getHostName()
                    + ", port " + factory.getPort() + ", database " + factory.getDatabase());
            System.out.println("Command timeout: " + factory.getClientConfiguration()
                    .getCommandTimeout());

            StringRedisTemplate redis = context.getBean(StringRedisTemplate.class);
            try {
                redis.opsForValue().set("greeting", "hello");
            } catch (RedisConnectionFailureException e) {
                System.out.println("First command: " + e.getClass().getSimpleName());
                System.out.println("  " + e.getMessage());
                Throwable root = e;
                while (root.getCause() != null) {
                    root = root.getCause();
                }
                System.out.println("  root cause: " + root.getClass().getSimpleName()
                        + ": " + root.getMessage());
            }
        }
    }
}
Output
Context started without contacting Redis
Client: Lettuce, host localhost, port 6390, database 2
Command timeout: PT2S
First command: RedisConnectionFailureException
  Unable to connect to Redis
  root cause: ConnectException: Connection refused
  • The application context started although no Redis server exists. Lettuce connects lazily, on the first command, so a Redis outage does not stop the application from starting.
  • The URL redis://shop:secret@localhost:6390/2 was split into user, password, host, port and database 2. Redis has 16 numbered databases by default; Redis Cluster supports only database 0.
  • spring.data.redis.timeout=2s became the command timeout. Without it, Lettuce waits 60 seconds for a reply, which is far too long for a cache that should answer in a millisecond.
  • The first command failed with Spring's RedisConnectionFailureException, "Unable to connect to Redis", caused by a plain ConnectException: Connection refused. Spring translates client exceptions into its DataAccessException hierarchy, so the code does not depend on Lettuce.

The separate properties work too: spring.data.redis.host, port, username, password, database and ssl.enabled. For high availability, spring.data.redis.sentinel.* configures Redis Sentinel and spring.data.redis.cluster.nodes a Redis Cluster. A Lettuce connection is thread-safe and shared, so a pool is rarely needed; spring.data.redis.lettuce.pool.enabled adds one, with commons-pool2, for blocking commands and transactions.

What actually gets stored: serializers

Redis stores bytes. Every Java key and value has to be turned into bytes by a RedisSerializer, and the choice decides whether other programs, and people with redis-cli, can read the data. The same product is written with each common serializer:

Java
import java.io.Serializable;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

public class Serializers {

    record Product(String sku, BigDecimal price) implements Serializable {
    }

    record Basket(String owner) {
    }

    static void show(String label, RedisSerializer<Object> serializer, Object value) {
        byte[] bytes = serializer.serialize(value);
        String text = new String(bytes, StandardCharsets.ISO_8859_1);
        boolean printable = text.chars().allMatch(c -> c >= 32 && c < 127);
        System.out.println(label + " (" + serializer.getClass().getSimpleName() + "): "
                + bytes.length + " bytes");
        System.out.println("  stored as: " + (printable ? text
                : HexFormat.of().formatHex(bytes, 0, 16) + "... (binary)"));
        System.out.println("  read back: " + serializer.deserialize(bytes));
    }

    public static void main(String[] args) {
        Product product = new Product("book-42", new BigDecimal("12.50"));

        show("java()", RedisSerializer.java(), product);
        show("json()", RedisSerializer.json(), product);

        JacksonJsonRedisSerializer<Product> typed = new JacksonJsonRedisSerializer<>(Product.class);
        byte[] bytes = typed.serialize(product);
        System.out.println("typed JSON (JacksonJsonRedisSerializer): " + bytes.length + " bytes");
        System.out.println("  stored as: " + new String(bytes, StandardCharsets.UTF_8));
        System.out.println("  read back: " + typed.deserialize(bytes));

        byte[] key = RedisSerializer.string().serialize("product:book-42");
        System.out.println("string() key: " + new String(key, StandardCharsets.UTF_8)
                + " (" + key.length + " bytes)");

        try {
            RedisSerializer.java().serialize(new Basket("ana"));
        } catch (SerializationException e) {
            System.out.println("java() on a class that is not Serializable: "
                    + e.getClass().getSimpleName());
            System.out.println("  " + e.getMessage());
        }
    }
}
Output
java() (JdkSerializationRedisSerializer): 398 bytes
  stored as: aced00057372001353657269616c697a... (binary)
  read back: Product[sku=book-42, price=12.50]
json() (GenericJacksonJsonRedisSerializer): 87 bytes
  stored as: {"@class":"Serializers$Product","sku":"book-42","price":["java.math.BigDecimal",12.50]}
  read back: Product[sku=book-42, price=12.50]
typed JSON (JacksonJsonRedisSerializer): 31 bytes
  stored as: {"sku":"book-42","price":12.50}
  read back: Product[sku=book-42, price=12.50]
string() key: product:book-42 (15 bytes)
java() on a class that is not Serializable: SerializationException
  Cannot serialize
  • java(), JDK serialization, wrote 398 bytes of binary that start with aced0005, the Java serialization header. Only a Java program with the same class on its classpath can read it, and renaming or moving the class breaks every stored value.
  • json() wrote 87 bytes of JSON with an @class property and the BigDecimal's type next to its value. That type information lets it read any object back without being told the class, at the cost of tying the data to Java class names.
  • JacksonJsonRedisSerializer for one type wrote 31 bytes, just the fields. It is the most compact and the easiest for other languages to read, but each serializer instance handles one type.
  • string() stored the key product:book-42 as its 15 UTF-8 bytes, readable as it is in redis-cli.
  • java() refused a record that does not implement Serializable with a SerializationException.

The trap is in the defaults. The auto-configured RedisTemplate<Object, Object> uses JDK serialization for keys too, so a key written as "product:book-42" is stored as binary and does not match the same key written by StringRedisTemplate. Use StringRedisTemplate for string data, or define your own RedisTemplate bean with string() keys and a JSON value serializer.

Spring Data Redis 4 uses Jackson 3 for JacksonJsonRedisSerializer and GenericJacksonJsonRedisSerializer, as the program does. The Jackson 2 classes, Jackson2JsonRedisSerializer and GenericJackson2JsonRedisSerializer, are still in the jar for applications that have not moved yet.

Redis as the Spring cache

With @EnableCaching and the Redis starter, Spring Boot creates a RedisCacheManager, and every @Cacheable method stores its results in Redis. This program configures defaults with properties and gives one cache its own settings, then prints what each cache would do:

Java
package demo.redis.cache;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HexFormat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.cache.autoconfigure.RedisCacheManagerBuilderCustomizer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;
import org.springframework.data.redis.serializer.RedisSerializer;

public class CacheSetup {

    @SpringBootApplication
    @EnableCaching
    static class ShopApplication {
        // per-cache settings on top of the spring.cache.redis.* defaults
        @Bean
        RedisCacheManagerBuilderCustomizer perCacheTtl() {
            return builder -> builder.withCacheConfiguration("prices",
                    RedisCacheConfiguration.defaultCacheConfig()
                            .entryTtl(Duration.ofSeconds(30))
                            .serializeValuesWith(SerializationPair.fromSerializer(
                                    RedisSerializer.json())));
        }
    }

    static void describe(CacheManager manager, String name) {
        RedisCacheConfiguration config = ((RedisCache) manager.getCache(name))
                .getCacheConfiguration();
        System.out.println("cache '" + name + "':");
        System.out.println("  key for 42      : " + config.getKeyPrefixFor(name) + "42");
        System.out.println("  time to live    : "
                + config.getTtlFunction().getTimeToLive("42", "value"));
        System.out.println("  caches nulls    : " + config.getAllowCacheNullValues());
        ByteBuffer written = config.getValueSerializationPair().write("hi");
        byte[] bytes = new byte[written.remaining()];
        written.get(bytes);
        System.out.println("  \"hi\" is stored as: " + (bytes[0] == '"'
                ? new String(bytes, StandardCharsets.UTF_8) + " (JSON)"
                : HexFormat.of().formatHex(bytes) + " (JDK serialization)"));
    }

    public static void main(String[] args) {
        try (var context = SpringApplication.run(ShopApplication.class,
                "--spring.main.banner-mode=off", "--logging.level.root=WARN",
                "--spring.cache.cache-names=orders,prices",
                "--spring.cache.redis.time-to-live=10m",
                "--spring.cache.redis.key-prefix=shop:",
                "--spring.cache.redis.cache-null-values=false")) {
            CacheManager manager = context.getBean(CacheManager.class);
            System.out.println("CacheManager: " + manager.getClass().getSimpleName());
            describe(manager, "orders");
            describe(manager, "prices");
        }
    }
}
Output
CacheManager: RedisCacheManager
cache 'orders':
  key for 42      : shop:orders::42
  time to live    : PT10M
  caches nulls    : false
  "hi" is stored as: aced00057400026869 (JDK serialization)
cache 'prices':
  key for 42      : prices::42
  time to live    : PT30S
  caches nulls    : true
  "hi" is stored as: "hi" (JSON)
  • The orders cache took the spring.cache.redis.* properties. Entry 42 would be stored under shop:orders::42: the key prefix, the cache name, two colons and the key. It expires after 10 minutes and never caches a null result.
  • Its values use JDK serialization: "hi" became aced0005.... That is the cache's default, the same as the template's.
  • The prices cache was configured by the customizer: 30 seconds and JSON, so "hi" was stored as "hi".
  • But prices also lost the property defaults: its key is prices::42 with no shop: prefix, and it caches null values again. A configuration built from RedisCacheConfiguration.defaultCacheConfig() starts from the library defaults, not from Spring Boot's properties.

Always set a time to live. Without one, cached entries never expire, and the cache keeps stale data until it is evicted for memory. A shared prefix such as shop: keeps the keys of several applications apart on one Redis server. The caching annotations themselves, @Cacheable, @CachePut and @CacheEvict, are explained on the Spring caching page.

When Redis is down

A cache should make the application faster, not less available. By default, though, a failed cache read is an exception like any other. This program calls a cached method with no Redis server, once with the default error handler and once with a handler that treats a failed read as a miss:

Java
package demo.redis.outage;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.SimpleCacheErrorHandler;
import org.springframework.stereotype.Service;

public class CacheOutage {

    @SpringBootApplication
    @EnableCaching
    static class ShopApplication implements CachingConfigurer {
        static boolean tolerant;

        @Override
        public CacheErrorHandler errorHandler() {
            if (!tolerant) {
                return new SimpleCacheErrorHandler();   // the default: rethrow
            }
            return new SimpleCacheErrorHandler() {
                @Override
                public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
                    System.out.println("  cache get failed for " + cache.getName() + "::" + key
                            + " (" + e.getClass().getSimpleName() + "), calling the method");
                }
            };
        }
    }

    @Service
    static class PriceService {
        @Cacheable("prices")
        public String price(String sku) {
            System.out.println("  loading the price of " + sku + " from the database");
            return sku + " costs 12.50";
        }
    }

    static void run(boolean tolerant) {
        ShopApplication.tolerant = tolerant;
        System.out.println(tolerant ? "Tolerant error handler:" : "Default error handler:");
        try (var context = SpringApplication.run(ShopApplication.class,
                "--spring.main.banner-mode=off", "--logging.level.root=OFF",
                "--spring.data.redis.port=6390")) {   // no Redis server on this port
            PriceService prices = context.getBean(PriceService.class);
            try {
                System.out.println("  result: " + prices.price("book-42"));
            } catch (RuntimeException e) {
                System.out.println("  call failed: " + e.getClass().getSimpleName()
                        + ": " + e.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        run(false);
        run(true);
    }
}
Output
Default error handler:
  call failed: RedisConnectionFailureException: Unable to connect to Redis
Tolerant error handler:
  cache get failed for prices::book-42 (RedisConnectionFailureException), calling the method
  loading the price of book-42 from the database
  result: book-42 costs 12.50
  • With the default SimpleCacheErrorHandler, the call failed with RedisConnectionFailureException. The price was available in the database all along, but the method never ran: a cache outage became an outage of every cached endpoint.
  • With the overridden handleCacheGetError, the failed read was reported and treated as a miss. The method loaded the price from the database, and the caller got book-42 costs 12.50.

Register the handler by implementing CachingConfigurer, as here. A production handler logs and counts the failures instead of printing them, and can override handleCachePutError, handleCacheEvictError and handleCacheClearError in the same way. Combine it with the short command timeout from the first program, or each request waits for the full timeout before falling back. An evict that fails is more dangerous than a read that fails, because the stale entry stays in Redis after Redis comes back.

Data structures with RedisTemplate (not run)

Beyond caching, Redis's data types solve common problems in one command each. StringRedisTemplate exposes them through opsForValue(), opsForHash(), opsForList(), opsForSet() and opsForZSet():

Java
@Service
public class ShopRedis {
    private final StringRedisTemplate redis;

    public ShopRedis(StringRedisTemplate redis) {
        this.redis = redis;
    }

    // a value with a time to live: SET session:abc ... EX 1800
    public void saveSession(String id, String json) {
        redis.opsForValue().set("session:" + id, json, Duration.ofMinutes(30));
    }

    // an atomic counter: INCR, safe with many application instances
    public long countView(String productId) {
        return redis.opsForValue().increment("views:" + productId);
    }

    // a hash: one key with named fields, read or updated one field at a time
    public void saveCart(String user, String sku, int quantity) {
        redis.opsForHash().put("cart:" + user, sku, String.valueOf(quantity));
    }

    // a sorted set: members ordered by score, here a leaderboard
    public Set<String> topSellers(int n) {
        return redis.opsForZSet().reverseRange("sales:2026-11", 0, n - 1);
    }
}
  • increment maps to INCR, which Redis runs atomically. Two application instances counting the same view can never lose an update, unlike a read, add and write in Java.
  • A hash is the right shape for an object whose fields change separately, such as a cart; updating one item does not rewrite the rest.
  • Name keys with a type and an id separated by colons, such as cart:ana. Tools group keys by those segments, and a consistent scheme makes them easy to find with SCAN.
  • Never call keys("*") in production code. KEYS walks every key while blocking the single command thread; redis.scan(ScanOptions.scanOptions().match("cart:*").build()) walks them in small batches.

Locks, transactions and scripts (not run)

A short lock that several application instances respect is built from one atomic command: set the key only if it does not exist, with an expiry so that a crashed holder cannot keep it forever:

Java
public boolean runOnce(String job, Runnable task) {
    String token = UUID.randomUUID().toString();
    Boolean acquired = redis.opsForValue()
            .setIfAbsent("lock:" + job, token, Duration.ofSeconds(30));   // SET NX EX
    if (!Boolean.TRUE.equals(acquired)) {
        return false;                                   // another instance holds the lock
    }
    try {
        task.run();
        return true;
    } finally {
        // delete only our own lock: compare and delete in one atomic Lua script
        redis.execute(RedisScript.of("""
                if redis.call('get', KEYS[1]) == ARGV[1]
                then return redis.call('del', KEYS[1]) else return 0 end""", Long.class),
                List.of("lock:" + job), token);
    }
}
  • The random token matters. If the task outlives the 30 seconds, another instance may take the lock, and a plain delete would then remove that instance's lock. The script deletes only when the stored token is still ours.
  • Such a lock is fine for avoiding duplicate work, such as a scheduled job on several instances. It is not safe for correctness under failover, because a Redis replica can lose a recent write. For that, use a database lock, or ShedLock for scheduled jobs.
  • Redis transactions, MULTI and EXEC, are available through redis.execute(SessionCallback). They queue commands and run them together, but there is no rollback, and a value cannot be read in the middle of one. A Lua script is usually the simpler way to make several steps atomic.
  • Pipelining, with redis.executePipelined(...), sends many commands without waiting for each reply, which cuts network round trips when loading thousands of keys.

Pub/sub and repositories (not run)

Redis can also deliver messages. A publisher calls convertAndSend, and a listener container delivers each message to every subscriber that is connected at that moment:

Java
@Bean
RedisMessageListenerContainer listeners(RedisConnectionFactory factory) {
    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    container.setConnectionFactory(factory);
    container.addMessageListener(
            (message, pattern) -> System.out.println("price changed: " + message),
            new ChannelTopic("price-changes"));
    return container;
}

// elsewhere: redis.convertAndSend("price-changes", "book-42");

Pub/sub keeps nothing: a subscriber that is down misses the message. That suits cache invalidation across instances, where a missed message only means a stale entry until its time to live runs out. For messages that must not be lost, use Redis Streams through StreamMessageListenerContainer, or a broker such as Kafka.

Spring Data repositories also work on Redis. An entity annotated with @RedisHash("carts") is stored as a hash, @Id forms its key, @Indexed fields get secondary indexes for findBy... methods, and @TimeToLive sets an expiry. Repositories keep their index sets in separate keys, which makes them heavier than direct template calls; they suit small, object-shaped data more than high-volume caching.

Running Redis in production

  • Memory limits: set maxmemory and an eviction policy on the server. For a pure cache, allkeys-lru evicts the least recently used keys; the default, noeviction, makes writes fail when memory is full.
  • Timeouts: set spring.data.redis.timeout and spring.data.redis.connect-timeout to values that match a cache, such as a few hundred milliseconds, not the client's 60-second default.
  • Big keys: a hash or list with millions of entries blocks the server while it is read or deleted. Split large structures, and delete big keys with UNLINK, which frees memory in the background.
  • Health checks: with Actuator, Spring Boot adds a Redis health indicator. Do not add it to the readiness group if the application can run without its cache, or a Redis outage takes every instance out of the load balancer.
  • Tests: run integration tests against a real Redis in a container with @ServiceConnection, as the Testcontainers page shows.

Choosing the right Redis feature

Spring Data Redis features for common needs
NeedFeature
Cache method results@Cacheable with RedisCacheManager, a time to live and a tolerant CacheErrorHandler
Strings, counters and values with an expiryStringRedisTemplate.opsForValue()
Objects whose fields change separatelyopsForHash()
Rankings and time-ordered dataopsForZSet()
Avoid duplicate work across instancessetIfAbsent with an expiry and a token
Several steps that must be atomicA Lua script with RedisScript
Notify all instances, losing messages is acceptablePub/sub with RedisMessageListenerContainer
Messages that must not be lostRedis Streams, or a broker
Values readable by other languagesstring() keys and JacksonJsonRedisSerializer values

Start with StringRedisTemplate and the cache abstraction, choose the serializer on purpose, and decide in advance what the application does when Redis is unavailable. For caching without a separate server, see the in-memory options on the Spring caching page.