00:00

Redis Tutorial: Data Types, Persistence and Spring Boot Caching

Last updated:

Redis is an in-memory data store that keeps data in RAM and answers most requests in well under a millisecond. Java teams use it as a cache in front of a database, a store for user sessions and shopping carts, a counter for rate limits, and a lightweight message channel. Because it is so fast and simple to run, Redis is one of the most common building blocks in modern backend systems.

This Redis tutorial explains how Redis works, its core data types and commands, expiration, transactions, Pub/Sub and Streams, persistence, eviction and high availability. It then builds a complete Spring Boot 4 cache-aside example with Spring Data Redis and tests it against a real Redis container. Every redis-cli reply and every log line on this page comes from running the examples on Redis 8.10 and Spring Boot 4.1.

1. What Is Redis?

Redis (short for REmote DIctionary Server) is a key-value store: you save a value under a name, called a key, and read it back by that name. Unlike a simple map, the value can be a rich data structure such as a hash, a list, a set or a sorted set, and Redis gives you commands that work on those structures directly on the server.

Three ideas explain why Redis is popular:

  • Memory first: the whole dataset lives in RAM, so reads and writes avoid disk access. Persistence to disk is optional.
  • Data structures as a service: you increment a counter, push to a list or update a leaderboard with one command, instead of reading, changing and writing a value in your application.
  • Simple operations: one small server process, a text-based protocol and clients for every language.

Redis is usually not the main database. It sits next to a durable database such as MySQL, PostgreSQL or MongoDB and makes the hot paths faster. If you are new to databases, start with the Database Tutorial and the overview of NoSQL databases.

Version note: This page targets Redis Open Source 8.10 (8.10.3 was used for testing), Spring Boot 4.1, Spring Data Redis 4.1 and Java 21. Redis 8 is available under a choice of RSALv2, SSPLv1 or AGPLv3; Redis 7.4 to 7.8 were RSALv2/SSPLv1 only, and 7.2 and earlier were BSD-licensed. Valkey, a Linux Foundation fork of Redis 7.2.4, is a BSD-licensed alternative that supports the same core commands.

2. Redis vs a Relational Database

Redis and a relational database solve different problems. The table shows where each one fits.

AspectRedisRelational database (MySQL, PostgreSQL)
Where data livesRAM, with optional snapshots or a log on diskDisk, with a memory cache for hot pages
Data modelKeys with typed values (strings, hashes, lists, sets, sorted sets, streams)Tables with rows, columns, keys and constraints
QueriesLook up by key; commands per data type; no joinsSQL with joins, filters, aggregation
Typical latencySub-millisecondMilliseconds
DurabilityConfigurable; some recent writes can be lostCommitted transactions survive crashes
TransactionsMULTI/EXEC without rollback; Lua scriptsFull ACID transactions with rollback
Best forCaching, sessions, counters, leaderboards, rate limits, queuesSystem of record: orders, customers, payments

3. How Redis Works Internally

A client opens a TCP connection to port 6379 and sends commands such as GET product:1001. Inside the server, an event loop on the main thread picks up ready requests and runs them one after another against the in-memory dataset.

How a Redis server handles client requests Several clients send commands over TCP. Network I/O reads and parses the requests, on the main thread or on optional I/O threads. The main thread runs one command at a time against the dataset in memory. Background work such as RDB snapshots, AOF fsync and lazy freeing runs outside the main thread. Spring Boot app Worker service redis-cli clients (TCP 6379) Redis server process Network I/Oread + parse,write replies(io-threads opt.) Main threadevent loop: runs onecommand at a time Datasetin RAM Background work (does not block commands) RDB snapshot (fork) AOF fsync Lazy free (UNLINK)
Figure 1: Commands execute one at a time on the main thread, so each command is atomic. I/O threads and background tasks only take work off that thread.
  • Command execution is single-threaded. Only one command runs at a time, so a single command such as INCR is always atomic: no other client can see a half-finished change.
  • I/O can be multi-threaded. Since Redis 6, the io-threads setting lets extra threads read requests and write replies. It is off by default (io-threads 1).
  • Background work runs elsewhere. RDB snapshots run in a forked child process, and background threads handle AOF fsync and lazy freeing of large deleted keys (UNLINK).
  • Slow commands block everyone. Because commands share one thread, a command that scans millions of keys delays every other client. This is why KEYS * is dangerous in production.

4. Installing Redis with Docker

The quickest way to run Redis on your machine is the official redis image on Docker Hub. The first command starts a throwaway development server:

Console
# Start Redis 8.10 locally (development only: no password, port bound to localhost)
docker run -d --name redis-dev -p 127.0.0.1:6379:6379 redis:8.10

# Open the Redis command-line client inside the container
docker exec -it redis-dev redis-cli

Check that the server answers. redis-cli shows a prompt with the host and port, and PING replies PONG:

redis-cli
127.0.0.1:6379> PING
PONG

For the Spring Boot example later, use Docker Compose with a password, append-only persistence and a named volume. The port is bound to 127.0.0.1 so that Redis is not reachable from other machines:

