Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 42 ยท Practice and Review

Practice Exercises with Solutions

Twelve graded Redis exercises on strings, expiry, lists, hashes, sets, sorted sets, transactions, rate limiting, caching and locks, with runnable code and solutions.

You learn Redis by sending commands and watching the replies, so this page gives you twelve small tasks to do exactly that. They run from beginner to advanced and cover every core data type, expiry, transactions and the patterns you will meet in real applications: counters, rate limits, caches and locks.

Each group of three exercises shares one editor. The editor contains your starting functions at the top (exercise1, exercise2, ...) and a JavaScript emulator below the line that says "do not edit". Redis itself cannot run on this site, so the emulator (a small class called MiniRedis) executes the same command semantics: the data types, expiry with a fake clock, transactions and sorted sets. It models the commands, not the network or real performance, and the real redis-cli syntax you type is the same. Use run("COMMAND args") to print a command and its reply in redis-cli style.

How to practice well:

  • Try first, peek later. Open a solution only after an honest attempt.
  • Run often. Each exercise prints its replies, and the solution block shows the output to compare with.
  • Check the lessons. Every group names the lesson it practises. The cheat sheet is a good tab to keep open.

The emulator splits commands on spaces, so values here never contain spaces. Real drivers pass each argument separately, so spaces are fine there. Redis also keeps set members in no guaranteed order; the emulator sorts them so the output stays stable.

Group A: Strings, counters and expiry

These practice strings and counters and keys and expiry.

1. Page view counter (Beginner)

Count three page views of the home page on the key views:home with INCR, add a bulk import of 10 views with INCRBY, and read the total with GET. Use run("...") so every reply is printed.

2. First claim wins (Beginner)

A coupon may be claimed by one user only. Let alice claim claim:SPRING25 with a single SET command that only succeeds when the key does not exist, then let bob try the same, and finally read who owns the claim.

3. Session that expires (Beginner)

Store session:42 with the value token-abc and a time to live of 30 seconds in one command. Print its TTL, advance the fake clock by 10 seconds with r.tick(10) and print the TTL again. Then advance by 25 more seconds and show what GET, TTL and EXISTS reply.

JS Exercises 1 to 3: Strings, counters and expiry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Solutions for exercises 1 to 3

Show solution 1: Page view counter
JavaScript
function exercise1() {
  run("INCR views:home");
  run("INCR views:home");
  run("INCR views:home");
  run("INCRBY views:home 10");
  run("GET views:home");
}

Output:

TEXT
--- Exercise 1: Page view counter ---
> INCR views:home
(integer) 1
> INCR views:home
(integer) 2
> INCR views:home
(integer) 3
> INCRBY views:home 10
(integer) 13
> GET views:home
"13"

INCR creates a missing key at 0 and then adds one, so you never need to initialise a counter. Redis stores the number as a string, which is why GET replies with "13" in quotes while INCR replies with an integer.

Show solution 2: First claim wins
JavaScript
function exercise2() {
  run("SET claim:SPRING25 alice NX");
  run("SET claim:SPRING25 bob NX");
  run("GET claim:SPRING25");
}

Output:

TEXT
--- Exercise 2: First claim wins ---
> SET claim:SPRING25 alice NX
OK
> SET claim:SPRING25 bob NX
(nil)
> GET claim:SPRING25
"alice"

SET key value NX is a one-command check-and-set: Redis tests for the key and writes it inside one atomic step, so two clients cannot both win. The losing call replies with nil.

Show solution 3: Session that expires
JavaScript
function exercise3() {
  run("SET session:42 token-abc EX 30");
  run("TTL session:42");
  r.tick(10);
  run("TTL session:42");
  r.tick(25);
  run("GET session:42");
  run("TTL session:42");
  run("EXISTS session:42");
}

Output:

TEXT
--- Exercise 3: Session that expires ---
> SET session:42 token-abc EX 30
OK
> TTL session:42
(integer) 30
> TTL session:42
(integer) 20
> GET session:42
(nil)
> TTL session:42
(integer) -2
> EXISTS session:42
(integer) 0

Setting the value and the expiry in one SET ... EX avoids the gap that two separate commands would leave. After the key expires, TTL replies -2 (no such key). A TTL of -1 would mean the key exists with no expiry.

