What you'll learn: By the end of this lesson you will be able to name the Redis structure that fits a question (counter, record, unique set, ranking, queue), read the cost of its commands from the documented complexity, explain why one command is atomic and a read-then-write pair is not, use
WATCHor a script to protect a check-then-act, and walk the keyspace withSCANinstead ofKEYS. A small in-memory model lab prints every claim, and it is a model, not Redis.
A kitchen has more than one container. Salt lives in a labelled jar, one pinch at a time. A recipe card keeps its ingredients in named lines. A guest list never writes a name twice. A leaderboard on the wall is always in order because every score is placed where it belongs. A spike by the pass holds order tickets, oldest first. None of these is "a box"; each is a shape that makes one job easy and another awkward.
Redis describes itself as a data structure server: its values are hashes, lists, sets, sorted sets and more, not only strings. NoSQL types placed Redis in the key-value family and distributed caches covered several servers sharing keys. This lesson stays inside one server: which structure to put under a key, what each command costs, and what is atomic.
Verified against the current Redis open-source documentation (the latest pages) and a model lab, on 2026-12-01. Redis changes quickly: features are dated where the pages date them, and you should read the page for the version you run.
The core idea
Every Redis question starts from a key, and the type of the value stored there decides which questions the server answers for you. If the structure matches the question, one cheap command does the work. If it does not, you read data into the application, change it and write it back, and that is where races and wasted bandwidth appear.
| Structure | What it holds | A question it answers directly | Commands and documented cost |
|---|---|---|---|
| String | A sequence of bytes (also used as a counter) | "What is the value?", "add one" | GET, SET, INCR: O(1) |
| Hash | Field-value pairs under one key | "This one field of the record", "add to this field" | HGET, HINCRBY: O(1); HGETALL: O(N) |
| List | Strings in insertion order (a linked list) | "Newest N", "next job" | push and pop at either end: constant time; by index: proportional to the index |
| Set | Unordered unique strings | "Is this member in?", "how many?", "who is in both?" | SADD, SISMEMBER, SCARD: O(1); SMEMBERS: O(N) |
| Sorted set | Unique strings ordered by a score | "Top N", "what is this member's rank?" | ZADD: O(log N); ZRANGE: O(log N + M) |
| Stream | An append-only log of entries | "Everything after this entry", with consumer groups | XADD: O(1) when adding an entry |
Three illustrations run through the lesson: a minimal example (a session, a counter and a cart in the model lab), a realistic example (ShopStream's best sellers, unique viewers and job queue) and a failure example (two shoppers buying the last egg).
Figure 1. One question, one structure. How to read this: each box is one key and its type; each arrow is the command the application sends. The point is that none of the arrows is "read the whole value, change it, write it back".
Strings: counters and expiring values
A string is the most basic type: a sequence of bytes. Redis has no integer type, so INCR treats the stored string as a base-10 signed 64-bit integer. If the key does not exist it is set to 0 first, so the first INCR returns 1; a non-integer value or another type is an error. INCR is O(1) and is the basis of the documented counter pattern.
Any key can carry a time to live, with one-millisecond resolution; expiry information is replicated and persisted. SET key value EX seconds stores and expires in one command, and TTL reports what is left.
The lab's first section runs a session and a counter on a clock the lab moves by hand.
Expected output, captured from a real run (Java 25.0.3, 2026-12-01):
== 1. Strings: a session with a time to live, and a counter ==
SET session:ab12 shopper:42 EX 1800 TTL = 1800 s
after 1799 s GET = shopper:42 TTL = 1 s
after 1800 s GET = (nil) TTL = -2 (-2 means the key does not exist)
INCR views:product:9001 on a missing key -> 1
INCR views:product:9001 again -> 2
INCR note:1 (holds the text hello) -> ERR value is not an integer or out of range
LPUSH note:1 x (a list command on a string) -> WRONGTYPE Operation against a key holding the wrong kind of value
A command for another type is refused with the WRONGTYPE error the documentation shows. Keys are binary-safe strings with no namespaces; the documented convention is colons (object-type:id), a 1,024-byte key is "a bad idea", and the maximum key size is 512 MB.
Hashes: a record with counters inside
A hash is a set of field-value pairs under one key: "record types" in the documentation's words, used for basic objects and groupings of counters. HGET and HINCRBY are O(1), HGETALL is O(N), and the number of fields has no practical limit other than memory. Since Redis 7.4 individual fields can have their own expiry.
The alternative for a cart is one string holding the whole cart as JSON, and the cost is that every change is read, modify, write.
Figure 2. Read-modify-write against one command. How to read this: in the top half each client works on its own copy of the text, so the later write wins. In the bottom half the server applies each increment to the current value.
The lab starts a 25-line cart with every product at quantity 1 and lets two clients each add one unit of p01.
Expected output, captured from a real run (Java 25.0.3, 2026-12-01):
== 2. A cart with 25 lines as one string, then as one hash ==
string: 201 characters of JSON in one key; hash: 25 fields in one key
p01 starts at 1 and two clients each add 1, so 3 is right. As a string (GET, GET, SET, SET) p01 ends at 2 and one add is lost
as a hash (HINCRBY, HINCRBY) p01 ends at 3 because each command is one step on the server
characters of key and value text moved for one add: string GET + SET = 424, hash HINCRBY = 17
HGETALL on the hash looked at 25 fields; HGET looks at one
The string cart lost an add and moved 424 characters of key and value text to change one number; the hash moved 17 (the model's own counts, for a 25-line cart). The documentation's advice is a rule of thumb: hashes suit simple objects with a small number of non-nested fields, JSON suits nested data.
Sets and sorted sets: membership and rank
A set is an unordered collection of unique strings: SADD ignores an existing member, SISMEMBER and SCARD are O(1), SINTER answers "who is in both?", and SMEMBERS is O(N) with no guaranteed order.
A sorted set orders unique strings by a floating-point score, and members with the same score are ordered lexicographically. Order is a property of the structure, not computed on request: it is a skip list together with a hash table, so each add is O(log N) and a range read does no sorting. The documentation names leaderboards and sliding-window rate limiters as uses.
Expected output, captured from a real run (Java 25.0.3, 2026-12-01):
== 3. Sets and sorted sets ==
SADD viewed:product:9001 u1 u2 u3 -> 3 new; SADD u2 u1 again -> 0 new; SCARD = 3
SINTER viewed bought (viewers who also bought) -> [u2]
SISMEMBER viewed u9 -> false
ZINCRBY bestsellers 1 <product> for 14 order lines
ZREVRANGE bestsellers 0 2 (highest first) -> [milk=5, eggs=5, bread=3]
milk and eggs both have score 5: equal scores are ordered by the member text, and the reverse order puts milk first
ZRANK bread = 1, ZREVRANK bread = 2, ZSCORE bread = 3
ZADD bestsellers 3 bread (member exists) -> 0 added, the score was replaced
The set ignored duplicate viewers, and the sorted set turned 14 order lines into four scored members, so "top three" is a range read. The milk and eggs tie shows why a leaderboard needs a stated tie rule. The model reverses the whole order for highest-first, which is how it reads the documentation's description of reverse order, so check that detail on a real server.
Lists and streams: queues and capped history
A list is a linked list of strings: pushing at either end is constant time, while reaching an element by index costs work proportional to the index. LPUSH with RPOP gives first-in, first-out, and LTRIM makes a capped collection of the latest N items. The documentation says special list commands make the queue use case "more reliable and efficient" and its command table lists LMOVE and BLMOVE. The lab shows why: a pop removes the element.
Expected output, captured from a real run (Java 25.0.3, 2026-12-01):
== 4. Lists: a job queue and a capped list ==
LPUSH j1, j2, j3 -> list is [j3, j2, j1] (newest at the head)
RPOP -> j1 (oldest first, so LPUSH + RPOP is a FIFO queue)
a worker RPOPs j2 and crashes before finishing; LLEN jobs = 1, the list still holds [j3]
the popped job is in no key any more: a list gives it to one caller and forgets it
LPUSH p1..p8 each followed by LTRIM 0 4 -> [p8, p7, p6, p5, p4], LLEN = 5
after the last pop the list is gone: EXISTS jobs = false
A crashed worker took job j2 with it. A stream is for work that must not vanish: an append-only log whose entries have ids, with consumer groups that split entries among consumers and support at-least-once delivery. Kafka internals and message queues compare logs and queues in general.
Atomic: one command, MULTI/EXEC, WATCH, scripts
Each of INCR, HINCRBY and ZINCRBY is one command, so no other client's command runs in the middle of it. A check-then-act that spans two commands is a different matter: another client can run between the read and the write.
Redis transactions (MULTI, EXEC, DISCARD, WATCH) guarantee that queued commands run one after another with no other client served in the middle, and that either none or all run depending on whether EXEC was reached. They do not roll back: if a queued command fails after EXEC, the others still run. WATCH adds optimistic locking: if a watched key was modified before EXEC (including by expiry or eviction), the transaction aborts and EXEC returns a null reply, so you retry. The documentation adds that a script can do anything a transaction can, usually simpler and faster.
Figure 3. Optimistic locking with WATCH. How to read this: both shoppers saw stock 1. Only the first EXEC runs. The second is refused, so the second shopper must look again and finds the stock gone.
The lab runs three versions of "two shoppers, one egg left": a bare check-then-act, WATCH, and a function standing in for a server-side script.
Expected output, captured from a real run (Java 25.0.3, 2026-12-01):
== 5. Two shoppers, one egg left: check-then-act, WATCH, and a script ==
GET, GET, then SET, SET (check then act): orders accepted = 2, stock left = 0 (one egg sold twice)
WATCH, GET, MULTI, SET, EXEC: A's EXEC -> [OK], B's EXEC -> (nil), the transaction was aborted
B retries: GET = 0 -> sold out; orders accepted = 1, stock left = 0
script 'take one if stock > 0': A -> bought, B -> sold out; stock left = 0
The unprotected version sold one egg twice. Both WATCH and the script sold it once. The model is single-threaded, so the interleavings are written out by hand; it shows the logic of each protection, not Redis's timing, and the script is an ordinary function rather than a Lua script.
Walking the keyspace: KEYS against SCAN
Finding keys by anything but their exact name is the awkward case. The documentation warns that KEYS blocks the server until all keys are returned and is for debugging, not application code. SCAN is O(1) per call and O(N) for a full walk, with limited guarantees: a full iteration returns every element present throughout, an element may be returned several times, and elements added or removed meanwhile may or may not appear. The default COUNT is 10, a hint, and MATCH is applied after elements are fetched, so a rare pattern means many empty calls. For "all keys of kind X", the documentation suggests keeping a set.
Expected output, captured from a real run (Java 25.0.3, 2026-12-01):
== 6. Finding 3 keys among 10003: KEYS against SCAN with MATCH ==
KEYS flash:* -> 3 keys in 1 call, which looked at 10003 keys
call style calls keys looked at matches calls that returned nothing
SCAN COUNT 10 1001 10003 3 1000
SCAN COUNT 100 101 10003 3 100
SCAN COUNT 1000 11 10003 3 10
SCAN spreads the same walk over many short calls; MATCH filters after the keys were looked at, so a rare pattern still costs a full walk
Both styles looked at all 10,003 keys. SCAN spreads the work so other clients are served in between, but a rare pattern is still a full walk. The model scans in sorted-key order and never repeats a key; a real SCAN uses its own cursor order and may repeat.
Build it: the in-memory model lab
Setup. From examples/backend (no Docker, no Redis server):
./gradlew :labs:redis-data-structures:test
./gradlew -q :labs:redis-data-structures:run
The command runs 21 tests; the second prints the report quoted above, which is examples/golden/redis-data-structures.txt. The code is in examples/backend/labs/redis-data-structures/src/main/java/buildingai/labs/redismodel/.
What it is, and is not. MiniRedis is a stand-in written from the documentation: single-threaded, in memory, with the five structures, expiry on a clock the lab controls, KEYS, SCAN, WATCH/MULTI/EXEC and a "script" that is a plain function. It is not Redis: no network, persistence, replication, Cluster, real SCAN cursor or timing. "Work" is how many elements the model's own code looked at, and its interleavings are scripted, not observed.
The one piece of logic worth reading is the WATCH check in MiniRedis.Transaction.exec, which compares the version of each watched key with the version seen at WATCH time and returns nothing on a difference:
for (Map.Entry<String, Long> w : watched.entrySet()) {
live(w.getKey());
if (versions.getOrDefault(w.getKey(), 0L) != w.getValue()) {
return Optional.empty();
}
}
The live call applies expiry first, so an expired watched key counts as a change, as documented.
Break it. In MiniRedis.Transaction.exec, delete the return Optional.empty(); branch: watchAbortsTheTransactionWhenAWatchedKeyChanged fails, and the Demo's section 5 shows both shoppers succeeding. Restore it and run the tests again.
Choosing a structure
Figure 4. A decision tree by question. How to read this: start from what the application will ask, not from what the data looks like.
| Structure | Gain | Cost | Wrong when |
|---|---|---|---|
| String | O(1) INCR counters |
Opaque to the server | Parts of a record change concurrently |
| Hash | Field reads, counters, expiry | HGETALL is O(N); no nesting |
The record is deeply nested |
| List | Constant-time ends, capped history | A pop forgets the item | Work must survive a crashed consumer |
| Set | O(1) membership, intersections | SMEMBERS is O(N), unordered |
You need an order |
| Sorted set | Always ordered; rank reads | O(log N) writes; the highest memory cost of the collection types | Only membership is needed |
| Stream | Log with consumer groups | More concepts than a list | A throwaway queue is enough |
The other side of this topic
Browsers keep their own small key-value stores, covered in the front-end lessons on browser storage (plain text until published). A browser store holds one user's data and offers no atomic counter shared between users, which a server-side counter does.
In practice: ShopStream's flash sale
This is an educational scenario on the course's running example ShopStream. Numbers are illustrative.
This is a realistic scenario, not a case history.
The situation
ShopStream runs a one-hour flash sale on 200 products (illustrative). Shoppers see a "best sellers" strip and a "viewed by N shoppers" label, fill carts and order; a worker updates stock. The team already has a Redis server for the cache tier. Redis sits beside the orders database and holds fast, replaceable data; the database stays the record of orders and stock.
Starting architecture
The web app writes carts and counters to Redis and orders to the database; the order worker takes jobs from Redis and updates stock in the database.
Options considered
| Option | Behaviour | Risk |
|---|---|---|
| A. Carts as JSON strings, best sellers computed per request | Simple | Lost cart edits; slow rankings |
| B. Hashes, sorted set, set, list | One command per question | A crashed worker drops a job |
| C. B with jobs on a stream and the stock check in a script | No lost jobs, no oversold item | More moving parts |
The decision
Option C. Carts are hashes with a key-level expiry, so abandoned carts clean themselves up. Best sellers are one sorted set updated with ZINCRBY as the worker confirms each order line. Viewer counts use a set per product for the sale's hour, since the unique count is what the label shows. Jobs use a stream so a crashed worker's job can be claimed again, and the stock check is one script so two shoppers cannot take the last item. The orders database stays the record: Redis can be rebuilt from it.
Rollout and verification
Start with carts behind a flag and replay sample cart edits against the lab's two-client shape to confirm no lost adds. Then add the sorted set and compare its top ten with a database query for the same hour. Verification is "the top ten match, cart quantities match orders, and no job is older than its allowed processing time".
The 2 a.m. failure
An operator's clean-up script runs KEYS cart:* to find abandoned carts, and the shop's page loads stall while it runs, because KEYS blocks the server until it finishes. The checks are the application's latency graph lining up with the script's start time, and the script itself. The mitigation is to stop the script. The lasting fix is to iterate with SCAN or, better, never need to find carts by pattern: expiry already removes abandoned ones.
Architect's notes
- Choose by question. Write the question next to each key; if it needs two commands that must not interleave, the structure is wrong or you need a script.
- Prefer one command to read-modify-write, and treat
KEYSandSMEMBERSas O(N). - Decide what a lost entry costs. A list forgets a popped job; a stream tracks delivery. There are no rollbacks, so design queued commands to fail harmlessly.
Common mistakes
- Storing a record as a JSON string you update. Concurrent edits lose changes; a hash updates one field.
- Assuming
MULTIrolls back, or usingKEYSin application code. Neither is true or safe. - Using a list as a durable queue. A pop removes the job.
Key takeaways
- The structure decides the cheap questions; match it to what you ask.
INCR,HINCRBYandZINCRBYare single steps; a read followed by a write is not.WATCHaborts on a change; a script runs as one step; neither rolls back.SCANspreads a walk over many calls but still visits every key, and may repeat one.- The lab's counts come from a model: 424 against 17 characters for one cart edit, one lost add, one egg sold twice.
Practice exercises
Exercise 1 (20 min). For a loyalty balance, a "recently viewed" strip, a set of banned users and a daily top ten, name the structure and the command.
Exercise 2 (1 hour). Run "Break it" and say what a shopper would see if WATCH never aborted.
Exercise 3 (2 hours). Extend the lab with LMOVE and a "processing" list, and show a crashed worker's job being recovered.
Related reading
- NoSQL types: where key-value sits among the families.
- Distributed caches: Redis and Memcached: several servers and failure.
- Cache strategies, eviction and cache stampedes: Redis as a cache.
- Distributed locks and fencing tokens: what a lock needs beyond
SET. - Redis rate limiting in Java is the next lesson (plain text until published).
Official documentation
- Redis, data types and compare data types.
- Redis, hashes, sets, sorted sets and lists.
- Redis, keys and values and the
SCANcommand. - Redis, transactions and the
INCRcommand.