compose.yaml
services:
  redis:
    image: redis:8.10
    container_name: shop-redis
    command: ["redis-server", "--requirepass", "${REDIS_PASSWORD}", "--appendonly", "yes"]
    ports:
      - "127.0.0.1:6379:6379"
    volumes:
      - redis-data:/data

volumes:
  redis-data:
Console
export REDIS_PASSWORD='choose-a-long-random-password'
docker compose up -d
docker exec -it shop-redis redis-cli
redis-cli
127.0.0.1:6379> PING
(error) NOAUTH Authentication required.
127.0.0.1:6379> AUTH choose-a-long-random-password
OK
127.0.0.1:6379> PING
PONG

5. Keys, TTL and Expiration

5.1 Key Naming Convention

Redis has no tables, so the key name carries the structure. This page uses one convention everywhere: object type, then the id, separated by colons. Owners come before the id when a key belongs to someone.

KeyTypeHolds
product:1001StringCached JSON of product 1001
stock:product:2002StringStock counter for product 2002
cart:user:42HashShopping cart of user 42 (product → quantity)
session:7f3a9cStringLogin session with id 7f3a9c
recent:user:42ListProducts user 42 viewed recently
leaderboard:weeklySorted setWeekly player scores
orders:eventsStreamOrder events for other services

5.2 Setting a TTL

A TTL (time to live) tells Redis to delete a key automatically after a number of seconds. Set it in the same command with EX (seconds) or PX (milliseconds). TTL returns the seconds left, -1 when the key has no expiry and -2 when the key does not exist.

redis-cli
127.0.0.1:6379> SET session:7f3a9c '{"userId":42,"role":"customer"}' EX 1800
OK
127.0.0.1:6379> TTL session:7f3a9c
(integer) 1800
127.0.0.1:6379> SET session:7f3a9c '{"userId":42,"role":"admin"}'
OK
127.0.0.1:6379> TTL session:7f3a9c
(integer) -1
127.0.0.1:6379> TTL session:missing
(integer) -2

Notice the trap: a plain SET on an existing key removes its TTL. Add KEEPTTL when you want to change the value but keep the remaining lifetime:

redis-cli
127.0.0.1:6379> SET session:7f3a9c '{"userId":42,"role":"customer"}' EX 1800
OK
127.0.0.1:6379> SET session:7f3a9c '{"userId":42,"role":"admin"}' KEEPTTL
OK
127.0.0.1:6379> TTL session:7f3a9c
(integer) 1800

5.3 How Expired Keys Are Removed

Redis removes expired keys in two ways. Lazy expiration checks a key's TTL whenever a client touches it, and deletes it if it has expired. Active expiration runs in the background (10 times per second by default, the hz setting), samples keys that have a TTL and deletes the expired ones. Together they keep memory free without scanning every key. An expired key is never returned to a client, even if it has not been physically deleted yet.

5.4 Finding Keys with SCAN

KEYS pattern walks the whole keyspace in one blocking call, so never run it on a production server. Use SCAN, which returns a cursor and a small batch per call. When the returned cursor is "0", the scan is complete:

redis-cli
127.0.0.1:6379> SCAN 0 MATCH product:* COUNT 100
1) "0"
2) 1) "product:1001"

With many keys, call SCAN again with the returned cursor until it comes back as "0".

6. Redis Data Types

Each key has exactly one type. Commands are grouped by type, and using the wrong one returns a WRONGTYPE error instead of corrupting data.

6.1 Strings and Counters

A string holds text, JSON, numbers or binary data up to 512 MB. It is the type behind most caches. Numeric strings support atomic counters with INCR, INCRBY and DECRBY, so two clients can never lose each other's updates.

redis-cli
127.0.0.1:6379> SET product:1001 '{"id":1001,"name":"Wireless Mouse","price":799.00,"stock":25}' EX 600
OK
127.0.0.1:6379> GET product:1001
"{\"id\":1001,\"name\":\"Wireless Mouse\",\"price\":799.00,\"stock\":25}"
127.0.0.1:6379> GET product:9999
(nil)
127.0.0.1:6379> SET stock:product:2002 12
OK
127.0.0.1:6379> DECRBY stock:product:2002 2
(integer) 10
127.0.0.1:6379> INCR views:product:1001
(integer) 1

6.2 Hashes

A hash stores field-value pairs under one key, like a small map. It is ideal for a shopping cart, where each field is a product and each value a quantity. You can change one field without rewriting the whole object.

redis-cli
127.0.0.1:6379> HSET cart:user:42 product:1001 2 product:2002 1
(integer) 2
127.0.0.1:6379> HINCRBY cart:user:42 product:1001 1
(integer) 3
127.0.0.1:6379> HGETALL cart:user:42
1) "product:1001"
2) "3"
3) "product:2002"
4) "1"
127.0.0.1:6379> HDEL cart:user:42 product:2002
(integer) 1
127.0.0.1:6379> EXPIRE cart:user:42 604800
(integer) 1