Group B: Lists, hashes and sets

These practice lists, hashes and sets.

4. Capped activity feed (Beginner)

Keep only the three newest events of a user in the list feed:7. Push the events login, view, edit, comment and logout one at a time with LPUSH (newest at the head), trimming after every push so the list never holds more than three items. Finally print the list with LRANGE.

5. User profile hash (Beginner)

Create the hash user:7 with the fields name = Mina, plan = free and logins = 0 in one HSET. Record two logins with HINCRBY, upgrade the plan to pro, and print the whole hash with HGETALL.

6. Shared interests (Intermediate)

Ana likes redis, php and go; Ben likes go, python and redis. Store them in the sets interests:ana and interests:ben, print the interests they share with SINTER, count Ana's interests with SCARD and test whether Ana likes python with SISMEMBER.

JS Exercises 4 to 6: Lists, hashes and sets

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Solutions for exercises 4 to 6

Show solution 4: Capped activity feed
JavaScript
function exercise4() {
  const events = ["login", "view", "edit", "comment", "logout"];
  for (const e of events) {
    r.cmd("LPUSH feed:7 " + e);
    r.cmd("LTRIM feed:7 0 2");
  }
  run("LLEN feed:7");
  run("LRANGE feed:7 0 -1");
}

Output:

TEXT
--- Exercise 4: Capped activity feed ---
> LLEN feed:7
(integer) 3
> LRANGE feed:7 0 -1
1) "logout"
2) "comment"
3) "edit"

LPUSH followed by LTRIM key 0 N-1 is the classic capped list. In real code you would send both commands in one transaction or pipeline so the list is never seen over its limit.

Show solution 5: User profile hash
JavaScript
function exercise5() {
  run("HSET user:7 name Mina plan free logins 0");
  run("HINCRBY user:7 logins 1");
  run("HINCRBY user:7 logins 1");
  run("HSET user:7 plan pro");
  run("HGETALL user:7");
}

Output:

TEXT
--- Exercise 5: User profile hash ---
> HSET user:7 name Mina plan free logins 0
(integer) 3
> HINCRBY user:7 logins 1
(integer) 1
> HINCRBY user:7 logins 1
(integer) 2
> HSET user:7 plan pro
(integer) 0
> HGETALL user:7
1) "name"
2) "Mina"
3) "plan"
4) "pro"
5) "logins"
6) "2"

HSET replies with the number of fields that were new: 3 the first time, 0 when it only updates plan. HGETALL returns a flat list of field, value, field, value. Each field is its own counter, so HINCRBY needs no read-modify-write.

Show solution 6: Shared interests
JavaScript
function exercise6() {
  run("SADD interests:ana redis php go");
  run("SADD interests:ben go python redis");
  run("SINTER interests:ana interests:ben");
  run("SCARD interests:ana");
  run("SISMEMBER interests:ana python");
}

Output:

TEXT
--- Exercise 6: Shared interests ---
> SADD interests:ana redis php go
(integer) 3
> SADD interests:ben go python redis
(integer) 3
> SINTER interests:ana interests:ben
1) "go"
2) "redis"
> SCARD interests:ana
(integer) 3
> SISMEMBER interests:ana python
(integer) 0

A set stores each member once and answers membership questions fast. SINTER builds the overlap on the server. Real Redis returns set members in no promised order (the emulator sorts them to keep the output stable).

Group C: Sorted sets and transactions

These practice sorted sets and transactions.

7. Leaderboard top three (Intermediate)

Add the players ann (120), bo (90), cy (150) and di (70) to the sorted set board with one ZADD. Give bo 40 more points with ZINCRBY. Print the top three with their scores, highest first.

8. Players around me (Intermediate)

The board board holds cy 150, bo 130, ann 120, ed 100 and di 70. Find the 0-based rank of ann counted from the top with ZREVRANK, then print ann together with the player directly above and the player directly below. Compute the range from the rank in JavaScript (r.cmd returns the number).

9. A transfer, and no rollback (Advanced)

Set balance:alice to 100 and balance:bob to 20. Move 30 from Alice to Bob in one transaction with r.multi([...]) and print the replies with show(). Then store the text hello in note and run a second transaction that contains INCR note followed by INCRBY balance:bob 5. Print its replies and Bob's balance to see whether the second command ran.

