Redis Tutorial: Data Types, Persistence and Spring Boot Caching
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.
2. Redis vs a Relational Database
Redis and a relational database solve different problems. The table shows where each one fits.
| Aspect | Redis | Relational database (MySQL, PostgreSQL) |
|---|---|---|
| Where data lives | RAM, with optional snapshots or a log on disk | Disk, with a memory cache for hot pages |
| Data model | Keys with typed values (strings, hashes, lists, sets, sorted sets, streams) | Tables with rows, columns, keys and constraints |
| Queries | Look up by key; commands per data type; no joins | SQL with joins, filters, aggregation |
| Typical latency | Sub-millisecond | Milliseconds |
| Durability | Configurable; some recent writes can be lost | Committed transactions survive crashes |
| Transactions | MULTI/EXEC without rollback; Lua scripts | Full ACID transactions with rollback |
| Best for | Caching, sessions, counters, leaderboards, rate limits, queues | System 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.
- Command execution is single-threaded. Only one command runs at a time, so a single command such as
INCRis always atomic: no other client can see a half-finished change. - I/O can be multi-threaded. Since Redis 6, the
io-threadssetting 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:
# 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:
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:
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:
export REDIS_PASSWORD='choose-a-long-random-password'
docker compose up -d
docker exec -it shop-redis 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.
| Key | Type | Holds |
|---|---|---|
product:1001 | String | Cached JSON of product 1001 |
stock:product:2002 | String | Stock counter for product 2002 |
cart:user:42 | Hash | Shopping cart of user 42 (product → quantity) |
session:7f3a9c | String | Login session with id 7f3a9c |
recent:user:42 | List | Products user 42 viewed recently |
leaderboard:weekly | Sorted set | Weekly player scores |
orders:events | Stream | Order 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.
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:
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:
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.
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.
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:
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".
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:
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.
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
| Type | Use it for |
|---|---|
| JSON | Storing and updating nested JSON documents by path (built into Redis 8) |
| Bitmaps | Daily active users or feature flags as one bit per user id |
| HyperLogLog | Approximate unique counts (for example, unique visitors) in about 12 KB |
| Geospatial | Finding stores or drivers within a radius |
| Time series, Bloom filters, vector sets | Metrics, "have I seen this?" checks and similarity search (built into Redis 8) |
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).
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.
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:
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/Sub | Streams | |
|---|---|---|
| Storage | None: messages are pushed and forgotten | Entries are stored in the stream until trimmed |
| Offline consumers | Miss every message sent while disconnected | Read what they missed when they come back |
| Delivery guarantee | At most once | At least once with consumer groups and XACK |
| Load sharing | Every subscriber gets every message | Consumer groups split entries between workers |
| Good for | Live notifications, cache invalidation signals | Order 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:
127.0.0.1:6379> PUBLISH price-updates product:1001
(integer) 0
A connected subscriber sees the message as a three-part reply:
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.
appendfsync everysec narrows the loss window to about one second.| RDB | AOF | |
|---|---|---|
| Default in Redis 8.10 | On: save 3600 1 300 100 60 10000 | Off: appendonly no |
| What a crash can lose | Every write since the last snapshot (up to minutes) | About one second with appendfsync everysec; nothing acknowledged with always, at a large speed cost |
| File size | Small, compressed | Larger; rewritten in the background to stay compact |
| Restart speed | Fast to load | Slower for big logs (an RDB preamble helps) |
| Best for | Backups and disaster recovery copies | Data 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:
# 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.
| Policy | Which keys can be evicted | How the victim is chosen |
|---|---|---|
noeviction (default) | None: writes fail with an error | - |
allkeys-lru | Any key | Least recently used |
allkeys-lfu | Any key | Least frequently used |
allkeys-random | Any key | Random |
allkeys-lrm | Any key | Least recently modified (reads do not count) |
volatile-lru | Only keys with a TTL | Least recently used |
volatile-lfu | Only keys with a TTL | Least frequently used |
volatile-random | Only keys with a TTL | Random |
volatile-ttl | Only keys with a TTL | Shortest remaining TTL first |
volatile-lrm | Only keys with a TTL | Least 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.
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.
WAITlets 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 ascart:{user:42}andorders:{user:42}forces related keys into one slot.
| Setup | Solves | Choose it when |
|---|---|---|
| Single instance | Simplicity | Development, or a cache that can be rebuilt quickly |
| Primary + replicas + Sentinel | Automatic failover, read scaling | Data fits on one server but must stay available |
| Redis Cluster | Horizontal scaling of memory and writes | Data 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.
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.
<?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>
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.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
spring.redis.* to spring.data.redis.*. Old keys are ignored, which is a common reason a migrated app suddenly connects to localhost.CREATE TABLE product (
id BIGINT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
stock INT NOT NULL
);
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
package com.javabytechie.shop.product;
import java.math.BigDecimal;
public record Product(long id, String name, BigDecimal price, int stock) {
}
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");
}
}
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.
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
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());
}
}
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:
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
{"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
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):
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:
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
| Property | Default | Purpose |
|---|---|---|
spring.data.redis.host | localhost | Redis server host |
spring.data.redis.port | 6379 | Redis server port |
spring.data.redis.username | none | ACL user name (Redis 6+) |
spring.data.redis.password | none | Password for AUTH |
spring.data.redis.url | none | Connection URL such as rediss://user:pass@host:6380; overrides host, port and password |
spring.data.redis.database | 0 | Logical database index |
spring.data.redis.timeout | client default | Read timeout for commands |
spring.data.redis.connect-timeout | client default | Timeout for opening a connection |
spring.data.redis.ssl.enabled | false | Use TLS |
spring.data.redis.client-type | lettuce when available | Choose lettuce or jedis |
spring.data.redis.lettuce.pool.enabled | off unless commons-pool2 is present | Connection pooling; not needed for most Lettuce apps |
spring.data.redis.sentinel.master / .nodes | none | Connect through Sentinel |
spring.data.redis.cluster.nodes | none | Connect to a Redis Cluster |
13.2 Key redis.conf Directives
| Directive | Default (Redis 8.10) | Purpose |
|---|---|---|
maxmemory | 0 (no limit) | Memory cap for data |
maxmemory-policy | noeviction | What to do when the cap is reached |
save | 3600 1 300 100 60 10000 | RDB snapshot rules |
appendonly | no | Enable the AOF log |
appendfsync | everysec | How often AOF is flushed to disk |
io-threads | 1 | Threads for network I/O |
requirepass / ACL users | none | Authentication |
bind and protected-mode | Depends on the config file used | Which 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.
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();
}
}
mvn test
[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
| Pitfall | What goes wrong | Fix |
|---|---|---|
| Cache keys without a TTL | Stale data lives forever and memory fills up | Set a TTL on every cache write |
KEYS * in production | Blocks the server while it scans every key | Use SCAN with a cursor |
Plain SET on a key with a TTL | The TTL is silently removed | Use KEEPTTL or set EX again |
| Big keys | A 2 million-element list or a 100 MB value blocks the server on read or delete | Split data into smaller keys; delete with UNLINK |
| Many keys expiring at the same moment | A burst of misses hits the database together (cache stampede) | Add a little random jitter to TTLs; load hot keys once |
noeviction on a cache | Writes start failing with OOM errors when memory is full | Use allkeys-lru or allkeys-lfu for pure caches |
Trusting MULTI for rollback | A failed command leaves other changes applied | Validate first, or use a Lua script |
Old spring.redis.* keys | Spring Boot 3+ ignores them and connects to localhost | Rename 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:
- Is Redis running?
docker psshould list the container, anddocker exec -it shop-redis redis-cli PINGshould answer. - Host and port: inside Docker Compose, other containers reach Redis by service name (
redis), notlocalhost. - Port mapping:
127.0.0.1:6379:6379only accepts connections from the same machine. - Property names: make sure you use
spring.data.redis.*. - Authentication: a wrong or missing password gives
NOAUTHorWRONGPASSerrors rather than "connection refused"; checkREDIS_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
requirepassfor 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 onproduct:*. - Encrypt traffic with TLS when Redis runs on another host or in the cloud, and enable
spring.data.redis.ssl.enabledin the client. - Disable or rename dangerous commands such as
FLUSHALL,KEYSandCONFIGfor 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 cases | Poor use cases |
|---|---|
| Caching database or API results with a TTL | The only copy of orders, payments or other critical records |
| User sessions and shopping carts | Data much larger than the RAM you can afford |
| Counters, rate limits and distributed locks with a TTL | Complex queries with joins, reporting and ad hoc analytics |
| Leaderboards and top-N lists with sorted sets | Long-term event storage with replay for many teams (use Kafka) |
| Lightweight queues and order events with streams | Workloads that need multi-key transactions with rollback |
18. Best Practices
- Use one key naming convention (
type:id, such asproduct:1001andcart: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
ProductCacheServicedoes. - Invalidate on write by deleting the cached key after updating the database.
- Use
SCAN, notKEYS, and avoid big keys and slow commands on hot paths. - Choose the eviction policy on purpose:
allkeys-lruorallkeys-lfufor caches,noevictionwhen losing keys is unacceptable. - Enable AOF with
appendfsync everysecfor 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_keysand 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
- Redis data types
- Keys and values (keyspace and expiration)
- Transactions
- Pub/Sub
- Streams
- Persistence
- Key eviction
- Security
- Redis Open Source 8.10 release notes
- Redis licenses
Spring and tooling documentation
Frequently Asked Questions (FAQ)
Q1. Is Redis single-threaded?
Redis runs commands on a single main thread, so two commands never interleave and each one is atomic. It is not completely single-threaded, though. Since Redis 6 you can enable I/O threads with the io-threads setting to read and write network data in parallel, and background threads handle tasks such as AOF fsync and lazy freeing of deleted keys. RDB snapshots run in a forked child process.
Q2. What is the difference between Redis and Memcached?
Both are in-memory key-value stores used for caching. Memcached stores plain string values and is multi-threaded, but it has no persistence or replication of its own. Redis adds data structures (hashes, lists, sets, sorted sets, streams), optional persistence, replication, Pub/Sub and atomic scripts. Choose Memcached only for a very simple string cache; Redis covers that case and much more.
Q3. Does Redis lose data on restart?
It depends on persistence. With the default settings of recent Redis releases, RDB snapshots are on (save 3600 1 300 100 60 10000) and AOF is off, so a crash can lose every write since the last snapshot. With appendonly yes and appendfsync everysec, you lose about one second of writes at most. Managed services and Docker images can override these defaults, so check CONFIG GET save and CONFIG GET appendonly on your server.
Q4. Why did my Redis key expire early or lose its TTL?
A plain SET on an existing key removes its TTL, and a SET with EX replaces it; use KEEPTTL to keep the old one. Keys can also disappear before their TTL when Redis reaches maxmemory and the eviction policy removes them, for example with allkeys-lru. Check INFO stats for evicted_keys and expired_keys to see which one happened.
Q5. How much data can Redis hold?
Redis keeps the whole dataset in RAM, so the practical limit is the memory you give it (set maxmemory to a safe value). A single string value can be up to 512 MB, and one hash, list, set or sorted set can hold over four billion elements. For data larger than one machine, Redis Cluster splits keys across several nodes.
Q6. Is Redis free and open source?
Redis 8 and later are available under a choice of three licenses: RSALv2, SSPLv1 or the OSI-approved AGPLv3. Versions 7.4 to 7.8 used only RSALv2/SSPLv1, and 7.2 and earlier were BSD-licensed. Valkey, a Linux Foundation fork of Redis 7.2.4, remains BSD-licensed.
Q7. Should I use Lettuce or Jedis in Spring Boot?
Spring Boot uses Lettuce by default when you add spring-boot-starter-data-redis. Lettuce is non-blocking, thread-safe and shares one connection across threads, which suits most applications. Jedis is a simpler, blocking client that needs a connection pool; switch with spring.data.redis.client-type=jedis and the Jedis dependency if your team prefers it.
Q8. Can Redis replace my main database?
Sometimes, for data that fits in memory and can tolerate the durability settings you choose, such as sessions or counters. For business records like orders and payments, keep a durable database (MySQL, PostgreSQL, MongoDB) as the system of record and use Redis in front of it for speed. Redis has no SQL joins, no rollback on failed transactions and only asynchronous replication by default.