The last command keeps an abandoned cart for seven days (604,800 seconds).

6.3 Lists

A list is an ordered sequence that is fast to push and pop at both ends. Combined with LTRIM, it keeps a fixed-size "recently viewed" list:

redis-cli
127.0.0.1:6379> LPUSH recent:user:42 product:1001
(integer) 1
127.0.0.1:6379> LPUSH recent:user:42 product:2002
(integer) 2
127.0.0.1:6379> LPUSH recent:user:42 product:3003
(integer) 3
127.0.0.1:6379> LTRIM recent:user:42 0 9
OK
127.0.0.1:6379> LRANGE recent:user:42 0 -1
1) "product:3003"
2) "product:2002"
3) "product:1001"

6.4 Sets

A set holds unique, unordered strings. Adding a member that already exists does nothing, which makes sets perfect for tags, unique visitors or "users who liked this".

redis-cli
127.0.0.1:6379> SADD tags:product:1001 wireless mouse office
(integer) 3
127.0.0.1:6379> SADD tags:product:1001 mouse
(integer) 0
127.0.0.1:6379> SISMEMBER tags:product:1001 office
(integer) 1
127.0.0.1:6379> SCARD tags:product:1001
(integer) 3

6.5 Sorted Sets

A sorted set is a set where every member has a numeric score, and members are always kept in score order. It powers leaderboards, priority queues and "top N" lists:

redis-cli
127.0.0.1:6379> ZADD leaderboard:weekly 1500 alice 2300 bob 1800 chen
(integer) 3
127.0.0.1:6379> ZINCRBY leaderboard:weekly 600 alice
"2100"
127.0.0.1:6379> ZRANGE leaderboard:weekly 0 2 REV WITHSCORES
1) "bob"
2) "2300"
3) "alice"
4) "2100"
5) "chen"
6) "1800"
127.0.0.1:6379> ZREVRANK leaderboard:weekly chen
(integer) 2

ZREVRANK is zero-based, so 2 means chen is third.

6.6 Streams

A stream is an append-only log of entries, each with an id and field-value pairs. Consumer groups let several workers share the entries and acknowledge each one with XACK. Section 8 compares streams with Pub/Sub.

redis-cli
127.0.0.1:6379> XGROUP CREATE orders:events shipping $ MKSTREAM
OK
127.0.0.1:6379> XADD orders:events * orderId 5001 status PLACED
"1793696718212-0"
127.0.0.1:6379> XREADGROUP GROUP shipping worker-1 COUNT 10 STREAMS orders:events >
1) 1) "orders:events"
   2) 1) 1) "1793696718212-0"
         2) 1) "orderId"
            2) "5001"
            3) "status"
            4) "PLACED"
127.0.0.1:6379> XACK orders:events shipping 1793696718212-0
(integer) 1

The entry id is generated from the server clock, so yours will differ.

6.7 Other Data Types

TypeUse it for
JSONStoring and updating nested JSON documents by path (built into Redis 8)
BitmapsDaily active users or feature flags as one bit per user id
HyperLogLogApproximate unique counts (for example, unique visitors) in about 12 KB
GeospatialFinding stores or drivers within a radius
Time series, Bloom filters, vector setsMetrics, "have I seen this?" checks and similarity search (built into Redis 8)
Version note: Before Redis 8, JSON, time series, probabilistic types and the query engine came as separate modules (Redis Stack). Redis Open Source 8 ships them in the main distribution.

7. Atomic Operations, Transactions and Lua

7.1 Single Commands Are Atomic

Every single command runs to completion before the next one starts. SET key value NX EX 30 sets the key only if it does not exist, with a TTL, in one atomic step. That makes it a simple lock: the second worker gets (nil).

redis-cli
127.0.0.1:6379> SET lock:order:5001 worker-1 NX EX 30
OK
127.0.0.1:6379> SET lock:order:5001 worker-2 NX EX 30
(nil)

7.2 MULTI/EXEC Transactions

MULTI starts a transaction; commands are queued and then run together, without other clients' commands in between, when you call EXEC. The important difference from a SQL database: there is no rollback. If one queued command fails at run time, the others still take effect.

redis-cli
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> DECRBY stock:product:2002 1
QUEUED
127.0.0.1:6379(TX)> INCR product:1001
QUEUED
127.0.0.1:6379(TX)> EXEC
1) (integer) 9
2) (error) ERR value is not an integer or out of range
127.0.0.1:6379> GET stock:product:2002
"9"

INCR failed because product:1001 holds JSON, yet the stock was still decremented. To protect against concurrent changes, call WATCH stock:product:2002 before MULTI: if another client changes the watched key before EXEC, the transaction is cancelled and EXEC returns (nil), so you can retry. This is optimistic locking.

7.3 Lua Scripts and Functions

When logic needs several commands plus a decision, send it as a Lua script with EVAL. The whole script runs atomically. This fixed-window rate limiter counts requests for user 42 and starts a 60-second window on the first one:

