A kit room right by the pitch
A sports club keeps most of its things in a big storage shed at the far end of the grounds. Everything is safe there, but fetching anything takes a long walk.
So the club also has a small kit room right next to the pitch. It's a wall of cubbies, and every cubby has a label on the front, called a key, like "Ana's shirt" or "Today's team sheet". You don't search for things: you say the label, and the kit manager hands you what's inside, almost instantly.
The catch is that the kit room is small, and if the building floods, whatever was only in the cubbies is gone unless someone kept a copy.
An in-memory key-value server
Redis (and its fork Valkey) is a server that keeps all its data in RAM. Every piece of data sits under a
key, a string such as user:42:name, and clients send commands like SET and GET over TCP using a simple
text protocol called RESP.
Because reads and writes touch memory rather than disk, a typical command takes microseconds inside the server, and the round trip is usually well under a millisecond on a local network. That's why it's the usual choice for a shared cache in front of a database (see distributed caching).
Memory is volatile. Redis can persist data to disk with RDB snapshots and an append-only file (AOF), but by design it's usually treated as fast storage next to the source of truth, not as the only copy of important data.
Different kinds of cubby
Not every cubby holds one thing. The kit room has a few kinds, and the kit manager knows the right tricks for each:
- A cubby with one item, or a tally card the manager can add one to.
- A cubby with little labelled pockets, like a player's card with name, shirt size and number.
- A cubby with a row of hooks in order, where new things go on one end and are taken from the other.
- A cubby with a bag of name tags, where the same name can never be in twice.
- The leaderboard: every name with a score, always kept in order, so "who's in the top three?" is instant.
Because the manager works inside the cubby, you never have to carry the whole thing out, change it and carry it back. These kinds of cubby are called data structures.
Data structures, not just strings
A value isn't only a blob of bytes. Each key holds one of several types, each with its own commands that run on the server:
| Type | Example commands | Typical use |
|---|---|---|
| String | SET, GET, INCR, SET key v EX 60 | cached pages, counters, rate limits |
| Hash | HSET user:42 name Ana size M, HGET | objects and sessions, field by field |
| List | LPUSH, RPUSH, LPOP, BLPOP | simple work queues, recent items |
| Set | SADD, SISMEMBER, SINTER | unique visitors, tags, membership |
| Sorted set | ZADD, ZINCRBY, ZREVRANGE | leaderboards, priority queues, time windows |
There are more: streams (XADD, XREADGROUP) are an append-only log with consumer groups, and there are
bitmaps, HyperLogLogs and geospatial indexes.
Doing the work on the server matters. Adding to a score with ZINCRBY is one command; reading a whole leaderboard
into your app, changing it and writing it back would be slow and racy.
One kit manager, one request at a time
The kit room has one kit manager, and they serve one request at a time, start to finish. That sounds slow, but every request is tiny and everything is within arm's reach, so the queue moves very fast.
It also means nobody can cut in halfway. If two coaches both say "add one to the goals tally" at the same moment, the manager does one, then the other, and the tally goes up by two. That's what atomic means: each request happens completely, with nothing slipped in between.
It goes wrong only if a coach takes the tally card away, adds one at their desk and brings it back, because then two coaches can both copy the same old number. So ask the manager to add one; don't do the sum yourself.
Busy days have helpers at the hatch who take requests and hand things back, but only the manager ever touches the cubbies.
Single-threaded execution and atomicity
Redis runs commands on one main thread with an event loop. It multiplexes thousands of client connections,
but executes one command at a time, so every single command is atomic: INCR, HSET and ZINCRBY never
interleave with another client's command, and need no locks.
The catch is a read-modify-write done in the client: GET a counter, add one in Java, SET it back. Two clients
can read the same value and one update is lost. Use INCR instead, or one of these:
MULTI/EXEC: queue several commands and run them together, with no other client's commands in between. There's no rollback: if one command fails at run time, the others still apply.WATCHadds optimistic locking, aborting theEXECif a watched key changed.- Lua scripts (
EVAL) and functions run atomically on the server, for logic that needs a read and a decision. - Pipelining is different: the client sends many commands without waiting for each reply, saving round trips. It's about speed, not atomicity; other clients' commands can run in between.
Since Redis 6, optional I/O threads (io-threads) can read from and write to sockets in parallel, but the
commands still run on the main thread. The flip side of one thread: a slow command such as KEYS * on a large
database, or a huge SMEMBERS, blocks every other client until it finishes. Use SCAN to iterate keys.
Clear-by tags and a full room
Some things only matter for a while, so the manager can tie a clear-by tag to a cubby: "clear this out in 30 minutes". When the time passes, the cubby is emptied by itself. That suits things like "Ben has asked for kit three times this minute".
The room also has only so much shelf space. The club decides in advance what happens when it's full. The manager can refuse anything new until space is freed, or clear out the cubby nobody has opened for the longest time to make room. That clearing out is called eviction.
TTLs, maxmemory and eviction policies
Any key can carry a time to live: SET key value EX 60, EXPIRE key 60, TTL key to read it, PERSIST to
remove it. Expired keys are removed lazily when accessed and by a periodic background sweep. TTLs are what make
sessions (session:<id>) and fixed-window rate limits (INCR then EXPIRE on rate:<user>:<minute>) clean
themselves up.
Memory is capped with maxmemory, and maxmemory-policy decides what happens at the cap:
| Policy | Evicts |
|---|---|
noeviction (the default) | nothing: writes that need memory fail with an OOM error |
allkeys-lru / allkeys-lfu | any key, least recently / least frequently used |
volatile-lru / volatile-lfu | only keys that have a TTL |
volatile-ttl | the key with a TTL closest to expiring |
allkeys-random / volatile-random | a random key |
LRU and LFU are approximated by sampling a few keys, which saves memory. For a pure cache, allkeys-lru or
allkeys-lfu is the usual choice. If Redis also holds data you can't lose, use noeviction, or a volatile-* policy where only
disposable cache keys carry a TTL: under volatile-*, any key with a TTL (sessions included) can still be
evicted.
A second kit room, built from the same plan
For years, the kit room's plan was free for any club to copy and run, and many big sports centres ran their own copy for other clubs. Then, in 2024, the company that looked after the plan changed the rules so those big centres couldn't freely run new versions as a service for other clubs any more.
So a group of those centres took the last freely shared plan and built their own kit room from it, called Valkey, looked after by a neutral group that no single company controls. It has the same cubbies and you ask for things in exactly the same words, so a coach can walk into either room and be served. Since then, each room has added its own improvements. In 2025 the original kit room's plan was made free to share again too, under a third set of rules, so clubs can choose either.
Valkey: the fork
The Redis core was BSD-licensed until March 2024, when Redis Ltd. moved future releases (from Redis 7.4) to a dual source-available licence, RSALv2 or SSPLv1, which aren't OSI-approved open source licences. About a week later, the Linux Foundation launched Valkey, forked from Redis 7.2.4 and kept under the BSD 3-clause licence, with backing from AWS, Google Cloud, Oracle, Ericsson, Snap and others.
What that means in practice:
- Valkey speaks the same protocol and commands as Redis OSS 7.2, so existing clients (Lettuce, Jedis, redis-cli) and Spring Data Redis work against it unchanged.
- Since the fork, the two have diverged. Each adds features and performance work the other may not have, so check compatibility for anything newer than 7.2.
- With Redis 8 (May 2025), Redis added the AGPLv3 as a third licence option alongside RSALv2 and SSPLv1, so Redis is available under an OSI-approved licence again.
- Several managed services, including some cloud providers' Redis-compatible caches, now offer Valkey.
For most application code, the choice is about licensing, hosting and features, not about how you call it.
Using the kit room from a Java app
A Java app doesn't walk to the hatch itself. It has a club assistant who carries its requests to the kit manager and brings the answers back.
And for things that are slow to fetch from the storage shed, you can put a sign on a job that says "check the kit room first". If the answer is in a cubby, the long walk is skipped; if not, the job runs and the answer is left in a cubby for next time.
Spring Data Redis
With spring-boot-starter-data-redis, Spring Boot configures a connection factory using the Lettuce client by
default (Jedis is the alternative) and a ready-made StringRedisTemplate. Point spring.data.redis.host at
Redis or Valkey; the code is the same.
1import java.time.Duration;23@Service4class RateLimiter {5private final StringRedisTemplate redis;67RateLimiter(StringRedisTemplate redis) { this.redis = redis; }89boolean allow(String userId) {10String key = "rate:" + userId + ":" + (System.currentTimeMillis() / 60_000);11Long count = redis.opsForValue().increment(key); // INCR, atomic on the server12if (count != null && count == 1) {13redis.expire(key, Duration.ofMinutes(1)); // first hit starts the window14}15return count != null && count <= 100;16}17}
Other types have their own operations: opsForHash(), opsForList(), opsForSet() and opsForZSet() (for
example incrementScore("leaderboard", "ben", 3) is ZINCRBY).
For caching, add spring-boot-starter-cache and @EnableCaching. Spring Boot then creates a RedisCacheManager,
and @Cacheable checks Redis before the method runs:
1@Cacheable(cacheNames = "products", key = "#id")2public Product find(long id) { // runs only on a cache miss3return repository.findById(id).orElseThrow();4}
Set a TTL with spring.cache.redis.time-to-live=10m; without one, cached entries never expire. Values are
serialized with JDK serialization by default, so many teams configure a JSON serializer instead.
INCR then EXPIRE isn't atomic as a pair. If the app dies between them, the key never expires. Wrap both in
MULTI/EXEC or a Lua script, or use SET key 0 EX 60 NX before incrementing.
Big keys and hot keys. A single key with millions of members is slow to delete and to move; UNLINK frees
it in the background. One very hot key lands all its load on one thread, and in Redis Cluster on one node.
It isn't a durable database by default. Depending on persistence settings, a crash can lose the last second or more of writes, and replication to replicas is asynchronous. Don't keep the only copy of money or orders here.