TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท redis ยท valkey ยท caching ยท data structures ยท in-memory

Redis and Valkey

An in-memory key-value server with rich data structures, where one thread runs each command atomically, keys can expire, and memory limits trigger eviction; Valkey is the Linux Foundation fork made in 2024 when Redis changed its licence.

15 min6 animations

๐Ÿ“š Builds on๐Ÿ“‹ Distributed caching

๐Ÿ–จ๏ธ Cheat sheet

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.

An in-memory key-value server5 steps
๐Ÿšช Kit room by the pitch๐Ÿง‘โ€๐ŸซCoach Maya๐Ÿท๏ธ Ana's name cubby๐Ÿš๏ธ Storage shed (far away)
Press play and watch it happen!

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:

TypeExample commandsTypical use
StringSET, GET, INCR, SET key v EX 60cached pages, counters, rate limits
HashHSET user:42 name Ana size M, HGETobjects and sessions, field by field
ListLPUSH, RPUSH, LPOP, BLPOPsimple work queues, recent items
SetSADD, SISMEMBER, SINTERunique visitors, tags, membership
Sorted setZADD, ZINCRBY, ZREVRANGEleaderboards, 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.

Data structures on the server5 steps
๐Ÿšช Kit roomRow of hooks01234๐Ÿง‘โ€๐ŸซCoach Maya๐Ÿ”ข Tally card๐Ÿชช Player card๐Ÿ‘œ Bag of name tags๐Ÿ† Leaderboard
Press play and watch it happen!

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. WATCH adds optimistic locking, aborting the EXEC if 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.

One thread, one command at a time5 steps
๐Ÿšช Kit room๐Ÿง‘โ€๐ŸซCoach Maya๐Ÿง”Coach Leo๐Ÿง‘โ€๐Ÿ”งKit manager๐Ÿ”ข Goals tally
Press play and watch it happen!

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:

PolicyEvicts
noeviction (the default)nothing: writes that need memory fail with an OOM error
allkeys-lru / allkeys-lfuany key, least recently / least frequently used
volatile-lru / volatile-lfuonly keys that have a TTL
volatile-ttlthe key with a TTL closest to expiring
allkeys-random / volatile-randoma 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.

TTLs and eviction5 steps
๐Ÿšช Kit room with 3 cubbies๐Ÿง‘โ€๐ŸซCoach Maya๐ŸŽซ Ana's locker pass๐Ÿ”ข Ben's request count๐Ÿ“‹ Old team sheet
Press play and watch it happen!

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.

Valkey, the fork5 steps
๐Ÿง‘โ€๐ŸซCoach Maya๐ŸšชOriginal kit room
Press play and watch it happen!

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;2 3@Service4class RateLimiter {5    private final StringRedisTemplate redis;6 7    RateLimiter(StringRedisTemplate redis) { this.redis = redis; }8 9    boolean allow(String userId) {10        String key = "rate:" + userId + ":" + (System.currentTimeMillis() / 60_000);11        Long count = redis.opsForValue().increment(key);         // INCR, atomic on the server12        if (count != null && count == 1) {13            redis.expire(key, Duration.ofMinutes(1));            // first hit starts the window14        }15        return 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 miss3    return 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.

Spring Data Redis4 steps
๐Ÿง‘โ€๐Ÿ’ผClub assistant๐Ÿง‘โ€๐ŸซCoach Maya๐ŸชงCheck-first sign๐Ÿšช Kit room๐Ÿš๏ธ Storage shed
Press play and watch it happen!
๐Ÿ”ง Going deeper

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.

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐Ÿ”—Design a URL shortenerShort codes for long links, and billions of redirects.practice problem

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about Redis and Valkey, told the same way as the story.
  1. Two coaches each ask the kit manager to add one to the goals tally at the same moment. What happens?
  2. A coach takes the tally card away, adds one at their desk and brings it back, while another coach does the same. What can go wrong?
  3. The kit room is full and the club's rule is never to throw anything out. A coach brings something new. What happens?
  4. Maya's club moves from the original kit room to the Valkey kit room. What does she need to change in how she asks for things?
Answer every question to check.Passing marks Redis and Valkey as done.
Got the hang of Redis and Valkey? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿงฐ Caching with Redis, Valkey and HazelcastStep 2 of 8

โ† Previous on the path๐Ÿ“‹ Distributed cachingNext on the path โ†’๐Ÿงพ Redis persistence and replication

๐Ÿ‘‰ Read next

  • ๐ŸชAmazon ElastiCacheHiring an agency to run your shop's express counter, staff and standby clerk included, while you choose what it stocks.
  • ๐ŸซRedis ClusterA school office with 16,384 numbered pigeonholes shared out among the staff, picked by a fixed sum on each name.
  • ๐Ÿ”‘Distributed locks with RedisOne key to a shared meeting room, tagged with the borrower's name and a time it must come back by.
  • ๐ŸงพRedis persistence and replicationA till that keeps everything in memory, with photos and a receipt roll to rebuild it after a power cut.
  • ๐Ÿ“ปRedis Streams and pub/subA radio show that's gone once aired, next to a deli ticket rail where tickets stay until someone serves them.