redis-cli
127.0.0.1:6379> EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end return n" 1 rate:user:42 60
(integer) 1
127.0.0.1:6379> EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end return n" 1 rate:user:42 60
(integer) 2
127.0.0.1:6379> TTL rate:user:42
(integer) 60

Your application rejects the request when the returned count passes its limit. Since Redis 7, you can also register reusable server-side functions with FUNCTION LOAD and call them with FCALL; they run atomically too. The rate limiting pattern page compares fixed windows with token buckets and sliding windows.

8. Redis Pub/Sub vs Streams

Both let one service send messages to others, but they make very different promises.

Pub/SubStreams
StorageNone: messages are pushed and forgottenEntries are stored in the stream until trimmed
Offline consumersMiss every message sent while disconnectedRead what they missed when they come back
Delivery guaranteeAt most onceAt least once with consumer groups and XACK
Load sharingEvery subscriber gets every messageConsumer groups split entries between workers
Good forLive notifications, cache invalidation signalsOrder events, background jobs, audit logs

With Pub/Sub, PUBLISH returns the number of subscribers that received the message. With nobody listening, the message is simply lost:

redis-cli
127.0.0.1:6379> PUBLISH price-updates product:1001
(integer) 0

A connected subscriber sees the message as a three-part reply:

redis-cli
127.0.0.1:6379> SUBSCRIBE price-updates
1) "subscribe"
2) "price-updates"
3) (integer) 1
1) "message"
2) "price-updates"
3) "product:1001"

For high-volume event streaming with long retention and replay across many services, a dedicated platform such as Apache Kafka is usually a better fit than Redis Streams.

9. RDB vs AOF Persistence

Redis keeps data in memory, but it can also write it to disk so that a restart does not start empty. There are two mechanisms, and you can use both together.

  • RDB (Redis Database file): a compact point-in-time snapshot of the whole dataset, written by a forked child process to dump.rdb.
  • AOF (Append Only File): a log of every write command. On restart, Redis replays the log to rebuild the data.
RDB snapshots compared with the AOF log Writes arrive continuously. RDB saves a full snapshot only at intervals, so a crash loses every write made since the last snapshot. AOF appends every write to a log and, with appendfsync everysec, flushes it to disk once per second, so a crash loses about one second of writes at most. Writes RDB AOF snapshot snapshot lost on crash:writes since snapshot every write appended to appendonly.aof, fsync once per second ≤ ~1 s lost crash
Figure 2: RDB trades durability for compact, fast-loading snapshots. AOF with appendfsync everysec narrows the loss window to about one second.
RDBAOF
Default in Redis 8.10On: save 3600 1 300 100 60 10000Off: appendonly no
What a crash can loseEvery write since the last snapshot (up to minutes)About one second with appendfsync everysec; nothing acknowledged with always, at a large speed cost
File sizeSmall, compressedLarger; rewritten in the background to stay compact
Restart speedFast to loadSlower for big logs (an RDB preamble helps)
Best forBackups and disaster recovery copiesData you cannot easily rebuild

The save 3600 1 300 100 60 10000 rule means: snapshot after 3600 seconds if at least 1 key changed, after 300 seconds if 100 changed, or after 60 seconds if 10,000 changed. A typical setup for data you care about enables both:

redis.conf
# Snapshots for backups
save 3600 1 300 100 60 10000

# Append-only log for durability: lose about one second at most
appendonly yes
appendfsync everysec

If Redis is only a cache that can be rebuilt from the database, you can turn persistence off (save "" and appendonly no) for the lowest overhead.

10. Memory Limits and Eviction Policies

maxmemory caps how much RAM Redis may use for data (0, the default, means no limit). When the cap is reached, the maxmemory-policy decides what happens to new writes. The default, noeviction, rejects writes with an out-of-memory error instead of deleting anything.

PolicyWhich keys can be evictedHow the victim is chosen
noeviction (default)None: writes fail with an error-
allkeys-lruAny keyLeast recently used
allkeys-lfuAny keyLeast frequently used
allkeys-randomAny keyRandom
allkeys-lrmAny keyLeast recently modified (reads do not count)
volatile-lruOnly keys with a TTLLeast recently used
volatile-lfuOnly keys with a TTLLeast frequently used
volatile-randomOnly keys with a TTLRandom
volatile-ttlOnly keys with a TTLShortest remaining TTL first
volatile-lrmOnly keys with a TTLLeast recently modified

For a pure cache, allkeys-lru or allkeys-lfu is the usual choice. When Redis also stores data that must not disappear, such as sessions without a backup, keep noeviction and size the server properly, or use a volatile-* policy so only keys with a TTL can be evicted. LRU and LFU are approximations: Redis samples a few keys (maxmemory-samples, default 5) instead of tracking every key exactly.

Version note: The allkeys-lrm and volatile-lrm policies are recent additions in Redis 8 and are not available in Redis 7.x or in older managed services.

