Redis Exercises
Time to practise! Each exercise has a starter playground that already runs and shows part of the result. Complete the TODO lines in your own Redis (or edit the playground to plan your solution), and compare your transcript with the "Expected" description. Solutions are hidden below each exercise. Try for a few minutes before you peek.
Note: Playground examples in this course are simulated with saved transcripts, so edited commands only run for real against your own server (
docker run --rm -p 6379:6379 redis:8andredis-cli).
| # | Exercise | Topics |
|---|---|---|
| 1 | Stock counter | strings, INCRBY / DECRBY |
| 2 | One-time password | SET ... EX NX, TTL, GETDEL |
| 3 | Recent searches | lists, LPUSH + LTRIM |
| 4 | Common interests | sets, SINTER, SDIFF |
| 5 | User profile | hashes, HINCRBY |
| 6 | Top players | sorted sets, ZINCRBY, ZRANGE ... REV |
| 7 | Weekly unique visitors | HyperLogLog, PFMERGE |
| 8 | Safe transfer | transactions, Lua |
| 9 | Order events | streams, consumer groups |
1. Stock counter
A shop has 20 mugs in stock. Record a sale of 3 mugs, a delivery of 10 mugs, then a sale of 1 mug, each with one atomic command. Finally read the stock.
Expected: the replies of the three changes are 17, 27 and 26.
SET stock:mug 20
# TODO: sell 3, receive 10, sell 1
GET stock:mugredis> SET stock:mug 20
OK
redis> GET stock:mug
"20"
Show solution
SET stock:mug 20
DECRBY stock:mug 3
INCRBY stock:mug 10
DECR stock:mug
GET stock:mugDECRBY/INCRBY change the value inside Redis, so concurrent sales can never overwrite each other.
2. One-time password
Store the code 482913 for phone 5551234 so that it expires after 120 seconds and is not overwritten if a code already exists. Check the TTL, then verify the code by reading it in a way that also deletes it (so it can't be reused).
Expected: OK, (integer) 120, "482913", then (nil) when someone tries to use it a second time.
SET otp:5551234 482913
TTL otp:5551234redis> SET otp:5551234 482913
OK
redis> TTL otp:5551234
(integer) -1
Show solution
SET otp:5551234 482913 EX 120 NX
TTL otp:5551234
GETDEL otp:5551234
GETDEL otp:55512343. Recent searches
Keep each user's 3 most recent searches, newest first. The user searches for redis, lists, streams and lua, in that order.
Expected final list: lua, streams, lists.
LPUSH recent:user:7 redis
LPUSH recent:user:7 lists
# TODO: add the other two searches and keep only three entries
LRANGE recent:user:7 0 -1redis> LPUSH recent:user:7 redis
(integer) 1
redis> LPUSH recent:user:7 lists
(integer) 2
redis> LRANGE recent:user:7 0 -1
1) "lists"
2) "redis"
Show solution
LPUSH recent:user:7 redis
LTRIM recent:user:7 0 2
LPUSH recent:user:7 lists
LTRIM recent:user:7 0 2
LPUSH recent:user:7 streams
LTRIM recent:user:7 0 2
LPUSH recent:user:7 lua
LTRIM recent:user:7 0 2
LRANGE recent:user:7 0 -1Trimming after every push keeps the list bounded at all times. In code you would send the LPUSH and LTRIM together in a pipeline or transaction.
4. Common interests
Mai likes music, hiking, chess; Binh likes chess, cooking, music. Find the interests they share (how many and which), and the interests Mai has that Binh doesn't.
Expected: 2 shared interests (music, chess), and hiking for Mai only.
SADD likes:mai music hiking chess
SADD likes:binh chess cooking music
# TODO: count and list the shared interests, then Mai's ownredis> SADD likes:mai music hiking chess
(integer) 3
redis> SADD likes:binh chess cooking music
(integer) 3
Show solution
SADD likes:mai music hiking chess
SADD likes:binh chess cooking music
SINTERCARD 2 likes:mai likes:binh
SINTER likes:mai likes:binh
SDIFF likes:mai likes:binhThe order in which SINTER lists several members is not guaranteed.
5. User profile
Create user 42 with name Linh, city Da Nang and logins = 0 in one command. Record two logins, change the city to Hue, and read name, city and logins in one command.
Expected final reply: "Linh", "Hue", "2".
HSET user:42 name Linh
HGET user:42 nameredis> HSET user:42 name Linh
(integer) 1
redis> HGET user:42 name
"Linh"
Show solution
HSET user:42 name Linh city "Da Nang" logins 0
HINCRBY user:42 logins 1
HINCRBY user:42 logins 1
HSET user:42 city Hue
HMGET user:42 name city logins6. Top players
Players earn points during a game: ada +50, linus +30, ada +20, grace +90, linus +45. Show the top 2 with their scores, and ada's position counted from 1.
Expected: grace 90, linus 75; ada is 3rd (ZREVRANK returns 2).
ZINCRBY game 50 ada
# TODO: the other point events, the top 2, ada's rankredis> ZINCRBY game 50 ada
"50"
Show solution
ZINCRBY game 50 ada
ZINCRBY game 30 linus
ZINCRBY game 20 ada
ZINCRBY game 90 grace
ZINCRBY game 45 linus
ZRANGE game 0 1 REV WITHSCORES
ZREVRANK game adaRanks are 0-based, so add 1 before showing them.
7. Weekly unique visitors
Monday's visitors were u1 u2 u3, Tuesday's u2 u4, Wednesday's u1 u5 u6. Count unique visitors per day and for the whole period, storing the weekly total in uv:week.
Expected: 3, 2, 3 per day, and 6 for the week.
PFADD uv:mon u1 u2 u3
PFCOUNT uv:mon
# TODO: the other days and the weekly countredis> PFADD uv:mon u1 u2 u3
(integer) 1
redis> PFCOUNT uv:mon
(integer) 3
Show solution
PFADD uv:mon u1 u2 u3
PFADD uv:tue u2 u4
PFADD uv:wed u1 u5 u6
PFCOUNT uv:mon
PFCOUNT uv:tue
PFCOUNT uv:wed
PFMERGE uv:week uv:mon uv:tue uv:wed
PFCOUNT uv:week8. Safe transfer
Move 40 credits from credits:a (100) to credits:b (5) so that no client can see the intermediate state. Then write a Lua script that only performs the transfer when the sender has enough credits, and try to move 200.
Expected: balances 60 and 45, then the error not enough credits, and the balances are unchanged.
MSET credits:a 100 credits:b 5
# TODO: a MULTI/EXEC transfer of 40, then the Lua version with 200
MGET credits:a credits:bredis> MSET credits:a 100 credits:b 5
OK
redis> MGET credits:a credits:b
1) "100"
2) "5"
Show solution
MSET credits:a 100 credits:b 5
MULTI
DECRBY credits:a 40
INCRBY credits:b 40
EXEC
EVAL "if tonumber(redis.call('GET', KEYS[1])) < tonumber(ARGV[1]) then return redis.error_reply('not enough credits') end redis.call('DECRBY', KEYS[1], ARGV[1]) return redis.call('INCRBY', KEYS[2], ARGV[1])" 2 credits:a credits:b 200
MGET credits:a credits:bMULTI/EXEC alone cannot check the balance first, because queued commands can't see each other's results; the script can.
9. Order events
Add three order events with IDs 1-1, 2-1, 3-1 to the stream orders. Create the consumer group billing reading from the start, let consumer b1 read two events and acknowledge only the first, then show the pending summary.
Expected: one entry (2-1) pending for b1.
XADD orders 1-1 order 1001
XADD orders 2-1 order 1002
XADD orders 3-1 order 1003
# TODO: group, read two, ack one, pending summaryredis> XADD orders 1-1 order 1001
"1-1"
redis> XADD orders 2-1 order 1002
"2-1"
redis> XADD orders 3-1 order 1003
"3-1"
Show solution
XADD orders 1-1 order 1001
XADD orders 2-1 order 1002
XADD orders 3-1 order 1003
XGROUP CREATE orders billing 0
XREADGROUP GROUP billing b1 COUNT 2 STREAMS orders >
XACK orders billing 1-1
XPENDING orders billingTest yourself
Which pair of commands keeps a list at a maximum of 50 entries, newest first?
- RPUSH + LTRIM key 0 49
- LPUSH + LTRIM key 0 49
- LPUSH + LREM key 50
- LPUSH + LLEN
Which command reads a one-time code and deletes it in one step?
- GET
- GETDEL
- GETEX
- DEL
Why can't MULTI/EXEC alone implement 'transfer only if the balance is enough'?
- MULTI does not support DECRBY
- Queued commands run only at EXEC, so you cannot branch on a value read inside the transaction
- EXEC always fails
- Transactions are not atomic