JS Exercises 7 to 9: Sorted sets and transactions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Solutions for exercises 7 to 9

Show solution 7: Leaderboard top three
JavaScript
function exercise7() {
  run("ZADD board 120 ann 90 bo 150 cy 70 di");
  run("ZINCRBY board 40 bo");
  run("ZRANGE board 0 2 REV WITHSCORES");
}

Output:

TEXT
--- Exercise 7: Leaderboard top three ---
> ZADD board 120 ann 90 bo 150 cy 70 di
(integer) 4
> ZINCRBY board 40 bo
"130"
> ZRANGE board 0 2 REV WITHSCORES
1) "cy"
2) "150"
3) "bo"
4) "130"
5) "ann"
6) "120"

ZADD takes score first, then member. ZRANGE ... REV WITHSCORES lists from the highest score and interleaves each member with its score. Scores come back as strings, because they are doubles.

Show solution 8: Players around me
JavaScript
function exercise8() {
  r.cmd("ZADD board 150 cy 130 bo 120 ann 100 ed 70 di");
  const rank = r.cmd("ZREVRANK board ann");
  console.log("rank of ann:", rank);
  const from = Math.max(rank - 1, 0);
  run(`ZRANGE board ${from} ${rank + 1} REV`);
}

Output:

TEXT
--- Exercise 8: Players around me ---
rank of ann: 2
> ZRANGE board 1 3 REV
1) "bo"
2) "ann"
3) "ed"

An around-me query is two steps: ask for the rank, then read a small range around it. Clamp the lower bound at 0 so the top player does not ask for a negative index (negative indexes count from the end in Redis). Use ZREVRANK for a leaderboard where bigger scores win.

Show solution 9: A transfer, and no rollback
JavaScript
function exercise9() {
  run("SET balance:alice 100");
  run("SET balance:bob 20");
  console.log(show(r.multi(["INCRBY balance:alice -30", "INCRBY balance:bob 30"])));
  run("SET note hello");
  console.log(show(r.multi(["INCR note", "INCRBY balance:bob 5"])));
  run("GET balance:bob");
}

Output:

TEXT
--- Exercise 9: A transfer, and no rollback ---
> SET balance:alice 100
OK
> SET balance:bob 20
OK
1) (integer) 70
2) (integer) 50
> SET note hello
OK
1) (error) ERR value is not an integer or out of range
2) (integer) 55
> GET balance:bob
"55"

The first transaction replies with one integer per command. In the second, INCR note fails at run time because hello is not a number, yet INCRBY balance:bob 5 still runs: Redis has no rollback, so Bob ends at 55. If the failing command had been a typo caught at queue time, EXEC would have refused the whole transaction instead.

Group D: Patterns: rate limit, cache and lock

These combine commands into the patterns from Cache Invalidation and Stampedes and the other application lessons.

10. Fixed-window rate limiter (Intermediate)

Write allow(user) that permits at most 3 requests per user in a 60 second window. Count requests with INCR on rate:<user> and start the 60 second timer with EXPIRE when the counter is created. Call it five times for mina, advance the clock by 61 seconds and call it once more.

11. Cache-aside with a TTL (Intermediate)

Write getUser(id): look in the cache key user:<id> first; on a miss read the fake database (db), store the JSON in the cache with a 60 second TTL and return it. Count how often the database is read. Call it twice, advance the clock by 61 seconds and call it again.

12. A lock that only its owner releases (Advanced)

Write acquire(token), which takes the lock lock:report with a 10 second expiry only if nobody holds it, and release(token), which deletes the lock only if its value is still your token. Let worker A acquire, worker B fail to acquire, B try to release (and be refused), A release, and B acquire.

JS Exercises 10 to 12: Patterns: rate limit, cache and lock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Solutions for exercises 10 to 12

Show solution 10: Fixed-window rate limiter
JavaScript
function exercise10() {
  const allow = (user) => {
    const key = "rate:" + user;
    const count = r.cmd("INCR " + key);
    if (count === 1) r.cmd("EXPIRE " + key + " 60");
    return count <= 3;
  };
  for (let i = 1; i <= 5; i++) console.log("request", i, allow("mina") ? "allowed" : "blocked");
  r.tick(61);
  console.log("after 61 seconds:", allow("mina") ? "allowed" : "blocked");
}