11. Replication, Sentinel and Redis Cluster

  • Replication: one primary accepts writes and copies them to one or more replicas, which can serve reads. Replication is asynchronous by default, so a primary that crashes can lose writes it has not yet sent. WAIT lets a client wait for replicas to acknowledge, but it still does not make Redis strongly consistent.
  • Sentinel: a group of Sentinel processes watches the primary, agrees when it is down and promotes a replica automatically. Clients ask Sentinel for the current primary address.
  • Redis Cluster: splits the keyspace into 16,384 hash slots spread across several primaries, each with its own replicas. A key's slot is CRC16(key) mod 16384. Commands that touch several keys only work when all keys are in the same slot; a hash tag such as cart:{user:42} and orders:{user:42} forces related keys into one slot.
SetupSolvesChoose it when
Single instanceSimplicityDevelopment, or a cache that can be rebuilt quickly
Primary + replicas + SentinelAutomatic failover, read scalingData fits on one server but must stay available
Redis ClusterHorizontal scaling of memory and writesData or write load is larger than one server

12. Redis Caching in Spring Boot: Complete Example

This example builds a product catalog API with the cache-aside pattern: the application reads Redis first, loads from the database on a miss, and writes the result back with a TTL. It uses Spring Data Redis with StringRedisTemplate, stores products as JSON, and keeps working (more slowly) when Redis is down. For the general idea of caching, see What Is Caching.

Cache-aside flow in ProductCacheService A client calls GET /api/products/1001. ProductCacheService first reads key product:1001 from Redis. On a hit Redis returns the cached JSON. On a miss the service selects the row with id 1001 from the database, then writes product:1001 to Redis with a 10-minute TTL and returns the product. A price update changes the database row and then deletes product:1001. ClientGET /api/products/1001 ProductCacheServicegetProduct(1001) Redisproduct:1001TTL 10 min Databaseproduct table, id 1001 1. GET 2. hit: JSON 4. SET + TTL 3. miss: SELECT Update: PUT …/price → UPDATE row in database → DEL product:1001 in Redis
Figure 3: Cache-aside. The service reads Redis first (1). On a hit it returns the JSON (2); on a miss it loads the row from the database (3) and stores it in Redis with a TTL (4).

12.1 Project Setup

The project uses the package base com.javabytechie.shop. H2 is an in-memory database that plays the role of the real system of record, so you can run the example without installing MySQL or PostgreSQL.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.1.1</version>
        <relativePath/>
    </parent>

    <groupId>com.javabytechie</groupId>
    <artifactId>shop</artifactId>
    <version>1.0.0</version>

    <properties>
        <java.version>21</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-testcontainers</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>testcontainers-junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
Version note: In Spring Boot 4, spring-boot-starter-web is deprecated in favour of spring-boot-starter-webmvc, and Jackson 3 (package tools.jackson) replaces Jackson 2. Testcontainers 2 renamed its JUnit 5 artifact to testcontainers-junit-jupiter.
application.properties
spring.application.name=shop

# Redis connection (Spring Boot 3+ uses the spring.data.redis.* prefix)
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.password=${REDIS_PASSWORD}
spring.data.redis.timeout=2s
spring.data.redis.connect-timeout=2s

# In-memory H2 database that plays the role of the slow system of record
spring.datasource.url=jdbc:h2:mem:shop
Version note: Spring Boot 3.0 moved Redis properties from spring.redis.* to spring.data.redis.*. Old keys are ignored, which is a common reason a migrated app suddenly connects to localhost.
schema.sql
CREATE TABLE product (
    id    BIGINT PRIMARY KEY,
    name  VARCHAR(100)   NOT NULL,
    price DECIMAL(10, 2) NOT NULL,
    stock INT            NOT NULL
);
data.sql
INSERT INTO product (id, name, price, stock) VALUES (1001, 'Wireless Mouse', 799.00, 25);
INSERT INTO product (id, name, price, stock) VALUES (2002, 'Mechanical Keyboard', 3499.00, 12);

12.2 The Product Record and Repository

Product.java
package com.javabytechie.shop.product;

import java.math.BigDecimal;

public record Product(long id, String name, BigDecimal price, int stock) {
}
ProductNotFoundException.java
package com.javabytechie.shop.product;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ProductNotFoundException extends RuntimeException {

    public ProductNotFoundException(long id) {
        super("Product " + id + " not found");
    }
}
ProductRepository.java
package com.javabytechie.shop.product;

import java.math.BigDecimal;
import java.util.Optional;

import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Repository;

@Repository
public class ProductRepository {

    private final JdbcClient jdbc;

    public ProductRepository(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    public Optional<Product> findById(long id) {
        return jdbc.sql("SELECT id, name, price, stock FROM product WHERE id = :id")
                .param("id", id)
                .query(Product.class)
                .optional();
    }

    public boolean updatePrice(long id, BigDecimal price) {
        int rows = jdbc.sql("UPDATE product SET price = :price WHERE id = :id")
                .param("price", price)
                .param("id", id)
                .update();
        return rows == 1;
    }
}

12.3 The Cache-Aside Service

The service owns all Redis access. Every write sets a 10-minute TTL, an update deletes the cached copy so the next read reloads it, and any Redis failure (a Spring DataAccessException) is logged and treated as a cache miss, so customers still get data from the database.

ProductCacheService.java
package com.javabytechie.shop.product;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import tools.jackson.databind.json.JsonMapper;

/**
 * Cache-aside: read from Redis first, fall back to the database on a miss,
 * then store the result in Redis with a TTL.
 */
@Service
public class ProductCacheService {

    static final Duration CACHE_TTL = Duration.ofMinutes(10);
    private static final Logger log = LoggerFactory.getLogger(ProductCacheService.class);

    private final StringRedisTemplate redis;
    private final ProductRepository repository;
    private final JsonMapper jsonMapper;

    public ProductCacheService(StringRedisTemplate redis, ProductRepository repository, JsonMapper jsonMapper) {
        this.redis = redis;
        this.repository = repository;
        this.jsonMapper = jsonMapper;
    }

    static String cacheKey(long id) {
        return "product:" + id;           // naming convention: <type>:<id>
    }

    public Product getProduct(long id) {
        Optional<Product> cached = readFromCache(id);
        if (cached.isPresent()) {
            log.info("Cache hit for {}", cacheKey(id));
            return cached.get();
        }

        log.info("Cache miss for {}, loading from database", cacheKey(id));
        Product product = repository.findById(id)
                .orElseThrow(() -> new ProductNotFoundException(id));
        writeToCache(product);
        return product;
    }

    public Product updatePrice(long id, BigDecimal newPrice) {
        if (!repository.updatePrice(id, newPrice)) {
            throw new ProductNotFoundException(id);
        }
        evict(id);                          // the next read reloads fresh data
        return getProduct(id);
    }

    private Optional<Product> readFromCache(long id) {
        try {
            String json = redis.opsForValue().get(cacheKey(id));
            return Optional.ofNullable(json).map(value -> jsonMapper.readValue(value, Product.class));
        } catch (DataAccessException ex) {
            log.warn("Redis unavailable, reading {} from database: {}", cacheKey(id), ex.getMessage());
            return Optional.empty();
        }
    }

    private void writeToCache(Product product) {
        try {
            String json = jsonMapper.writeValueAsString(product);
            redis.opsForValue().set(cacheKey(product.id()), json, CACHE_TTL);
        } catch (DataAccessException ex) {
            log.warn("Redis unavailable, {} not cached: {}", cacheKey(product.id()), ex.getMessage());
        }
    }

    private void evict(long id) {
        try {
            redis.delete(cacheKey(id));
        } catch (DataAccessException ex) {
            log.warn("Redis unavailable, {} not evicted: {}", cacheKey(id), ex.getMessage());
        }
    }
}

12.4 The Controller and Application Class

ProductController.java
package com.javabytechie.shop.product;

import java.math.BigDecimal;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    public record PriceUpdate(BigDecimal price) {
    }

    private final ProductCacheService productService;

    public ProductController(ProductCacheService productService) {
        this.productService = productService;
    }

    @GetMapping("/{id}")
    public Product getProduct(@PathVariable long id) {
        return productService.getProduct(id);
    }

    @PutMapping("/{id}/price")
    public Product updatePrice(@PathVariable long id, @RequestBody PriceUpdate update) {
        return productService.updatePrice(id, update.price());
    }
}
ShopApplication.java
package com.javabytechie.shop;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ShopApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShopApplication.class, args);
    }
}

12.5 Run the Example

Start Redis with the Compose file from section 4, then run the application with the same password:

Console
export REDIS_PASSWORD='choose-a-long-random-password'
mvn spring-boot:run

# in a second terminal
curl http://localhost:8080/api/products/1001
curl http://localhost:8080/api/products/1001
curl -X PUT -H 'Content-Type: application/json' -d '{"price": 749.00}' http://localhost:8080/api/products/1001/price
curl -i http://localhost:8080/api/products/9999
HTTP responses (last call: status line only)
{"id":1001,"name":"Wireless Mouse","price":799.00,"stock":25}
{"id":1001,"name":"Wireless Mouse","price":799.00,"stock":25}
{"id":1001,"name":"Wireless Mouse","price":749.00,"stock":25}
HTTP/1.1 404
Application log (trimmed)
INFO  c.j.shop.product.ProductCacheService : Cache miss for product:1001, loading from database
INFO  c.j.shop.product.ProductCacheService : Cache hit for product:1001
INFO  c.j.shop.product.ProductCacheService : Cache miss for product:1001, loading from database
INFO  c.j.shop.product.ProductCacheService : Cache miss for product:9999, loading from database

The first request misses and fills the cache, the second is served from Redis, and the price update evicts the key so the third read reloads fresh data. Unknown products return 404 and are not cached. Look at the cached value from redis-cli (after AUTH):

redis-cli
127.0.0.1:6379> GET product:1001
"{\"id\":1001,\"name\":\"Wireless Mouse\",\"price\":749.00,\"stock\":25}"
127.0.0.1:6379> TTL product:1001
(integer) 600