Output:

TEXT
--- Exercise 10: Fixed-window rate limiter ---
request 1 allowed
request 2 allowed
request 3 allowed
request 4 blocked
request 5 blocked
after 61 seconds: allowed

The counter and its window both come from one key: when it expires, the next INCR starts a fresh window. There is a weak spot: if the client crashes between INCR and EXPIRE, the key never expires. Production code sends both in a Lua script or a transaction. Fixed windows also let a burst straddle two windows; token buckets smooth that out.

Show solution 11: Cache-aside with a TTL
JavaScript
function exercise11() {
  let dbReads = 0;
  const db = (id) => {
    dbReads++;
    return { id, name: "user" + id };
  };
  const getUser = (id) => {
    const cached = r.cmd("GET user:" + id);
    if (cached !== null) return JSON.parse(cached);
    const user = db(id);
    r.cmd("SET user:" + id + " " + JSON.stringify(user) + " EX 60");
    return user;
  };
  console.log(JSON.stringify(getUser(1)), "db reads:", dbReads);
  console.log(JSON.stringify(getUser(1)), "db reads:", dbReads);
  r.tick(61);
  console.log(JSON.stringify(getUser(1)), "db reads:", dbReads);
}

Output:

TEXT
--- Exercise 11: Cache-aside with a TTL ---
{"id":1,"name":"user1"} db reads: 1
{"id":1,"name":"user1"} db reads: 1
{"id":1,"name":"user1"} db reads: 2

This is cache-aside: the application checks the cache, falls back to the source of truth, and fills the cache with a TTL so stale data cannot live forever. The JSON has no spaces because the emulator splits commands on spaces; real drivers pass arguments separately.

Show solution 12: A lock that only its owner releases
JavaScript
function exercise12() {
  const acquire = (token) => r.cmd("SET lock:report " + token + " NX EX 10") === "OK";
  const release = (token) => {
    if (r.cmd("GET lock:report") !== token) return false;
    r.cmd("DEL lock:report");
    return true;
  };
  console.log("A acquires:", acquire("tokenA"));
  console.log("B acquires:", acquire("tokenB"));
  console.log("B releases:", release("tokenB"));
  console.log("A releases:", release("tokenA"));
  console.log("B acquires:", acquire("tokenB"));
}

Output:

TEXT
--- Exercise 12: A lock that only its owner releases ---
A acquires: true
B acquires: false
B releases: false
A releases: true
B acquires: true

SET NX EX takes the lock and its expiry atomically, and the unique token stops one worker from deleting another worker's lock. The release above has a race (the lock could expire between the GET and the DEL), which is why real code does the compare and delete in one Lua script.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which single command makes a key only if it does not exist yet, so that two clients cannot both win?

    SET with NX tests and writes in one atomic step. GET followed by SET leaves a gap in which another client can write.
  2. 2. A transaction queues INCR on a text value and then another valid command. What happens at EXEC?

    Redis has no rollback. A run-time error appears only in the slot of the command that failed.
  3. 3. A key was set with EX 30. Ten seconds later you run SET on the same key without any option. What is its TTL?

    A plain SET replaces the value and clears the expiry. Use KEEPTTL to keep it.
  4. 4. Why does the fixed-window rate limiter in exercise 10 have a weak spot?

    The two commands are separate. Sending them in a transaction or a Lua script removes the gap.
  5. 5. In a leaderboard where higher scores win, which command gives the rank counted from the top?

    ZRANK counts from the lowest score, ZREVRANK from the highest.

Summary

  • Counters, flags and claims are one-liners: INCR, SET ... NX and SET ... EX are atomic, so they need no extra locking.
  • Capped lists (LPUSH + LTRIM), hashes for records, sets for membership and sorted sets for rankings cover most data modelling.
  • Transactions queue commands and run them uninterrupted, but they never roll back.
  • Rate limits, caches and locks are small combinations of these commands; the weak spots (non-atomic pairs) are fixed with Lua scripts.
  • The emulator models command semantics only; always test timing and load against a real server.

Next, test yourself on the theory with Redis Interview Questions.