If you stop Redis with docker stop shop-redis, requests still succeed from the database and the log shows the fallback:

Application log with Redis stopped
WARN  c.j.shop.product.ProductCacheService : Redis unavailable, reading product:2002 from database: Redis command timed out
WARN  c.j.shop.product.ProductCacheService : Redis unavailable, product:2002 not cached: Redis command timed out

Each of those calls waited for the 2-second spring.data.redis.timeout. In production, keep the timeout short and consider a circuit breaker so a Redis outage does not slow every request.

12.6 The Alternative: @Cacheable

Spring's cache abstraction can do the same with less code: add spring-boot-starter-cache, put @EnableCaching on a configuration class and @Cacheable("products") on the read method, and set spring.cache.redis.time-to-live=10m. It is a good fit for simple read caching. The manual approach above gives you explicit control over key names, TTLs, logging and failure handling. The Spring Boot caching tutorial covers the annotations in detail.

13. Configuration Options

13.1 Spring Boot Properties

PropertyDefaultPurpose
spring.data.redis.hostlocalhostRedis server host
spring.data.redis.port6379Redis server port
spring.data.redis.usernamenoneACL user name (Redis 6+)
spring.data.redis.passwordnonePassword for AUTH
spring.data.redis.urlnoneConnection URL such as rediss://user:pass@host:6380; overrides host, port and password
spring.data.redis.database0Logical database index
spring.data.redis.timeoutclient defaultRead timeout for commands
spring.data.redis.connect-timeoutclient defaultTimeout for opening a connection
spring.data.redis.ssl.enabledfalseUse TLS
spring.data.redis.client-typelettuce when availableChoose lettuce or jedis
spring.data.redis.lettuce.pool.enabledoff unless commons-pool2 is presentConnection pooling; not needed for most Lettuce apps
spring.data.redis.sentinel.master / .nodesnoneConnect through Sentinel
spring.data.redis.cluster.nodesnoneConnect to a Redis Cluster

13.2 Key redis.conf Directives

DirectiveDefault (Redis 8.10)Purpose
maxmemory0 (no limit)Memory cap for data
maxmemory-policynoevictionWhat to do when the cap is reached
save3600 1 300 100 60 10000RDB snapshot rules
appendonlynoEnable the AOF log
appendfsynceverysecHow often AOF is flushed to disk
io-threads1Threads for network I/O
requirepass / ACL usersnoneAuthentication
bind and protected-modeDepends on the config file usedWhich interfaces accept connections

14. Testing with Testcontainers

Mocking StringRedisTemplate would not prove that keys, TTLs and JSON really work. Testcontainers starts a real Redis 8.10 container for the test, with a password like production, and the test checks Redis state before and after each call.

ProductCacheServiceTest.java
package com.javabytechie.shop.product;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import java.math.BigDecimal;

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.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

@SpringBootTest
@Testcontainers
class ProductCacheServiceTest {

    private static final String PASSWORD = "test-secret";

    @Container
    static GenericContainer<?> redisContainer = new GenericContainer<>("redis:8.10")
            .withCommand("redis-server", "--requirepass", PASSWORD)
            .withExposedPorts(6379);

    @DynamicPropertySource
    static void redisProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.data.redis.host", redisContainer::getHost);
        registry.add("spring.data.redis.port", () -> redisContainer.getMappedPort(6379));
        registry.add("spring.data.redis.password", () -> PASSWORD);
    }

    @Autowired
    ProductCacheService productService;

    @Autowired
    StringRedisTemplate redis;

    @Autowired
    JdbcClient jdbc;

    @BeforeEach
    void resetState() {
        redis.delete("product:1001");
        jdbc.sql("UPDATE product SET price = 799.00 WHERE id = 1001").update();
    }

    @Test
    void cacheMissStoresProductWithTtl() {
        assertThat(redis.hasKey("product:1001")).isFalse();

        Product product = productService.getProduct(1001);

        assertThat(product.name()).isEqualTo("Wireless Mouse");
        assertThat(redis.opsForValue().get("product:1001")).contains("\"name\":\"Wireless Mouse\"");
        assertThat(redis.getExpire("product:1001")).isBetween(1L, 600L);
    }

    @Test
    void cacheHitDoesNotReadTheDatabase() {
        productService.getProduct(1001);                                        // fills the cache
        jdbc.sql("UPDATE product SET price = 1.00 WHERE id = 1001").update();   // change behind the cache

        Product cached = productService.getProduct(1001);

        assertThat(cached.price()).isEqualByComparingTo("799.00");
    }

    @Test
    void updatePriceEvictsAndReloads() {
        productService.getProduct(1001);

        Product updated = productService.updatePrice(1001, new BigDecimal("749.00"));

        assertThat(updated.price()).isEqualByComparingTo("749.00");
        assertThat(redis.opsForValue().get("product:1001")).contains("749");
    }

    @Test
    void unknownProductIsNotCached() {
        assertThatThrownBy(() -> productService.getProduct(9999))
                .isInstanceOf(ProductNotFoundException.class);
        assertThat(redis.hasKey("product:9999")).isFalse();
    }
}
Console
mvn test
Output (trimmed)
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

The tests cover a miss that stores JSON with a TTL, a hit that never reaches the database, eviction on update and a not-found product that is never cached. Docker must be running for Testcontainers to start the container.

15. Common Pitfalls

PitfallWhat goes wrongFix
Cache keys without a TTLStale data lives forever and memory fills upSet a TTL on every cache write
KEYS * in productionBlocks the server while it scans every keyUse SCAN with a cursor
Plain SET on a key with a TTLThe TTL is silently removedUse KEEPTTL or set EX again
Big keysA 2 million-element list or a 100 MB value blocks the server on read or deleteSplit data into smaller keys; delete with UNLINK
Many keys expiring at the same momentA burst of misses hits the database together (cache stampede)Add a little random jitter to TTLs; load hot keys once
noeviction on a cacheWrites start failing with OOM errors when memory is fullUse allkeys-lru or allkeys-lfu for pure caches
Trusting MULTI for rollbackA failed command leaves other changes appliedValidate first, or use a Lua script
Old spring.redis.* keysSpring Boot 3+ ignores them and connects to localhostRename to spring.data.redis.*

15.1 How to Fix "Redis Connection Refused"

Spring logs Unable to connect to Redis or Lettuce reports Connection refused when nothing accepts connections on the host and port. Check, in order:

  1. Is Redis running? docker ps should list the container, and docker exec -it shop-redis redis-cli PING should answer.
  2. Host and port: inside Docker Compose, other containers reach Redis by service name (redis), not localhost.
  3. Port mapping: 127.0.0.1:6379:6379 only accepts connections from the same machine.
  4. Property names: make sure you use spring.data.redis.*.
  5. Authentication: a wrong or missing password gives NOAUTH or WRONGPASS errors rather than "connection refused"; check REDIS_PASSWORD.

16. Securing Redis

  • Never expose Redis to the internet. Bind it to private interfaces or 127.0.0.1, and use firewalls or security groups. The official Docker image accepts connections on all interfaces with protected mode off, so the port mapping and a password are your protection.
  • Require authentication. Use requirepass for simple setups, or ACL users (Redis 6+) with their own passwords and limited commands and key patterns, for example a user that can only run read commands on product:*.
  • Encrypt traffic with TLS when Redis runs on another host or in the cloud, and enable spring.data.redis.ssl.enabled in the client.
  • Disable or rename dangerous commands such as FLUSHALL, KEYS and CONFIG for application users through ACL rules.
  • Keep Redis patched. Recent 8.x patch releases fixed security issues, so follow the release notes for your version.

17. When to Use Redis and When to Avoid It

Good use casesPoor use cases
Caching database or API results with a TTLThe only copy of orders, payments or other critical records
User sessions and shopping cartsData much larger than the RAM you can afford
Counters, rate limits and distributed locks with a TTLComplex queries with joins, reporting and ad hoc analytics
Leaderboards and top-N lists with sorted setsLong-term event storage with replay for many teams (use Kafka)
Lightweight queues and order events with streamsWorkloads that need multi-key transactions with rollback

18. Best Practices

  • Use one key naming convention (type:id, such as product:1001 and cart:user:42) across all services.
  • Set a TTL on every cache key and add jitter for keys that are created in bulk.
  • Treat Redis as a cache, not the system of record, unless you have configured persistence and replication for that data.
  • Handle Redis failures by falling back to the database with short timeouts, as ProductCacheService does.
  • Invalidate on write by deleting the cached key after updating the database.
  • Use SCAN, not KEYS, and avoid big keys and slow commands on hot paths.
  • Choose the eviction policy on purpose: allkeys-lru or allkeys-lfu for caches, noeviction when losing keys is unacceptable.
  • Enable AOF with appendfsync everysec for data you cannot rebuild, and keep RDB snapshots for backups.
  • Secure every environment with authentication or ACLs, private networking and TLS.
  • Test against a real Redis with Testcontainers and monitor used_memory, evicted_keys and hit rate in production.

19. Summary

In this Redis tutorial you saw that Redis is an in-memory key-value store that runs commands one at a time on its main thread, which makes single commands atomic and very fast. You used strings, hashes, lists, sets, sorted sets and streams with a consistent key naming convention, controlled lifetimes with TTLs, learned that MULTI/EXEC does not roll back, chose between Pub/Sub and Streams, and compared RDB and AOF persistence, eviction policies and high-availability options. Finally, you built and tested a Spring Boot 4 cache-aside service that sets a TTL on every write, evicts on update and falls back to the database when Redis is down. The main recommendation: use Redis to speed up a durable database, not to replace it, and secure and size it with the same care as any production service. Next, explore the MongoDB Tutorial to compare Redis with a document database.

References

Official documentation used to check the commands, defaults and version notes on this page:

Redis documentation

Spring and tooling documentation