Build a Redis-compatible server one command at a time. Start with a TCP connection and a PING reply, then choose extensions such as lists, streams, replication or transactions.

Set up your project

Choose a starter for your language. C · Clojure · C++ · Crystal · C# · Dart · Elixir · Gleam · Go · Haskell · Java · JavaScript · Kotlin · OCaml · Odin · PHP · Python · Ruby · Rust · Scala · Swift · TypeScript · Zig.

Use the examples in each stage to check your implementation locally. CodeCrafters operates its hosted runner separately.

Contents

Core project

1. Bind to a port

Redis servers communicate over TCP, a protocol that enables reliable data exchange between clients and servers. In this stage, you’ll implement a TCP server that listens on port 6379, just like the real Redis.

Original stage jm1

2. Respond to PING

In this stage, you’ll implement the Redis PING command.

What is PING?

Redis clients talk to Redis servers by sending commands and receiving responses.

For example:

redis> PING                  # client sends a PING command
"PONG"                       # server replies with PONG

redis> SET name Alice        # store the value "Alice" under the key "name"
OK                           # server confirms success

PING is the simplest Redis command. It’s used to check whether a Redis server is alive and responding.

When a Redis server replies to PING, the raw response it sends over the network is actually +PONG\r\n, which is the string PONG encoded using RESP, a format Redis uses to exchange messages between clients and servers.

For this stage, your task is to simply hardcode a +PONG\r\n response, regardless of the incoming command.

You’ll learn more about RESP and how input command parsing works in future stages.

Original stage rg2

3. Respond to multiple PINGs

In this stage, you’ll respond to multiple PING commands sent by the same connection.

Handling Multiple Commands

A Redis server starts to listen for the next command as soon as it’s done responding to the previous one. This allows Redis clients to send multiple commands using the same connection.

For this stage, your server should run a loop that continuously reads commands and sends responses back through the same connection. Since we’re only dealing with the PING command for now, your program can run a loop that reads input and responds with +PONG\r\n.

For JavaScript

In most languages, you’d need to write specific code to run this loop on your server. In JavaScript, however, if you’re listening to the data event, this should be automatically handled for you. It is very likely that the code you used in previous stages will pass this stage without any changes!

For TypeScript

In most languages, you’d need to write specific code to run this loop on your server. In JavaScript, however, if you’re listening to the data event, this should be automatically handled for you. It is very likely that the code you used in previous stages will pass this stage without any changes!

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send multiple PING commands using the same connection.

For example, it might send:

$ echo -e "PING\nPING" | redis-cli

The tester will expect to receive a +PONG\r\n response for each command sent.

Notes
  • The exact bytes your program will receive won’t be just PING. You’ll receive something like this: *1\r\n$4\r\nPING\r\n, which is the Redis protocol encoding of the PING command.
  • Just like the previous stage, you can hardcode +PONG\r\n as the response for this stage. We’ll get to parsing client input in later stages.
  • The tester will send the PING commands using the same connection. We’ll get to handling multiple connections in later stages.

Original stage wy1

4. Handle concurrent clients

In this stage, you’ll add support for multiple concurrent clients.

Handling Multiple Clients

In addition to handling multiple commands from the same client, Redis servers can also handle multiple clients at once.

For JavaScript

In most languages, you’d need to either use threads or implement an Event Loop to do this. In JavaScript, however, since the concurrency model itself is based on an event loop, most standard library functions are designed to support this kind of concurrent behaviour out of the box. It is very likely that the code you had for previous stages will pass this stage without any changes!

For TypeScript

In most languages, you’d need to either use threads or implement an Event Loop to do this. In JavaScript, however, since the concurrency model itself is based on an event loop, most standard library functions are designed to support this kind of concurrent behaviour out of the box. It is very likely that the code you had for previous stages will pass this stage without any changes!

For languages other than JavaScript

For languages other than TypeScript

To implement this, you’ll need to either use threads or, if you’re feeling adventurous, implement an Event Loop (like the official Redis implementation does).

Tests

The tester will execute your program like this:

$ ./your_program.sh

It’ll then send two PING commands concurrently using two different connections:

# These two will be sent concurrently so that we can test your server's ability to handle concurrent clients.
$ redis-cli PING
$ redis-cli PING

The tester will expect to receive two separate +PONG\r\n responses.

Notes
  • Since the tester client only sends the PING command at the moment, it’s okay to ignore what the client sends and hardcode a response. We’ll get to parsing client input in later stages.

Original stage zu2

5. Implement the ECHO command

In this stage, you’ll add support for the ECHO command.

The ECHO Command

The ECHO command is used for testing and debugging, similar to PING.

$ redis-cli PING # The command you implemented in the previous stages
PONG
$ redis-cli ECHO hey # The command you'll implement in this stage
hey

It accepts a single argument and sends it back as a RESP bulk string.

To pass this stage, your program will need to:

  • Parse the client’s input to extract the argument from the ECHO command
  • Then encode that argument as a bulk string for the response
Tests

The tester will execute your program like this:

$ ./your_program.sh

It’ll then send an ECHO command with an argument to your server:

$ redis-cli ECHO hey

The exact bytes you’ll receive will be a RESP Array that looks something like *2\r\n$4\r\nECHO\r\n$3\r\nhey\r\n. This is the RESP encoding of ["ECHO", "hey"].

The tester will expect to receive $3\r\nhey\r\n as a response. That’s the string hey encoded as a bulk string.

Notes
  • We highly recommend you implement a proper RESP parser at this stage. It’ll come in handy in later stages.
  • Redis command names are case-insensitive, so ECHO, echo, and EcHo are all valid commands.
  • The tester will send a random string as an argument to the ECHO command, so you won’t be able to hardcode the response to pass this stage.

Original stage qq0

6. Implement the SET & GET commands

In this stage, you’ll add support for the SET & GET commands.

The SET Command

The SET command is used to set a key to a value. For example, a client can set a key foo to a value bar like this:

$ redis-cli SET foo bar
OK

The server then responds with OK (as a RESP simple string) to confirm that the action was successful.

The SET command supports a number of extra options like EX (expiry time in seconds), PX (expiry time in milliseconds), and more. We won’t cover these extra options in this stage. We’ll get to them in later stages.

The GET Command

The GET command is used to retrieve the value of a key. For example, to retrieve the value for the key foo:

$ redis-cli GET foo
bar

The server responds with the value bar encoded as a RESP bulk string. If the key doesn’t exist, the server responds with a special null bulk string ($-1\r\n).

Tests

The tester will execute your program like this:

./your_program.sh

It’ll then send a SET command to your server:

$ redis-cli SET foo bar

The tester will expect to receive +OK\r\n as a response. That’s the string OK encoded as a simple string.

This command will be followed by a GET command:

$ redis-cli GET foo

The tester will expect to receive $3\r\nbar\r\n as a response. That’s the string bar encoded as a bulk string.

Notes
  • If you implemented a proper RESP parser in previous stages, you should be able to reuse it in this stage.
  • Just like previous stages, the keys and values will be random, so you won’t be able to hardcode the response to pass this stage.
  • If a key doesn’t exist, the GET command should return a null bulk string ($-1\r\n). We won’t explicitly test this in this stage, but you’ll need it in later stages.

Original stage la7

7. Expiry

In this stage, you’ll add support for setting a key with an expiry.

SET Command Options

The SET command can accept optional arguments to modify its behaviour.

For example, here are a few options you can use with SET:

# Set a key with a 10-second expiry
$ redis-cli SET mykey value EX 10
OK

# Set a key with a 1000-millisecond expiry
$ redis-cli SET mykey value PX 1000
OK
The PX Option

The PX option is used to set a key’s expiry time in milliseconds. After the key expires, it’s no longer accessible.

For example, a client can set a key with an expiry like this:

$ redis-cli SET foo bar PX 100
OK

This command sets the key foo to the value bar with an expiry of 100 milliseconds.

After the key expires, a GET command for that key should return a null bulk string ($-1\r\n).

$ redis-cli GET foo
(nil)

For Haskell

The time package is available to use as a dependency.

Tests

The tester will execute your program like this:

$ ./your_program.sh

Next, it will send a SET command to your server to set a key with an expiry:

$ redis-cli SET foo bar PX 100

Immediately after that, it will send a GET command to retrieve the value of the key:

$ redis-cli GET foo

The tester will expect to receive $3\r\nbar\r\n as a response. That’s the string bar encoded as a bulk string.

After waiting for the key to expire, it will send another GET command:

$ sleep 0.2 && redis-cli GET foo

The tester will expect the response to be a null bulk string ($-1\r\n).

Notes
  • Just like command names, command arguments are also case-insensitive. So PX, px, and pX are all valid.
  • The keys, values, and expiry times used in the tests will be random, so you won’t be able to hardcode a response to pass this stage.

Original stage yz1

Back to contents

Lists

1. Create a list

In this stage, you’ll add support for creating a new list using the RPUSH command.

The RPUSH Command

The RPUSH command is used to append elements to a list. If the list doesn’t exist, it is created first.

Example usage:

# Creating a new list with a single element
> RPUSH list_key "foo"
(integer) 1

# Appending a single element to an existing list
> RPUSH list_key "bar"
(integer) 2

The return value is the number of elements in the list after appending. This value is encoded as a RESP integer.

Tests

The tester will execute your program like this:

./your_program.sh

It will then send the following command to your program:

$ redis-cli RPUSH list_key "element"

The tester will verify that the response to the command is :1\r\n, which is 1 (the number of elements in the list), encoded as a RESP integer.

Notes
  • In this stage, you’ll only need to handle creating a new list with a single element. We’ll get to handling RPUSH for existing lists and multiple elements in later stages.

Original stage mh6

2. Append an element

In this stage, you’ll add support for RPUSH to append a single element to an existing list.

Appending to an Existing List

When a client sends RPUSH on a list that already exists, the new element is appended to the end of the list.

$ redis-cli RPUSH list_key "element1"
(integer) 1
$ redis-cli RPUSH list_key "element2"
(integer) 2

The server then returns the new length of the list as a RESP integer.

Tests

The tester will execute your program like this:

./your_program.sh

It will then send multiple RPUSH commands on the same list:

$ redis-cli RPUSH list_key "element1"
# Expect: (integer) 1 → encoded as :1\r\n

$ redis-cli RPUSH list_key "element2"
# Expect: (integer) 2 → encoded as :2\r\n

In each case, the tester will expect the response to be the length of the list encoded as a RESP integer.

Notes
  • You’ll need to check if a list already exists for the given key and append to it.

Original stage tn7

3. Append multiple elements

In this stage, you’ll add support for appending multiple elements in a single RPUSH command.

RPUSH with multiple elements

The RPUSH command supports adding multiple elements to a list at once.

# Creating a new list with multiple elements
> RPUSH another_list "bar" "baz"
(integer) 2

# Appending multiple elements to an existing list
> RPUSH another_list "foo" "bar" "baz"
(integer) 5

The response to each command is the new length of the list returned as a RESP integer.

Tests

The tester will execute your program like this:

./your_program.sh

It will then send multiple RPUSH commands, each including more than one element to append to the list.

$ redis-cli RPUSH list_key "element1" "element2" "element3"
# Expect: (integer) 3 → encoded as :3\r\n

$ redis-cli RPUSH list_key "element4" "element5"
# Expect: (integer) 5 → encoded as :5\r\n

In each case, the tester will expect the response to be the length of the list encoded as a RESP integer.

Notes
  • RPUSH accepts multiple elements even when creating a new list, not only when appending to an existing list.

Original stage lx4

4. List elements (positive indexes)

In this stage, you will add support for listing the elements of a list using the LRANGE command.

The LRANGE command

The LRANGE command is used to retrieve elements from a list using a start index and a stop index.

The index of the first element is 0. The stop index is inclusive, meaning the element at that index is included in the response.

For example:

# Create a list with 5 items
> RPUSH list_key "a" "b" "c" "d" "e"
(integer) 5

# List first 2 items 
> LRANGE list_key 0 1
1) "a"
2) "b"

# List items from index 2 to 4
> LRANGE list_key 2 4
1) "c"
2) "d"
3) "e"

The LRANGE command has several behaviors to keep in mind:

  • If the list doesn’t exist, an empty array is returned.
  • If the start index is greater than or equal to the list’s length, an empty array is returned.
  • If the stop index is greater than or equal to the list’s length, the stop index is treated as the last element.
  • If the start index is greater than the stop index, an empty array is returned.
Tests

The tester will execute your program like this:

./your_program.sh

It will then create a new list with multiple elements:

$ redis-cli RPUSH list_key "a" "b" "c" "d" "e"

After that, the tester will send your program a series of LRANGE commands. For each command, it will expect the response to be a RESP array or an empty array (*0\r\n), depending on the test case.

As an example, the tester might send your program a command like this:

$ redis-cli LRANGE list_key 0 2
# Expect RESP Encoded Array: ["a", "b", "c"]

It will expect the response to be a RESP array ["a", "b", "c"], which would look like this:

*3\r\n
$1\r\n
a\r\n
$1\r\n
b\r\n
$1\r\n
c\r\n
Notes
  • In this stage, you will only implement LRANGE with non-negative indexes. We will get to handling LRANGE for negative indexes in later stages.
  • If a list doesn’t exist, LRANGE should respond with an empty RESP array (*0\r\n).

Original stage sf6

5. List elements (negative indexes)

In this stage, you will add support for negative indexes for the LRANGE command.

LRANGE with negative indexes

The LRANGE command can also use negative indexes.

A negative index is an offset from the end of the list: -1 refers to the last element, -2 refers to the second-to-last, and so on.

For example:

# Create a list with 5 items
> RPUSH list_key "a" "b" "c" "d" "e"
(integer) 5

# List the last 2 items 
> LRANGE list_key -2 -1
1) "d"
2) "e"

# List all items except the last 2
> LRANGE list_key 0 -3
1) "a"
2) "b"
3) "c"

If a negative index is out of range (e.g., -6 on a list of length 5), it should be treated as 0 (the start of the list).

Tests

The tester will execute your program like this:

./your_program.sh

It will then create a new list with multiple elements.

$ redis-cli RPUSH list_key "a" "b" "c" "d" "e"

The tester will then send your program a series of LRANGE commands with one or more negative indexes.

For example, the tester might send you this command:

$ redis-cli LRANGE list_key 2 -1

In this case, the tester expects the response to be the array ["c", "d", "e"], which is RESP encoded as:

*3\r\n
$1\r\n
c\r\n
$1\r\n
d\r\n
$1\r\n
e\r\n

Original stage ri1

6. Prepend elements

In this stage, you’ll add support for the LPUSH command, which prepends elements to a list.

The LPUSH Command

The LPUSH command is similar to RPUSH, except that it inserts elements at the start of the list instead of the end. If the list doesn’t exist, it gets created first before prepending the elements.

For example:

> LPUSH list_key "a" "b" "c"
(integer) 3

Even though the elements were listed as “a”, “b”, “c”, they are added to the list in reverse order, so the list becomes ["c", "b", "a"].

> LRANGE list_key 0 -1
1) "c"
2) "b"
3) "a"
Tests

The tester will execute your program like this:

./your_program.sh

It will then send a series of LPUSH commands. For each command, the tester will expect the response to be the list’s length as a RESP integer.

$ redis-cli
> LPUSH list_key "c"
# Expect: (integer) 1

> LPUSH list_key "b" "a"
# Expect: (integer) 3

It’ll also use the LRANGE command to verify that elements are inserted in the correct order.

> LRANGE list_key 0 -1
# Expect RESP Encoded Array: ["a", "b", "c"]

Original stage gu5

7. Query list length

In this stage, you’ll add support for querying the length of a list using the LLEN command.

The LLEN Command

The LLEN command is used to get the length of a list. The result is encoded as a RESP integer.

For example:

# Create a new list with 4 items
> RPUSH list_key "a" "b" "c" "d"
(integer) 4

# Get the length of the new list
> LLEN list_key
(integer) 4

If the list doesn’t exist, the server returns 0 as a RESP integer.

Tests

The tester will execute your program like this:

./your_program.sh

It will then create a list with a random number of elements using RPUSH.

$ redis-cli
> RPUSH list_key <random number of elements>

Next, it will send an LLEN command for the newly created list.

> LLEN list_key
# Expect: list_length (RESP Encoded Integer)

The tester will expect the response to be the length of the list encoded as a RESP integer.

The tester will also verify the response for a non-existent list:

> LLEN missing_list_key
# Expect:  (integer) 0

In this case, your program should respond with 0, which is encoded as :0\r\n.

Original stage fv6

8. Remove an element

In this stage, you’ll add support for removing the first element of a list using the LPOP command.

The LPOP Command

The LPOP command removes and returns the first element of a list.

Here’s an example:

> RPUSH list_key "a" "b" "c" "d"
(integer) 4

> LPOP list_key
"a"

If the list is empty or doesn’t exist, it returns a null bulk string ($-1\r\n).

Tests

The tester will execute your program like this:

./your_program.sh

It will then create a list with some elements.

$ redis-cli
> RPUSH list_key "one" "two" "three" "four" "five"

Next, it will send an LPOP command to your server specifying the list that was just created:

> LPOP list_key
# Expecting: (Bulk string) "one"

The tester will expect the removed element to be returned as a RESP bulk string ($3\r\none\r\n).

The tester will also verify that the remaining elements are present in the list using the LRANGE command.

> LRANGE list_key 0 -1
# Expect a RESP Encoded Array: ["two", "three", "four", "five"]

Original stage ef1

9. Remove multiple elements

In this stage, you’ll add support for removing multiple elements in a single LPOP command.

LPOP with multiple elements

The LPOP command accepts an optional argument that specifies how many elements to remove from a list. The command returns the removed elements in a RESP array.

For example:

> RPUSH list_key "a" "b" "c" "d"
(integer) 4
> LPOP list_key 2
1) "a"
2) "b"
> LRANGE list_key 0 -1
1) "c"
2) "d"

In this case, LPOP removes the first two elements, a and b, and the list is left with c and d.

If the number of elements to remove is greater than the list’s length, the command should remove all elements in the list and return them as a RESP array.

Tests

The tester will execute your program like this:

./your_program.sh

It will first create a list with multiple elements.

$ redis-cli
> RPUSH list_key "one" "two" "three" "four" "five"
# Expect: 5 (RESP Encoded Integer)

After that, it will send your program an LPOP command with the number of elements to remove.

> LPOP list_key 2
# Expect RESP Encoded Array: ["one", "two"]

The tester will verify that the response is a RESP array of the removed elements.

It will also use the LRANGE command to verify the remaining elements in the list.

> LRANGE list_key 0 -1
# Expect RESP Encoded Array: ["three", "four", "five"]

Original stage jp1

10. Blocking retrieval

In this stage, you’ll add support for the BLPOP command, which blocks until an element is available to be popped.

The BLPOP Command

BLPOP is a blocking variant of the LPOP command. It waits for an element to become available on a list before popping it.

If the list is empty, the command blocks until:

  • A new element is added to the list
  • Or a specified timeout is reached.

If the timeout is 0, the command blocks indefinitely.

For example, a client can block on a list with an indefinite timeout like this:

> BLPOP list_key 0

This client will wait until an element is added to list_key. When an element like "foobar" is added, it is removed from the list, and the server responds with a RESP array:

1) "list_key"
2) "foobar"

The RESP array contains two bulk strings:

  1. The list name
  2. The element that was popped

The BLPOP command has a few other behaviours to keep in mind:

  • If a timeout duration is supplied, it is the number of seconds the client will wait for an element.
  • If no elements were inserted during the timeout interval, the server returns a null array (*-1\r\n).
  • If multiple clients are blocked for the same list, the server responds to the client that has been waiting the longest.
Tests

The tester will execute your program like this:

./your_program.sh

It will then send a BLPOP command with the timeout set to 0:

$ redis-cli BLPOP list_key 0
# (Blocks)

After a short while, another client will push an element to the same list:

# In another client:
$ redis-cli RPUSH list_key "foo"
# Expect: (integer) 1

The tester expects the first client to immediately receive the response, which is the RESP-encoded array ["list_key", "foo"].

# RESP encoding of ["list_key", "foo"]
*2\r\n
$8\r\n
list_key\r\n
$3\r\n
foo\r\n

The tester will also test BLPOP using multiple blocking clients. It will spawn several clients and have each one send a BLPOP command to the same list.

# Client 1 sends BLPOP first
$ redis-cli BLPOP another_list_key 0

# Client 2 sends BLPOP second
$ redis-cli BLPOP another_list_key 0

Then, a separate client will use RPUSH to add an element to the list.

$ redis-cli RPUSH another_list_key "foo"

The tester will expect your server to respond to the client that sent the BLPOP command first (Client 1).

Notes
  • In this stage, the timeout argument will always be 0, meaning BLPOP should wait indefinitely. We’ll handle non-zero timeouts in later stages.

Original stage ec3

11. Blocking retrieval with timeout

In this stage, you’ll add support for a non-zero timeout for the BLPOP command.

The BLPOP Command with a Non-Zero Timeout

The BLPOP command can accept a timeout duration in seconds.

$ redis-cli BLPOP list_key 0.5
# (Blocks for 0.5 seconds)

If an element is not available on the list within this time, the server returns a null array (*-1\r\n). If an element is pushed to the list before the timeout, the command unblocks and returns the list key and the popped element as a RESP array, just like with previous stages.

Tests

The tester will execute your program like this:

./your_program.sh

It will then send a BLPOP command with a non-zero timeout:

$ redis-cli BLPOP list_key 0.1
# (Blocks for 0.1 seconds)

After the timeout expires, the tester will expect to receive a null array (*-1\r\n) as the response.

The tester will also test the case where an element is appended to the list before the timeout is reached. In this case, the response should be a RESP encoded array like ["list_key", "foo"] where foo is the added element.

Original stage xj7

Back to contents

Streams

1. The TYPE command

In this stage, you’ll add support for the TYPE command.

The TYPE command

The TYPE command returns the type of value stored at a given key. These types include: string, list, set, zset, hash, stream, and vectorset.

Here’s an example:

# Set a key to a string value
$ redis-cli SET some_key "foo"
"OK"

# Check the type of value at the key
$ redis-cli TYPE some_key
"string"

The return value is encoded as a simple string.

If a key doesn’t exist, the return value will be none.

$ redis-cli TYPE missing_key
"none"
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a SET command to your server to create a key with a string value.

$ redis-cli SET some_key "foo"

Next, it will send a TYPE command for that key.

$ redis-cli TYPE some_key

Your server should respond with +string\r\n, which is string encoded as a simple string.

Next, the tester will send another TYPE command with a missing key.

$ redis-cli TYPE missing_key

Your server should respond with +none\r\n, which is none encoded as a simple string.

Notes
  • For now, you only need to handle the string and none types. We’ll add support for the stream type in later stages.

Original stage cc3

2. Create a stream

In this stage, you’ll add support for creating Redis streams using the XADD command.

Redis Streams & Entries

A Redis stream is used to store a sequence of entries in chronological order at a given key. Each entry consists of a unique ID and one or more key-value pairs.

For example, if you were using a Redis stream to store real-time data from a temperature & humidity monitor, the stream might look like this:

entries:
  - id: 1526985054069-0 # (ID of the first entry)
    temperature: 36 # (A key-value pair in the first entry)
    humidity: 95 # (Another key-value pair)

  - id: 1526985054079-0 # (ID of the second entry)
    temperature: 37 # (A key-value pair in the second entry)
    humidity: 94 # (Another key-value pair)

  # ... (and so on)

We’ll take a closer look at how entry IDs (like 1526985054069-0) are structured in later stages.

The XADD command

The XADD command appends an entry to a stream. If the stream doesn’t exist, it is created automatically.

The XADD command accepts a stream key, an entry ID, and one or more key-value pairs as arguments:

$ redis-cli XADD stream_key 1526919030474-0 temperature 36 humidity 95
"1526919030474-0"

The return value is the ID of the newly added entry as a bulk string.

XADD supports other optional arguments, but we won’t deal with them in this challenge.

XADD also supports auto-generated entry IDs, but for this stage, you’ll only deal with explicit IDs (like 1526919030474-0).

Tests

The tester will execute your program like this:

$ ./your_program.sh

It’ll then send an XADD command to your server and expect the ID as a response. For example, it might send:

$ redis-cli XADD stream_key 0-1 foo bar
"0-1"

In this case, your server should respond with $3\r\n0-1\r\n, which is 0-1 encoded as a bulk string.

Next, the tester will send a TYPE command to your server to verify the key’s type.

$ redis-cli TYPE stream_key
"stream"

Your server should respond with +stream\r\n, which is stream encoded as a simple string.

Notes
  • You still need to handle the string and none return values for the TYPE command. stream should only be returned for keys that are streams.

Original stage cf6

3. Validating entry IDs

In this stage, you’ll add support for validating entry IDs to the XADD command.

Entry IDs

Entry IDs are crucial for maintaining the order of entries in Redis streams.

Each ID is made up of two integers separated by a dash: <millisecondsTime>-<sequenceNumber>.

For example:

entries:
  - id: 1526985054069-0 # (ID of the first entry)
    temperature: 36
    humidity: 95

  - id: 1526985054079-0 # (ID of the second entry)
    temperature: 37
    humidity: 94

  # ... (and so on)

These IDs are unique within a stream and are guaranteed to be incremental. This means a new entry’s ID will always be greater than the ID of any previous entry.

Specifying Entry IDs in XADD

You can use three different formats to specify the ID for the XADD command:

  • Explicit (1526919030474-0)
  • Auto-generate only sequence number (1526919030474-*)
  • Auto-generate the time and sequence number (*)

For this stage, you will only handle explicit IDs (e.g., 1526919030474-0). You’ll add support for the other two cases in the later stages.

Your XADD implementation must validate the provided ID based on the following rules:

  • The ID must be strictly greater than the last entry’s ID.
    • The millisecondsTime portion of the new ID must be greater than or equal to the last entry’s millisecondsTime.
    • If the millisecondsTime values are equal, the sequenceNumber of the new ID must be greater than the last entry’s sequenceNumber.
  • If the stream is empty, the ID must be greater than 0-0. The minimum valid ID Redis accepts is 0-1.

Here’s an example of adding an entry with a valid ID followed by an invalid ID:

$ redis-cli XADD some_key 1-1 foo bar
"1-1"
$ redis-cli XADD some_key 1-1 bar baz
(error) ERR The ID specified in XADD is equal or smaller than the target stream top item

The second command fails because 1-1 is not strictly greater than the last ID.

Here’s another example:

$ redis-cli XADD some_key 1-1 foo bar
"1-1"
$ redis-cli XADD some_key 0-2 bar baz
(error) ERR The ID specified in XADD is equal or smaller than the target stream top item

The ID 0-2 is invalid because its millisecondsTime is less than the last ID’s millisecondsTime.

Finally, passing 0-0 is always invalid, since IDs must be strictly greater than 0-0:

$ redis-cli XADD some_key 0-0 bar baz
(error) ERR The ID specified in XADD must be greater than 0-0
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then create a few entries using XADD.

$ redis-cli XADD stream_key 1-1 foo bar
"1-1"
$ redis-cli XADD stream_key 1-2 bar baz
"1-2"

Next, it will send a few XADD commands with an invalid ID, such as 1-2 or 0-3.

# The exact time and sequence number as the last entry
$ redis-cli XADD stream_key 1-2 baz foo
(error) ERR The ID specified in XADD is equal or smaller than the target stream top item

# A smaller value for the time and a larger value for the sequence number
$ redis-cli XADD stream_key 0-3 baz foo
(error) ERR The ID specified in XADD is equal or smaller than the target stream top item

In each case, your server should respond with -ERR The ID specified in XADD is equal or smaller than the target stream top item\r\n\, encoded as a simple error.

After that, the tester will send another XADD command with 0-0 as the ID.

$ redis-cli XADD stream_key 0-0 baz foo
(error) ERR The ID specified in XADD must be greater than 0-0

Your server should respond with -ERR The ID specified in XADD must be greater than 0-0\r\n, which is the error message above encoded as a simple error.

Original stage hq8

4. Partially auto-generated IDs

In this stage, you’ll extend XADD to support auto-generating the sequence number of an entry ID.

Specifying Entry IDs in XADD (Recap)

As a recap, the XADD command accepts IDs in three formats:

  • Explicit (1526919030473-0) (Handled in previous stages)
  • Auto-generate only the sequence number (1526919030474-*)
  • Auto-generate the time part and sequence number (*)

For this stage, you’ll handle the second case, where only the sequence number is auto-generated.

Auto-Generating Sequence Numbers

Redis automatically assigns sequence numbers based on the following conditions:

  • If the stream is empty for a given time part, the sequence number starts at 0.
  • If there are already entries with the same time part, the new sequence number is the last sequence number plus 1.
  • The only exception is when the time part is 0. In that case, the default sequence number starts at 1.

Here’s an example of adding an entry with * as the sequence number:

$ redis-cli XADD some_key "1-*" foo bar
"1-0" # The sequence number is 0 if no prior entries exist

$ redis-cli XADD some_key "1-*" bar baz
"1-1" # Adding another entry will increment the sequence number
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send an XADD command with * as the sequence number.

$ redis-cli XADD stream_key 0-* foo bar

Your server should respond with $3\r\n0-1\r\n, which is 0-1 encoded as a bulk string.

Next, it will send another XADD command with * as the sequence number, but this time with a random number as the time part.

$ redis-cli XADD stream_key 5-* foo bar

Your server should respond with $3\r\n5-0\r\n, which is 5-0 encoded as a bulk string.

After that, the tester will send the same command again.

$ redis-cli XADD stream_key 5-* bar baz

Your server should respond with $3\r\n5-1\r\n, which is 5-1 encoded as a bulk string.

Notes
  • The tester will use a random number for the time part (we use 5 in the example above).

Original stage yh3

5. Fully auto-generated IDs

In this stage, you’ll extend XADD to support auto-generating entry IDs.

Specifying Entry IDs in XADD (Recap)

As a recap, the XADD command accepts IDs in three formats:

  • Explicit (1526919030473-0) (Handled in earlier stages)
  • Auto-generate only the sequence number (1526919030474-*) (Handled in previous stages)
  • Auto-generate the time part and sequence number (*)

For this stage, you’ll handle the third case, where the entire entry ID is auto-generated.

Auto-Generating Entry IDs

When * is used with the XADD command, the server automatically generates a unique ID for the new entry:

  • It uses the current Unix time in milliseconds for the time part and 0 for the sequence number.
  • If an entry with the same timestamp already exists in the stream, the server increments the sequence number by 1.

Here’s an example:

> XADD stream_key * foo bar
"1526919030474-0"
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then create an entry with * as the ID.

$ redis-cli XADD stream_key * foo bar

Your server should respond with a string like $15\r\n1526919030474-0\r\n, which is 1526919030474-0 encoded as a bulk string.

Notes
  • The time part of the ID should be the current Unix time in milliseconds, not seconds.
  • The tester doesn’t test the case where a time part already exists in the stream and the sequence number is incremented. This is difficult to test reliably since we’d need to send two commands within the same millisecond.

Original stage xu6

6. Query entries from stream

In this stage, you’ll add support for querying data from a stream using the XRANGE command.

The XRANGE command

The XRANGE command retrieves a range of entries from a stream.

It takes two arguments: a start ID and an end ID, and returns all entries within that range. The range is inclusive, meaning entries with IDs equal to the start and end IDs are included.

Here’s an example of how it works:

$ redis-cli XADD some_key 1526985054069-0 temperature 36 humidity 95
"1526985054069-0" # (ID of the first added entry)
$ redis-cli XADD some_key 1526985054079-0 temperature 37 humidity 94
"1526985054079-0"
$ redis-cli XRANGE some_key 1526985054069 1526985054079
1) 1) 1526985054069-0
   2) 1) temperature
      2) 36
      3) humidity
      4) 95
2) 1) 1526985054079-0
   2) 1) temperature
      2) 37
      3) humidity
      4) 94

The command can accept IDs in the format <millisecondsTime>-<sequenceNumber>, but the sequence number is optional. If you don’t provide a sequence number:

  • For the start ID, the sequence number defaults to 0.
  • For the end ID, the sequence number defaults to the maximum sequence number.

The return value of the command is not exactly what is shown in the example above. This is already formatted by redis-cli.

The actual return value is a RESP array of arrays.

Each inner array represents a single entry and contains two elements:

  • The entry’s ID (as a bulk string).
  • An array of key-value pairs (as bulk strings) in the order they were added.

The return value of the example above is actually something like this:

[
  [
    "1526985054069-0",
    [
      "temperature",
      "36",
      "humidity",
      "95"
    ]
  ],
  [
    "1526985054079-0",
    [
      "temperature",
      "37",
      "humidity",
      "94"
    ]
  ],
]

When encoded as a RESP array, it looks like this:

*2\r\n
*2\r\n
$15\r\n1526985054069-0\r\n
*4\r\n
$11\r\ntemperature\r\n
$2\r\n36\r\n
$8\r\nhumidity\r\n
$2\r\n95\r\n
*2\r\n
$15\r\n1526985054079-0\r\n
*4\r\n
$11\r\ntemperature\r\n
$2\r\n37\r\n
$8\r\nhumidity\r\n
$2\r\n94\r\n

(This response is separated into multiple lines for readability. The actual return value doesn’t contain any additional newlines.)

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then add a few entries to a stream.

$ redis-cli XADD stream_key 0-1 foo bar
"0-1"
$ redis-cli XADD stream_key 0-2 bar baz
"0-2"
$ redis-cli XADD stream_key 0-3 baz foo
"0-3"

Next, it will send an XRANGE command to your server.

$ redis-cli XRANGE stream_key 0-2 0-3

Your server should respond with a RESP array containing the range of entries from the IDs provided.

Based on the example above, the response should look like the following (encoded as a RESP array):

[
  [
    "0-2",
    [
      "bar",
      "baz"
    ]
  ],
  [
    "0-3",
    [
      "baz",
      "foo"
    ]
  ]
]

Original stage zx1

7. Query with –

In this stage, you’ll extend support for XRANGE to allow querying using -.

Using XRANGE with -

In the XRANGE command, the start argument can be specified as - to retrieve entries from the very beginning of the stream. This provides a simple way to get a range of entries starting from the first one without needing to know its ID.

Here’s an example of how that works:

$ redis-cli XADD some_key 1526985054069-0 temperature 36 humidity 95
"1526985054069-0"

$ redis-cli XADD some_key 1526985054079-0 temperature 37 humidity 94
"1526985054079-0"

$ redis-cli XRANGE some_key - 1526985054079
1) 1) 1526985054069-0
   2) 1) temperature
      2) 36
      3) humidity
      4) 95
2) 1) 1526985054079-0
   2) 1) temperature
      2) 37
      3) humidity
      4) 94

In the example above, XRANGE retrieves all entries from the beginning of the stream to the entry with ID 1526985054079-0.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then create a few entries.

$ redis-cli XADD stream_key 0-1 foo bar
"0-1"
$ redis-cli XADD stream_key 0-2 bar baz
"0-2"
$ redis-cli XADD stream_key 0-3 baz foo
"0-3"

Next, it will send an XRANGE command using - as the start ID:

$ redis-cli XRANGE stream_key - 0-2
1) 1) 0-1
   2) 1) foo
      2) bar
2) 1) 0-2
   2) 1) bar
      2) baz

Your server should respond with a RESP array containing the entries from the beginning of the stream up to the entry with the provided end ID.

From the example above, the response should look like the following, encoded as a RESP array:

[
  [
    "0-1",
    [
      "foo",
      "bar"
    ]
  ],
  [
    "0-2",
    [
      "bar",
      "baz"
    ]
  ]
]

Original stage yp1

8. Query with +

In this stage, you’ll extend support for XRANGE to allow querying using +.

Using XRANGE with +

In the XRANGE command, the end argument can be specified as + to retrieve entries from the given start ID to the end of the stream.

Here’s an example of how that works:

$ redis-cli XADD some_key 1526985054069-0 temperature 36 humidity 95
"1526985054069-0"

$ redis-cli XADD some_key 1526985054079-0 temperature 37 humidity 94
"1526985054079-0"

$ redis-cli XRANGE some_key 1526985054069 +
1) 1) 1526985054069-0
   2) 1) temperature
      2) 36
      3) humidity
      4) 95
2) 1) 1526985054079-0
   2) 1) temperature
      2) 37
      3) humidity
      4) 94

In the example above, XRANGE retrieves all the entries from some_key starting from the entry with ID 1526985054069-0 to the very end of the stream.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then create a few entries.

$ redis-cli XADD stream_key 0-1 foo bar
$ redis-cli XADD stream_key 0-2 bar baz
$ redis-cli XADD stream_key 0-3 baz foo

Next, it will send an XRANGE command using + as the end ID:

$ redis-cli XRANGE stream_key 0-2 +

Your server should respond with a RESP array containing the entries from the provided start ID to the end of the stream.

From the example above, your response should look like the following, encoded as a RESP array:

[
  [
    "0-2",
    [
      "bar",
      "baz"
    ]
  ],
  [
    "0-3",
    [
      "baz",
      "foo"
    ]
  ]
]

The raw RESP encoding looks like this:

*2\r\n
*2\r\n
$3\r\n0-2\r\n
*2\r\n
$3\r\nbar\r\n
$3\r\nbaz\r\n
*2\r\n
$3\r\n0-3\r\n
*2\r\n
$3\r\nbaz\r\n
$3\r\nfoo\r\n
Notes
  • In the response, the items are shown in separate lines for readability. The tester expects all of these to be in one line.

Original stage fs1

9. Query single stream using XREAD

In this stage, you’ll add support to querying a stream using the XREAD command.

The XREAD Command

The XREAD command is used to read data from one or more streams, starting from a specified entry ID.

Unlike XRANGE, which requires both a start and end ID, XREAD takes only a single ID.

Another difference is that XREAD is exclusive. This means that the command retrieves all entries with an ID greater than the specified ID.

The basic syntax for the command is:

XREAD STREAMS <key> <id>

XREAD supports other optional arguments, but we won’t deal with them at this stage.

Here’s an example of its behavior:

$ redis-cli XADD some_key 1526985054069-0 temperature 36 humidity 95
"1526985054069-0"

$ redis-cli XADD some_key 1526985054079-0 temperature 37 humidity 94
"1526985054079-0"

$ redis-cli XREAD STREAMS some_key 1526985054069-0
1) 1) "some_key"
   2) 1) 1) 1526985054079-0
         2) 1) temperature
            2) 37
            3) humidity
            4) 94

The return value is an array of streams, where each stream contains:

  • The stream key (as a bulk string).
  • An array of entries, where each entry is an array of two parts:
    • The entry’s ID (as a bulk string).
    • An array of key-value pairs (as bulk strings).

Here’s what the response from the example above would look like:

[
  [
    "some_key",
    [
      [
        "1526985054079-0",
        [
          "temperature",
          "37",
          "humidity",
          "94"
        ]
      ]
    ]
  ]
]

When encoded as a RESP array, it looks like this:

*1\r\n
*2\r\n
$8\r\nsome_key\r\n
*1\r\n
*2\r\n
$15\r\n1526985054079-0\r\n
*4\r\n
$11\r\ntemperature\r\n
$2\r\n37\r\n
$8\r\nhumidity\r\n
$2\r\n94\r\n

(The result is shown on separate lines for readability. The actual return value is a single line.)

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send an XADD command to add an entry to a stream.

$ redis-cli XADD stream_key 0-1 temperature 96

Next, the tester will send an XREAD command to your server.

$ redis-cli XREAD STREAMS stream_key 0-0

Your server should respond with a RESP array containing the correct stream entries.

From the example above, your response should look like the following, encoded as a RESP array:

[
  [
    "stream_key",
    [
      [
        "0-1",
        [
          "temperature",
          "96"
        ]
      ]
    ]
  ]
]

Original stage um0

10. Query multiple streams using XREAD

In this stage, you’ll add support for querying multiple streams using the XREAD command.

The XREAD Command for Multiple Streams

When reading from multiple streams, the XREAD command takes the STREAMS keyword, followed by a list of stream keys, and then a corresponding list of entry IDs for each stream.

The command format is:

XREAD STREAMS <key1> <key2> ... <id1> <id2> ...

The server’s response remains a RESP array of streams where:

  • Each stream is a two-item array: the stream’s key and the entries read from it.
  • The order of the streams in the response must match the order in which they were specified in the command.
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send multiple XADD commands to add entries to several streams.

$ redis-cli XADD stream_key 0-1 temperature 95
$ redis-cli XADD other_stream_key 0-2 humidity 97

Next, the tester will send an XREAD command to your server with multiple streams.

$ redis-cli XREAD streams stream_key other_stream_key 0-0 0-1

Your server should respond with a RESP array containing the results for all the specified streams.

From the example above, your response should look like the following, encoded as a RESP array:

[
  [
    "stream_key",
    [
      [
        "0-1",
        [
          "temperature",
          "95"
        ]
      ]
    ]
  ],
  [
    "other_stream_key",
    [
      [
        "0-2",
        [
          "humidity",
          "97"
        ]
      ]
    ]
  ]
]

Original stage ru9

11. Blocking reads

In this stage, you’ll extend your XREAD implementation to support blocking.

Understanding Blocking in XREAD

By default, the XREAD command is synchronous: it returns data immediately if entries are available, or an empty response if not.

However, with the optional BLOCK parameter, clients can wait for new data to arrive.

The syntax looks like this:

XREAD BLOCK <milliseconds> STREAMS <key> <id>

Here’s how it works:

  • The client sends the command and specifies a timeout in milliseconds.
  • If there are already entries with IDs greater than the specified ID, the command returns them immediately.
  • If there are no new entries available, the command blocks and waits.
  • If a new entry is added to the stream before the timeout expires, the command unblocks and returns the new entry (or entries).
  • If the timeout expires and no new data has arrived, the server responds with a null array (*-1\r\n).

For example, consider two separate clients. The first client sends a blocking XREAD command:

$ redis-cli XREAD BLOCK 1000 streams some_key 1526985054069-0

This client will now block and wait for a new entry to be added.

Meanwhile, a second client can add an entry to the stream:

$ other-redis-cli XADD some_key 1526985054079-0 temperature 37 humidity 94
"1526985054079-0"

If the entry is added within 1000 milliseconds, the first client’s XREAD command will immediately unblock and respond with the new entry:

1) 1) "some_key"
   2) 1) 1) 1526985054079-0
      2) 1) temperature
         2) 37
         3) humidity
         4) 94

However, if no new entry is added before the timeout expires, the command will fail and return a null array:

(nil)
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then add an entry to a stream.

$ redis-cli XADD stream_key 0-1 temperature 96

Next, it will send an XREAD command to your server with the BLOCK option.

$ redis-cli XREAD BLOCK 1000 streams stream_key 0-1

In another instance of the redis-cli, the tester will add an entry within 500 milliseconds.

$ redis-cli XADD stream_key 0-2 temperature 95

Your server should respond to the first client with the following, encoded as a RESP array:

[
  [
    "stream_key",
    [
      [
        "0-2",
        [
          "temperature",
          "95"
        ]
      ]
    ]
  ]
]

Next, the tester will send another blocking XREAD command, but this time, it will allow the full timeout duration to elapse before checking the response.

$ redis-cli XREAD block 1000 streams stream_key 0-2

In this case, your server should respond with a null array (*-1\r\n).

Original stage bs1

12. Blocking reads without timeout

In this stage, you’ll extend your XREAD implementation to support blocking indefinitely.

Indefinite Blocking in XREAD

As a recap, the XREAD command supports blocking using the BLOCK <milliseconds> parameter.

If the milliseconds value is set to 0, the XREAD command will block indefinitely until a new entry is added to the stream(s).

For example, consider two separate clients. The first client sends a blocking XREAD command with 0 as the time passed in:

$ redis-cli XREAD BLOCK 0 streams some_key 1526985054069-0

This client will be blocked indefinitely until a new entry is added.

If the second client adds an entry to the stream at any time:

$ other-redis-cli XADD some_key 1526985054079-0 temperature 37 humidity 94
"1526985054079-0"

The first client’s XREAD command will immediately unblock and respond with the new entry:

1) 1) "some_key"
   2) 1) 1) 1526985054079-0
         2) 1) temperature
            2) 37
            3) humidity
            4) 94
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then add an entry to a stream.

$ redis-cli XADD stream_key 0-1 temperature 96

Next, the tester will send an indefinite blocking XREAD command to your server:

$ redis-cli XREAD BLOCK 0 streams stream_key 0-1

It will then pause for 1000 milliseconds to confirm the client remains blocked and doesn’t time out. After that, it will add another entry:

$ redis-cli XADD stream_key 0-2 temperature 95

Your server should respond with the following, encoded as a RESP array:

[
  [
    "stream_key",
    [
      [
        "0-2",
        [
          "temperature",
          "95"
        ]
      ]
    ]
  ]
]

Original stage hw1

13. Blocking reads using $

In this stage, you’ll extend support for XREAD to handle $ as the starting ID in a blocking read.

Understanding $ as an Entry ID

When $ is passed as the ID, XREAD will only return new entries added after the command is sent. This is similar to passing in the maximum ID currently available in a stream.

For example, suppose we have two separate clients. The first client sends a blocking XREAD command with 1000 as the timeout and $ as the ID:

$ redis-cli XREAD BLOCK 1000 streams some_key $

Then, the second client adds an entry to the some_key stream.

$ other-redis-cli XADD some_key 1526985054079-0 temperature 37 humidity 94
"1526985054079-0"

Similar to the behavior detailed in the earlier stages, if the command is sent within 1000 milliseconds, the first client will be unblocked and get the new entry:

1) 1) "some_key"
   2) 1) 1) 1526985054079-0
         2) 1) temperature
            2) 37
            3) humidity
            4) 94

If not, the response will be a null array.

(nil)
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then add an entry to a stream.

$ redis-cli XADD stream_key 0-1 temperature 96

Next, it will send an XREAD command to your server with the BLOCK command with 0 as the time and $ as the ID.

$ redis-cli XREAD BLOCK 0 streams stream_key $

In another instance of the redis-cli, the tester will add another entry after 500 milliseconds.

$ redis-cli XADD stream_key 0-2 temperature 95

Your server should respond with the following, as a RESP array:

[
  [
    "stream_key",
    [
      [
        "0-2",
        [
          "temperature",
          "95"
        ]
      ]
    ]
  ]
]

After that, the tester will send another XREAD command to your server with the BLOCK command, but this time, it’ll wait for 1000 milliseconds before checking the response of your server.

$ redis-cli XREAD BLOCK 1000 streams stream_key $

Your server should respond with a null array (*-1\r\n).

Original stage xu1

Back to contents

Transactions

1. The INCR command (1/3)

In this stage, you’ll add support for the INCR command.

The INCR command

The INCR command is used to increment the value of a key by 1.

Example usage:

$ redis-cli SET foo 5
"OK"
$ redis-cli INCR foo
(integer) 6
$ redis-cli INCR foo
(integer) 7

If the key doesn’t exist, the value will be set to 1.

We’ll split the implementation of this command into three stages:

  • Key exists and has a numerical value (This stage)
  • Key doesn’t exist (later stages)
  • Key exists but doesn’t have a numerical value (later stages)
Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will then connect to your server as a Redis client and run the following commands:

$ redis-cli
> SET foo 41 (expecting "+OK" as the response)
> INCR foo (expecting ":42\r\n" as the response)

Original stage si4

2. The INCR command (2/3)

In this stage, you’ll add support for handling the INCR command when a key does not exist.

Recap

The implementation of INCR is split into three stages:

  • Key exists and has a numerical value (previous stages)
  • Key doesn’t exist (This stage)
  • Key exists but doesn’t have a numerical value (later stages)

When a key doesn’t exist, INCR sets the value to 1. Example:

$ redis-cli INCR missing_key
(integer) 1
$ redis-cli GET missing_key
"1"
Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will then connect to your server as a Redis client and run the following commands:

$ redis-cli
> INCR foo (expecting ":1\r\n" as the response)
> INCR bar (expecting ":1\r\n" as the response)
Notes
  • Your implementation still needs to pass the tests in previous stages.

Original stage lz8

3. The INCR command (3/3)

In this stage, you’ll add support for handling the INCR command when a key exists but doesn’t have a numerical value.

Recap

The implementation of INCR is split into three stages:

  • Key exists and has a numerical value (previous stages)
  • Key doesn’t exist (previous stages)
  • Key exists but doesn’t have a numerical value (This stage)

When a key exists but doesn’t have a numerical value, INCR will return an error. Example:

$ redis-cli SET foo xyz
"OK"
$ redis-cli INCR foo
(error) ERR value is not an integer or out of range
Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will then connect to your server as a Redis client and run the following commands:

$ redis-cli
> SET foo xyz (expecting "+OK\r\n" as the response)
> INCR foo (expecting "-ERR value is not an integer or out of range\r\n" as the response)

Original stage mk1

4. The MULTI command

In this stage, you’ll add support for the MULTI command.

The MULTI command

The MULTI command starts a transaction.

After a MULTI command is executed, any further commands from the same connection will be “queued” but not executed.

Example usage:

$ redis-cli
> MULTI
OK
> SET foo 41
QUEUED
> INCR foo
QUEUED

The queued commands can be executed using EXEC, which we’ll cover in later stages.

In this stage, you’ll just add support for handling the MULTI command and returning +OK\r\n. We’ll get to queueing commands in later stages.

Tests

The tester will execute your program like this:

./your_program.sh

The tester will then connect to your server as a Redis client and run the following command:

$ redis-cli MULTI

The tester will expect +OK\r\n as the response.

Notes
  • We’ll test queueing commands & executing a transaction in later stages.

Original stage pn0

5. The EXEC command

In this stage, you’ll add support for the EXEC command when the MULTI command has not been called.

The EXEC command

The EXEC command executes all commands queued in a transaction.

It returns an array of the responses of the queued commands.

Example usage:

$ redis-cli
> MULTI
OK
> SET foo 41
QUEUED
> INCR foo
QUEUED
> EXEC
1) OK
2) (integer) 42
EXEC without MULTI

If EXEC is executed without having called MULTI, it returns an error.

Example usage:

$ redis-cli EXEC
(error) ERR EXEC without MULTI

The returned value is a Simple error, the exact bytes are -ERR EXEC without MULTI\r\n.

Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will then connect to your server as a Redis client and run the following commands:

$ redis-cli EXEC

The tester will expect “-ERR EXEC without MULTI\r\n” as the response.

Notes
  • In this stage you only need to implement EXEC when MULTI hasn’t been called.
  • We’ll test handling EXEC after MULTI in later stages.

Original stage lo4

6. Empty transaction

In this stage, you’ll add support for executing an empty transaction.

Empty transactions

If EXEC is executed soon after MULTI, it returns an empty array.

The empty array signifies that no commands were queued, and that the transaction was executed successfully.

Example usage:

$ redis-cli
> MULTI
OK
> EXEC
(empty array)
Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will then connect to your server as a Redis client and run the following commands:

$ redis-cli
> MULTI (expecting "+OK\r\n")
> EXEC (expecting "*0\r\n" as the response)
> EXEC (expecting "-ERR EXEC without MULTI\r\n" as the response)

Original stage we1

7. Queueing commands

In this stage, you’ll add support for queuing commands within a transaction.

Queuing commands

After MULTI is executed, any further commands from a connection are queued until EXEC is executed.

The response to all of these commands is +QUEUED\r\n (That’s QUEUED encoded as a Simple String).

Example:

$ redis-cli
> MULTI
OK
> SET foo 41
QUEUED
> INCR foo
QUEUED

... (and so on, until EXEC is executed)

When commands are queued, they should not be executed or alter the database in any way.

In the example above, until EXEC is executed, the key foo will not exist.

Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will then connect to your server as a Redis client, and send multiple commands using the same connection:

$ redis-cli
> MULTI
> SET foo 41 (expecting "+QUEUED\r\n")
> INCR foo (expecting "+QUEUED\r\n")

Since these commands were only “queued”, the key foo should not exist yet. The tester will verify this by creating another connection and sending this command:

$ redis-cli GET foo (expecting `$-1\r\n` as the response)

Original stage rs9

8. Executing a transaction

In this stage, you’ll add support for executing a transaction that contains multiple commands.

Executing a transaction

When the EXEC command is sent within a transaction, all commands queued in that transaction are executed.

The response to EXEC is an array of the responses of the queued commands.

Example:

$ redis-cli
> MULTI
OK
> SET foo 41
QUEUED
> INCR foo
QUEUED
> EXEC
1) OK
2) (integer) 42

In the above example, OK is the response of the SET command, and 42 is the response of the INCR command.

Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will then connect to your server as a Redis client, and send multiple commands using the same connection:

$ redis-cli MULTI
> SET foo 6 (expecting "+QUEUED\r\n")
> INCR foo (expecting "+QUEUED\r\n")
> INCR bar (expecting "+QUEUED\r\n")
> GET bar (expecting "+QUEUED\r\n")
> EXEC (expecting an array of responses for the queued commands)

Since the transaction was executed, the key foo should exist and have the value 7.

The tester will verify this by running a GET command:

$ redis-cli GET foo (expecting "7" encoded as a bulk string)

Original stage fy6

9. The DISCARD command

In this stage, you’ll add support for the DISCARD command.

The DISCARD command

DISCARD is used to abort a transactions. It discards all commands queued in a transaction, and returns +OK\r\n.

Example:

$ redis-cli
> MULTI
OK
> SET foo 41
QUEUED
> DISCARD
OK
> DISCARD
(error) ERR DISCARD without MULTI

In the above example, note that the first DISCARD returns OK, but the second DISCARD returns an error since the transaction was aborted.

DISCARD
Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will then connect to your server as a Redis client, and send multiple commands using the same connection:

$ redis-cli
> MULTI
> SET foo 41 (expecting "+QUEUED\r\n")
> INCR foo (expecting "+QUEUED\r\n")
> DISCARD (expecting "+OK\r\n")
> GET foo (expecting "$-1\r\n" as the response)
> DISCARD (expecting "-ERR DISCARD without MULTI\r\n" as the response)

Original stage rl9

10. Failures within transactions

In this stage, you’ll add support for handling failures within a transaction.

Failures within transactions

When executing a transaction, if a command fails, the error is captured and returned within the response for EXEC. All other commands in the transaction are still executed.

You can read more about this behaviour in the official Redis docs.

Example:

$ redis-cli
> MULTI
OK
> SET foo xyz
QUEUED
> INCR foo
QUEUED
> SET bar 7
> EXEC
1) OK
2) (error) ERR value is not an integer or out of range
3) OK

In the example above, note that the error for the INCR command was returned as the second array element. The third command (SET bar 7) was still executed successfully.

Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will then connect to your server as a Redis client, and send multiple commands using the same connection:

$ redis-cli
> SET foo abc
OK
> SET bar 41
OK
> MULTI
OK
> INCR foo
QUEUED
> INCR bar
QUEUED
> EXEC
1) (error) ERR value is not an integer or out of range
2) (integer) 42

The expected response for EXEC is a RESP array of the responses of the queued commands. The exact bytes will be:

*2\r\n-ERR value is not an integer or out of range\r\n:42\r\n

The tester will also verify that the last command was successfully executed and that the key bar exists:

$ redis-cli
> GET foo (expecting "$3\r\nabc\r\n" as the response)
> GET bar (expecting "$2\r\n42\r\n" as the response)
Notes
  • There are a subset of command failures (like syntax errors) that will cause a transaction to be aborted entirely. We won’t cover those in this challenge.

Original stage sg9

11. Multiple transactions

In this stage, you’ll add support for multiple concurrent transactions.

Multiple transactions

There can be multiple transactions open (i.e. MULTI has been called, but EXEC has not been called yet) at the same time. Each transaction gets its own command queue.

For example, say you started transaction 1 from one connection:

$ redis-cli
> MULTI
OK
> SET foo 41
QUEUED
> INCR foo
QUEUED

and started transaction 2 from another connection:

$ redis-cli
> MULTI
OK
> INCR foo
QUEUED

If you then run EXEC in transaction 1, you should see the following:

> EXEC
1) OK
2) (integer) 42

OK is the response to SET foo 41, and 42 is the response to INCR foo.

And for transaction 2, running EXEC should return:

> EXEC
1) (integer) 43

43 is the response to INCR foo. The key foo was updated to 42 by transaction 1, and INCR foo further increments it to 43.

Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will then connect to your server as multiple Redis clients, and send multiple commands from each connection:

$ redis-cli MULTI
> INCR foo
> EXEC

Original stage jf8

Back to contents

Optimistic Locking

1. The WATCH command

In this stage, you’ll add support for the WATCH command.

The WATCH Command

Redis uses the WATCH command to implement optimistic locking. It tells the server to monitor a key for changes. Later, when the client executes a group of commands as a transaction, the server checks whether any watched keys were modified in the meantime. If they were, the whole transaction is discarded.

Here’s what that looks like in practice:

Client A: WATCH counter          # "Tell me if this changes"
Client A: GET counter → 10       # Read current value
Client B: SET counter 20         # Another client sneaks in an update
Client A: MULTI                  # Start a transaction
Client A: SET counter 11         # Queue an update based on stale data
Client A: EXEC                   # Try to execute...
→ (nil)                          # Transaction aborted, counter changed

You’ll implement this full flow in later stages. For this stage, you only need to parse the WATCH command and respond with +OK\r\n.

$ redis-cli WATCH key
OK
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a WATCH command:

$ redis-cli WATCH key

The tester will verify that:

  • The response is +OK\r\n (a RESP simple string)
  • Your program doesn’t crash or produce errors
Notes
  • WATCH can accept multiple keys in a single command (e.g., WATCH key1 key2 key3), but you only need to handle a single key for now. We’ll handle multiple keys in later stages.
  • The actual watch tracking and transaction abort behavior will come in later stages.

Original stage jb7

2. WATCH inside transaction

In this stage, you’ll implement MULTI and update WATCH to reject calls inside transactions.

Redis Transactions

In previous stages, you saw how WATCH fits into a larger flow: watch a key, start a transaction with MULTI, queue some commands, and execute with EXEC. Now you’ll start building the transaction side.

Redis transactions allow clients to execute multiple commands as a single operation. The basic flow is:

  1. MULTI – Enter transaction mode (commands get queued instead of executing immediately)
  2. SET key value, INCR counter, etc. – Commands are queued
  3. EXEC – Execute all queued commands

We’ll implement EXEC in later stages. For this stage, you’ll implement the MULTI command and make WATCH check whether it’s being called inside a transaction.

The MULTI Command

The MULTI command is used to start a transaction.

$ redis-cli MULTI
OK

When a client uses MULTI, the server:

  1. Marks the connection as being inside a transaction
  2. Returns OK as a simple string
The WATCH Command (Updated)

WATCH is meant to be called before a transaction starts. Calling it inside a transaction is not allowed because the transaction has already begun, and commands are already being queued.

Now that you have the transaction state, WATCH needs to enforce this:

  • If the connection is outside a transaction:
    1. Add the key to the connection’s collection of watched keys
    2. Return OK as a simple string
  • If the connection is inside a transaction (after MULTI):
    1. Return a RESP error like: -ERR WATCH inside MULTI is not allowed\r\n. The exact wording is flexible but should include: ERR, WATCH, inside MULTI, and not allowed.

For example:

$ redis-cli
> WATCH counter
OK
> MULTI
OK
(TX)> WATCH another_key
(error) ERR WATCH inside MULTI is not allowed
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then spawn a client, begin a transaction using the MULTI command, and send a WATCH command with a random key:

$ redis-cli
> MULTI
OK
> WATCH key
(error) ERR WATCH inside MULTI is not allowed

The tester will verify that:

  • MULTI returns OK as a simple string
  • WATCH inside a transaction returns a RESP error containing: ERR, WATCH, inside MULTI, and not allowed
Notes
  • You’ll need a way to track state per connection (like a map keyed by the connection/socket).
  • When WATCH is called outside a transaction, you should still track the watched keys even though they’re not used yet. This prepares you for later stages.
  • The exact error message format is flexible as long as it includes the required keywords.

Original stage jq9

3. Tracking key modifications

In this stage, you’ll implement the EXEC command and add support for aborting transactions.

Redis Transactions (Recap)

As a recap, Redis transactions allow clients to execute multiple commands as a single operation. The basic flow is:

  1. MULTI – Enter transaction mode (Handled in previous stages)
  2. SET key value, INCR counter, etc. – Commands are queued
  3. EXEC – Execute all queued commands

For this stage, you’ll implement the EXEC command and fail transactions when their watched keys have been modified.

The EXEC Command

The EXEC command executes all commands that were queued after MULTI:

$ redis-cli
> SET foo 100
OK
> MULTI
OK
> SET foo 200
QUEUED
> SET bar 300
QUEUED
> EXEC
1) OK
2) OK

The response is a RESP array where each element is the result of a queued command, in the order they were queued.

Failing Transactions With WATCH

When a connection has watched keys, EXEC needs to check whether any of those keys were modified by another client between the WATCH and the EXEC. If they were, the transaction is aborted:

Client A: WATCH foo             # Server tracks "foo" for Client A
Client A: MULTI
Client A: SET bar 300           # Queued
Client B: SET foo 999           # Modifies Client A's watched key
Client A: EXEC                  # Returns *-1\r\n, queued commands discarded

EXEC returns a RESP null array (*-1\r\n), and the queued commands are discarded without executing.

If none of the watched keys were modified, EXEC runs the transaction normally.

Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will spawn four clients and run two scenarios.

In the first scenario, it modifies the watched key from a different client:

# Client 1
> SET foo 100        # → +OK
> SET bar 200        # → +OK
> WATCH foo          # → +OK
> MULTI              # → +OK
> SET bar 300        # → +QUEUED

# Client 2 modifies the watched key
> SET foo 200        # → +OK

# Client 1 tries to execute
> EXEC               # → *-1\r\n (null array, transaction aborted)
> GET bar            # → "200" (unchanged, SET bar 300 was never executed)

In the second scenario, it modifies a different key (not the watched one):

# Client 3
> SET baz 100        # → +OK
> SET caz 200        # → +OK
> WATCH baz          # → +OK
> MULTI              # → +OK
> SET caz 400        # → +QUEUED

# Client 4 modifies a different key (not the watched one)
> SET caz 300        # → +OK

# Client 3 executes successfully
> EXEC               # → array of responses (baz was not modified)

# Client 4 verifies the transaction's write took effect
> GET caz            # → "400"

The tester will verify that:

  • EXEC returns a RESP null array (*-1\r\n) when a watched key was modified by another client
  • EXEC returns the array of command results when no watched keys were modified
  • Queued commands are not executed when the transaction is aborted, and the original values are preserved
  • Queued commands are executed when no watched keys are modified, and their writes take effect
Notes
  • It’s not enough to compare the value of a watched key at WATCH time vs EXEC time. If a key was modified and then set back to its original value, the transaction should still abort. Track whether the key was touched, not whether its value changed.
  • After EXEC, clear the connection’s watch state (watched keys and dirty flag) regardless of whether the transaction succeeded or was aborted.

Original stage mh8

4. Watching multiple keys

In this stage, you’ll add support for watching multiple keys.

Watching Multiple Keys

In previous stages, you only needed to handle WATCH with a single key. However, the WATCH command also accepts multiple keys at once:

$ redis-cli
> WATCH foo bar baz
OK

All the keys are monitored for changes. If any one of them is modified by another client before EXEC, the transaction aborts:

Client A: WATCH foo bar          # Monitor both keys
Client B: SET bar 300            # Modifies one of the watched keys
Client A: MULTI
Client A: SET foo 400            # Queued
Client A: EXEC                   # Transaction aborted, bar was modified
Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will spawn two clients. Using the first client, it will set two keys, watch both of them, and begin a transaction:

# Client 1
> SET foo 100        # → OK
> SET bar 200        # → OK
> WATCH foo bar      # → OK
> MULTI              # → OK
> SET bar 300        # → QUEUED

Using the second client, it will modify one of the watched keys:

# Client 2
> SET foo 200        # → OK

Back on the first client, the tester will execute the transaction and verify the abort:

# Client 1
> EXEC               # → *-1\r\n (transaction aborted)

# Client 2
> GET bar            # → "200" (unchanged, transaction had no effect)

The tester will verify that:

  • WATCH with multiple keys returns +OK\r\n
  • EXEC returns a RESP null array (*-1\r\n) when any one of the watched keys was modified
  • The aborted transaction’s queued commands had no effect

Original stage fp0

5. Watching missing keys

In this stage, you’ll add support for watching keys that don’t exist yet.

Watching Non-existent Keys

So far, you’ve only watched keys that already have values. But WATCH also works on keys that don’t exist at the time of the call. If a watched key is created by another client before EXEC, the transaction should still abort.

# Client A
> WATCH foo
OK

# Client B
> SET foo 300
OK

# Client A
> MULTI
OK
> SET bar 500
QUEUED
> EXEC
*-1\r\n                # transaction aborted, foo was created after WATCH

The key didn’t exist when Client A watched it, but Client B created it before EXEC. That counts as a modification.

Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will then spawn two clients. Using the first client, it will watch a key that doesn’t exist:

# Client 1
> WATCH foo
OK

Using the second client, it will create the watched key:

# Client 2
> SET foo 200
OK

Back on the first client, the tester will start a transaction and attempt to execute it:

# Client 1
> MULTI
OK
> SET foo 300
QUEUED
> EXEC
*-1\r\n                # transaction aborted
> GET foo
"200"                  # unchanged, transaction had no effect

The tester will verify that:

  • EXEC returns a RESP null array (*-1\r\n) when a watched key was created by another client
  • The aborted transaction’s queued commands had no effect
Notes
  • If your implementation already tracks modifications by flagging watched keys on any write command, this stage may already pass without changes.
  • The key insight is that “modified” includes going from non-existent to existing. A key doesn’t need to have a prior value to be considered touched.

Original stage uo9

6. The UNWATCH command

In this stage, you’ll add support for the UNWATCH command.

The UNWATCH Command

The UNWATCH command clears all watched keys for the current connection. Any keys previously registered with WATCH are no longer monitored, so future transactions won’t be affected by changes to those keys.

$ redis-cli
> WATCH foo bar
OK
> UNWATCH
OK

The response is always +OK\r\n.

After UNWATCH, even if the previously watched keys are modified by another client, the next transaction will execute normally.

Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will spawn two clients. Using the first client, it will set two keys and watch them:

# Client 1
> SET foo 100
OK
> SET bar 200
OK
> WATCH foo bar
OK

Using the second client, it will modify one of the watched keys:

# Client 2
> SET foo 200
OK

Back on the first client, the tester will unwatch all keys, then start and execute a transaction:

# Client 1
> UNWATCH
OK
> MULTI
OK
> SET foo 400
QUEUED
> EXEC
1) OK                  # transaction succeeds, keys were unwatched

# Client 2
> GET foo
"400"                  # confirms the transaction's write took effect

The tester will verify that:

  • UNWATCH returns +OK\r\n
  • EXEC succeeds even though a previously watched key was modified, because UNWATCH cleared the watch state
  • The transaction’s queued commands were applied
Notes
  • UNWATCH takes no arguments. It always clears all watched keys for the connection.
  • UNWATCH should work even if no keys were previously watched (it just returns +OK\r\n).

Original stage bn1

7. Unwatch on EXEC

In this stage, you’ll verify that watched keys are cleared after EXEC.

Clearing Watched Keys on EXEC

WATCH is meant to protect a single transaction. Once EXEC runs (whether the transaction succeeds or aborts), the connection’s watch state should be cleared. Without this cleanup, stale watch state could leak into future transactions on the same connection, causing them to fail for reasons unrelated to them.

$ redis-cli
# Client A
> WATCH foo
OK

# Client B
> SET foo 100
OK

# Client A
> MULTI
OK
> SET bar 200
QUEUED
> EXEC
*-1\r\n                # transaction aborted, foo was modified

# Client A starts a new transaction (no WATCH this time)
> MULTI
OK
> SET bar 200
QUEUED
> EXEC
1) OK                  # succeeds, previous EXEC cleared the watch state
Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will spawn two clients. Using the first client, it will set two keys, watch one of them, and begin a transaction:

# Client 1
> SET foo 100
OK
> SET bar 200
OK
> WATCH foo
OK
> MULTI
OK
> SET bar 300
QUEUED

Using the second client, it will modify the watched key:

# Client 2
> SET foo 200
OK

Back on the first client, the tester will execute the transaction (expecting it to abort), then immediately start and execute a second transaction:

# Client 1
> EXEC
*-1\r\n                # first transaction aborted

# Client 1 starts a new transaction
> MULTI
OK
> SET bar 300
QUEUED
> EXEC
1) OK                  # second transaction succeeds

# Client 2
> GET bar
"300"                  # confirms the second transaction's write took effect

The tester will verify that:

  • The first EXEC returns a RESP null array (*-1\r\n) because the watched key was modified
  • The second EXEC succeeds because the first EXEC cleared the watch state
  • The second transaction’s queued commands were applied
Notes
  • If you have already cleared the watch state after EXEC (as suggested in earlier stages), this stage should pass without additional changes.
  • Clearing watched keys on DISCARD will be handled in later stages.

Original stage fn4

8. Unwatch on DISCARD

In this stage, you’ll implement the DISCARD command and verify that it clears watched keys.

The DISCARD Command

The DISCARD command aborts a transaction. It throws away all queued commands and exits transaction mode:

$ redis-cli
> MULTI
OK
> SET foo 100
QUEUED
> SET bar 200
QUEUED
> DISCARD
OK

The response is always +OK\r\n.

Clearing Watch State

Just like EXEC, DISCARD also clears the connection’s watched keys. This means a subsequent transaction on the same connection won’t be affected by modifications that happened before the DISCARD.

$ redis-cli
# Client A
> WATCH foo
OK

# Client B
> SET foo 999
OK

# Client A
> MULTI
OK
> SET bar 200
QUEUED
> DISCARD
OK                     # watch state cleared

# Client A starts a new transaction (no WATCH active)
> MULTI
OK
> SET bar 200
QUEUED
> EXEC
1) OK                  # succeeds, DISCARD cleared the watch state

Without this cleanup, the second transaction would incorrectly fail because foo was modified before the DISCARD.

Tests

The tester will execute your program like this:

$ ./your_program.sh

The tester will spawn two clients. Using the first client, it will set two keys, watch them, and begin a transaction:

# Client 1
> SET foo 100
OK
> SET bar 200
OK
> WATCH foo bar
OK
> MULTI
OK
> SET bar 300
QUEUED

Using the second client, it will modify one of the watched keys:

# Client 2
> SET foo 400
OK

Back on the first client, the tester will discard the transaction, then immediately start and execute a new one:

# Client 1
> DISCARD
OK

# Client 1 starts a new transaction
> MULTI
OK
> SET bar 300
QUEUED
> EXEC
1) OK                  # succeeds, DISCARD cleared the watch state

# Client 2
> GET bar
"300"                  # confirms the second transaction's write took effect

The tester will verify that:

  • DISCARD returns +OK\r\n
  • DISCARD clears the connection’s watch state
  • The second transaction succeeds because the watched keys were cleared by DISCARD
  • The second transaction’s queued commands were applied
Notes
  • DISCARD should clear both the command queue and the watch state (watched keys and dirty flag).
  • If you already handle watch state cleanup in EXEC, the DISCARD implementation should follow the same pattern.

Original stage hq1

Back to contents

Replication

1. Configure listening port

In this stage, you’ll add support for starting the Redis server on a custom port.

Leader-Follower Replication

The leader-follower replication is a pattern where one server (the “master”) handles all write operations, and one or more servers (the “replicas”) maintain copies of the master’s data. When the master changes data, it automatically copies those changes to the replicas. This system provides data redundancy and improves read performance.

Custom Port Support

Since replication requires running multiple Redis servers simultaneously, each instance needs its own port. This means a Redis server must be able to start on a port other than the default 6379.

The --port flag passes the port number to the Redis server:

./your_program.sh --port <port_number>

The server then parses this argument and starts a TCP server on the specified port.

If you don’t provide a --port flag, the Redis server defaults to port 6379.

Tests

The tester will execute your program like this:

./your_program.sh --port 6380

It’ll then try to connect to your TCP server on the specified port number. If the connection succeeds, you’ll pass this stage.

Notes
  • The tester will pass a random port number to your program, so you can’t hardcode the port number from the example above.
  • If your repository was created before 5th Oct 2023, it’s possible that your ./your_program.sh script might not be passing arguments on to your program. You’ll need to edit ./your_program.sh to fix this, check this PR for details.

Original stage bw1

2. The INFO command

In this stage, you’ll add support for responding to the INFO command as a master server.

The INFO Command

The INFO command returns information and statistics about a running Redis server. For example, a client can get information about a server like this:

$ redis-cli INFO
# Server
redis_version:7.2.4
...
# Clients
connected_clients:1
...
# Memory
used_memory:859944
...
# Replication
role:master
...

The server then responds with a bulk string, where each line is a key-value pair separated by a colon (:). The string can also contain section header lines (starting with #) and blank lines.

The INFO command also accepts an optional parameter to specify which section of information to display, such as server, memory, or replication. For this stage, we’ll only focus on the replication section.

The replication Section

When you run the INFO command with the replication argument, the server returns only the details concerning its replication setup:

$ redis-cli INFO replication
# Replication
role:master
connected_slaves:0
master_replid:8371b4fb1155b71f4a04d3e1bc3e18c4a990aeeb
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:

Here are what some of the important fields mean:

  • role: The role of the server (either master or slave).
  • connected_slaves: The number of connected replica servers.
  • master_replid: The replication ID of the master.
  • master_repl_offset: The replication offset of the master.

In this stage, you’ll only need to support the role key. We’ll add support for other keys in later stages.

Tests

The tester will execute your program like this:

./your_program.sh --port <PORT>

It will then send the INFO command with replication as an argument.

$ redis-cli -p <PORT> info replication

Your server should respond with a bulk string where each line is a key value pair separated by a colon (:). The tester will only look for the role key and assert that the value is master.

Notes
  • In the response for the INFO command, you only need to support the role key for this stage. We’ll add support for the other keys in later stages.
  • The # Replication heading in the response is optional, and you can ignore it.
  • The response to INFO needs to be encoded as a bulk string.
    • An example valid response would be $11\r\nrole:master\r\n (the string role:master encoded as a bulk string)

Original stage ye5

3. The INFO command on a replica

In this stage, you’ll extend the INFO command to reflect a server’s role as a replica.

The --replicaof Flag

By default, your Redis server assumes the master role. When you pass the --replicaof flag, the server assumes the replica role instead.

For example:

./your_program.sh --port 6380 --replicaof "localhost 6379"

Here, we use the --replicaof flag to start a Redis server as a replica. The server will listen for connections on port 6380, but it will also connect to a master (another Redis server) running on localhost:6379 and replicate all its changes.

We’ll learn more about how this replication works in later stages.

For this stage, your primary task is to update the INFO replication command handler to check the server’s configuration:

  • If the user does not include the --replicaof flag, respond with role:master.
  • If the user includes the --replicaof flag, respond with role:slave.
Tests

The tester will execute your program like this:

./your_program.sh --port <PORT> --replicaof "<MASTER_HOST> <MASTER_PORT>"

It will then send the INFO command with a replication argument to your server.

$ redis-cli -p <PORT> INFO replication

Your program should respond with a bulk string where each line is a key-value pair separated by a colon (:). The tester will only look for the role key and assert that the value is slave.

Notes
  • Your program still needs to pass the tests for previous stages, so if --replicaof isn’t specified, you should default to the master role.
  • Just like the previous stages, you only need to support the role key in the response for this stage. We’ll add support for the other keys in later stages.
  • You don’t need to actually connect to the master server specified via --replicaof in this stage. We’ll get to that in later stages.

Original stage hc6

4. Initial replication ID and offset

In this stage, you’ll extend your INFO command to return the master_replid and master_repl_offset values.

The Replication ID and Offset

Every Redis master maintains two key pieces of information for managing replication: the replication ID and the replication offset.

The replication ID is a large pseudo-random string. This ID identifies the current history of the master’s dataset. When a master server boots for the first time or restarts, it resets its ID.

The replication offset tracks the number of bytes of commands the master has streamed to its replicas. This value is used to update the state of the replicas with changes made to the dataset. The offset starts at 0 when a master boots up and no replicas have connected yet.

In this stage, you’ll initialize a replication ID and offset for the master server:

  • The ID can be any pseudo-random alphanumeric string of 40 characters.
    • For this challenge, you don’t need to generate a random string. You can hardcode it instead.
    • As an example, you can hardcode 8371b4fb1155b71f4a04d3e1bc3e18c4a990aeeb as the replication ID.
  • The offset should be 0.

These two values should be returned as part of the INFO command output, under the master_replid and master_repl_offset keys, respectively.

Tests

The tester will execute your program like this:

./your_program.sh

It will then send the INFO command with the replication option to your server.

$ redis-cli INFO replication

Your program should respond with a bulk string where each line is a key-value pair separated by a colon (:). The tester will look for the following key-value pairs:

  • role: master
  • master_replid: A 40-character alphanumeric string
  • master_repl_offset: 0
Notes
  • Your code must pass the tests for previous stages, meaning you should still return the correct role key.

Original stage xc1

5. Send handshake (1/3)

In this stage, you’ll implement the first step of the replication handshake.

Handshake

When a replica connects to a master, it needs to go through a “handshake” before receiving updates from the master.

There are three steps to this handshake:

  1. The replica sends a PING to the master.
  2. The replica sends REPLCONF twice to the master.
  3. The replica sends PSYNC to the master.

We’ll learn more about REPLCONF and PSYNC in later stages. For now, we’ll focus on the first part of the handshake.

When your server starts in replica mode, it must connect to the specified master host and port, and then send the PING command.

The PING command must be sent encoded as a RESP array.

Tests

The tester will execute your program like this:

./your_program.sh --port <PORT> --replicaof "<MASTER_HOST> <MASTER_PORT>"

It will then assert that the replica connects to the master and sends the PING command as a RESP array (*1\r\n$4\r\nPING\r\n).

Original stage gl7

6. Send handshake (2/3)

In this stage, you’ll implement the second step of the replication handshake.

Handshake (Recap)

As a recap, there are three steps to the handshake:

  1. The replica sends a PING to the master (Handled in previous stages)
  2. The replica sends REPLCONF twice to the master
  3. The replica sends PSYNC to the master

For this stage, you’ll handle the second step of this process.

The REPLCONF Command

The REPLCONF command is used to configure a connected replica. After receiving a response to PING, the replica sends two REPLCONF commands one-by-one, waiting for a response after each.

  1. REPLCONF listening-port <PORT>: This tells the master which port the replica is listening on. This value is used for monitoring and logging, not for replication itself.
  2. REPLCONF capa psync2: This notifies the master of the replica’s capabilities.
    • capa stands for “capabilities”. It indicates that the next argument is a feature the replica supports.
    • psync2 signals that the replica supports the PSYNC2 protocol. PSYNC2 is an improved version of the partial synchronization feature used to resynchronize a replica with its master.
    • You can safely hardcode capa psync2 for now.

Both commands should be sent as RESP arrays, so the exact bytes will look something like this:

# REPLCONF listening-port <PORT>
*3\r\n$8\r\nREPLCONF\r\n$14\r\nlistening-port\r\n$4\r\n6380\r\n

# REPLCONF capa psync2
*3\r\n$8\r\nREPLCONF\r\n$4\r\ncapa\r\n$6\r\npsync2\r\n

For both commands, the master will respond with +OK\r\n. That’s the string OK encoded as a simple string. The replica should wait for this response before sending the next command.

Tests

The tester will execute your program like this:

./your_program.sh --port <PORT> --replicaof "<MASTER_HOST> <MASTER_PORT>"

It will then assert that the replica connects to the master and sends the following:

  1. The PING command
  2. The REPLCONF command with listening-port and <PORT> as the arguments
  3. The REPLCONF command with capa psync2 as the arguments

Notes

  • The response to REPLCONF will always be +OK\r\n.

Original stage eh4

7. Send handshake (3/3)

In this stage, you’ll implement the third step of the replication handshake.

Handshake (Recap)

As a recap, there are three steps to the handshake:

  • The replica sends a PING to the master (Handled in earlier stages)
  • The replica sends REPLCONF twice to the master (Handled in previous stages)
  • The replica sends PSYNC to the master
The PSYNC Command

After receiving a response to the second REPLCONF, the replica sends a PSYNC command to the master.

The PSYNC command is used to synchronize the state of the replica with the master. The command format is:

PSYNC <replication_id> <offset>

The command takes two arguments: the master’s current replication ID and the replica’s current offset.

For the replica’s first connection to the master:

  • The replication ID will be ? because the replica doesn’t know the master’s ID yet.
  • The offset will be -1 since the replica has no data from the master yet.

So the final command sent will be PSYNC ? -1, encoded as a RESP array:

*3\r\n$5\r\nPSYNC\r\n$1\r\n?\r\n$2\r\n-1\r\n

The master will respond with a simple string that looks like this:

+FULLRESYNC <REPL_ID> 0\r\n

You can ignore this response for now. We’ll get to handling it in later stages.

Tests

The tester will execute your program like this:

./your_program.sh --port <PORT> --replicaof "<MASTER_HOST> <MASTER_PORT>"

It will then assert that the replica connects to the master and sends the following commands:

  1. PING
  2. REPLCONF with listening-port and <PORT> as arguments
  3. REPLCONF with capa psync2 as arguments
  4. PSYNC with ? -1 as arguments

Original stage ju6

8. Receive handshake (1/2)

In this stage, we’ll start implementing support for receiving a replication handshake as a master.

Handshake (Recap)

Up until now, we’ve been implementing the handshake from the replica’s perspective. Now we’ll implement the same handshake on the master side.

As a recap, the master receives the following from the replica during the handshake:

  1. A PING command
  2. Two REPLCONF commands
  3. A PSYNC command

Your Redis server already supports the PING command, so there’s no additional work to do for the first step.

In this stage, you’ll add support for receiving the two REPLCONF commands as a master.

For the purposes of this challenge, you can safely ignore the arguments for both commands and simply respond with +OK\r\n. That’s the string OK encoded as a simple string

Tests

The tester will execute your program like this:

./your_program.sh --port <PORT>

It will then send the following commands:

  1. PING — expecting +PONG\r\n
  2. REPLCONF listening-port <PORT> — expecting +OK\r\n
  3. REPLCONF capa psync2 — expecting +OK\r\n

Original stage fj0

9. Receive handshake (2/2)

In this stage, you’ll add support for receiving the PSYNC command from the replica.

Handshake (Recap)

As a recap, the master receives the following for the handshake:

  1. A PING from the replica
  2. REPLCONF twice from the replica
  3. PSYNC from the replica

After the replica sends REPLCONF twice, it will send a PSYNC command with the arguments ? -1 to the master:

  • The replication ID is ? because the replica doesn’t know the master’s ID yet.
  • The offset is -1 since the replica has no data from the master yet.

The final command you’ll receive will look something like this:

*3\r\n$5\r\nPSYNC\r\n$1\r\n?\r\n$2\r\n-1\r\n

That’s ["PSYNC", "?", "-1"] encoded as a RESP array.

The master needs to respond with +FULLRESYNC <REPL_ID> 0\r\n, which is FULLRESYNC <REPL_ID> 0 encoded as a simple string. Here’s what the response means:

  • FULLRESYNC means that the master cannot perform an incremental update to the replica, and will start a full resynchronization.
  • <REPL_ID> is the replication ID of the master.
  • 0 is the replication offset of the master.

For example, if your replication ID is 8371b4fb1155b71f4a04d3e1bc3e18c4a990aeeb, you’d respond with:

+FULLRESYNC 8371b4fb1155b71f4a04d3e1bc3e18c4a990aeeb 0\r\n
Tests

The tester will execute your program like this:

./your_program.sh --port <PORT>

It will then connect to your TCP server as a replica and send the following commands:

  1. PING – expecting +PONG\r\n back
  2. REPLCONF listening-port <PORT> – expecting +OK\r\n back
  3. REPLCONF capa psync2 – expecting +OK\r\n back
  4. PSYNC ? -1 – expecting +FULLRESYNC <REPL_ID> 0\r\n back
Notes
  • In the response, <REPL_ID> needs to be replaced with the replication ID of the master, which you’ve initialized in previous stages.

Original stage vm3

10. Empty RDB transfer

In this stage, you’ll add support for sending an empty RDB file as a master.

Full Resynchronization

When a replica connects to a master for the first time, it sends a PSYNC ? -1 command. This is the replica’s way of telling the master that it doesn’t have any data yet and needs to be fully resynchronized.

The master responds in two steps:

  • It acknowledges with a FULLRESYNC response (Handled in previous stages)
  • It sends a snapshot of its current state as an RDB file.

The replica is expected to load the file into memory and replace its current state with the master’s data.

For this challenge, you don’t need to build an RDB file yourself. Instead, you can hardcode an empty RDB file, since we’ll assume the master’s database is always empty.

You can find the hex and base64 representation of an empty RDB file here. You need to decode these into binary contents before sending them to the replica.

The file is sent using the following format:

$<length_of_file>\r\n<binary_contents_of_file>

This is similar to how bulk strings are encoded, but without the trailing \r\n.

Tests

The tester will execute your program like this:

./your_program.sh --port <PORT>

It will then connect to your TCP server as a replica and execute the following commands:

  1. PING – expecting +PONG\r\n
  2. REPLCONF listening-port <PORT> – expecting +OK\r\n
  3. REPLCONF capa eof capa psync2 – expecting +OK\r\n
  4. PSYNC ? -1 – expecting +FULLRESYNC <REPL_ID> 0\r\n

After the last response, the tester will expect to receive an empty RDB file from your server.

The tester will accept any valid RDB file that is empty.

Notes
  • The RDB file should be sent like this: $<length>\r\n<contents>
    • <length> is the length of the file in bytes
    • <contents> is the binary contents of the file
    • Note that this is NOT a RESP bulk string and doesn’t contain a \r\n at the end.
  • If you want to learn more about the RDB file format, read this blog post. This challenge has a separate extension dedicated to reading RDB files.

Original stage cf8

11. Single-replica propagation

In this stage, you’ll add support for propagating write commands to a single replica as a master.

Command Propagation

After the replication handshake is complete and the master has sent the RDB file to the replica, the master starts propagating “write” commands to the replica.

Write commands are commands that modify the master’s dataset, such as SET and DEL. Commands like PING, ECHO, etc., are not considered “write” commands, so they aren’t propagated.

The Propagation Process

Command propagation happens over the replication connection. This is the same connection that was used for the handshake.

The propagated commands are sent as RESP arrays. For example, if the master receives SET foo bar as a command from a client, it’ll send *3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n to all connected replicas over their respective replication connections.

Replicas process commands received over the connection just like they would process commands received from a client, but with one difference: they don’t send responses back to the master. They just process the command silently and update their state.

Similarly, the master doesn’t wait for a response from the replica when propagating commands. It just sends the commands as they come in.

There is one exception to this “no response” rule: the REPLCONF GETACK command. We’ll learn about this command in later stages.

Tests

The tester will execute your program like this:

./your_program.sh --port <PORT>

It will then connect to your TCP server as a replica and complete the full handshake sequence covered in previous stages.

The tester will then wait for your server to send an RDB file.

Once the RDB file is received, the tester will send a series of write commands to your program (as a separate Redis client).

$ redis-cli SET foo 1
$ redis-cli SET bar 2
$ redis-cli SET baz 3

It will then assert that these commands were propagated to the replica in the correct order. The tester will expect to receive these commands:

  • Encoded as RESP arrays.
  • Sent on the same connection used for the handshake (replication connection).
Notes
  • Although replicas provide a listening-port during the handshake, it’s used only for monitoring/logging purposes, not for propagation. Redis propagates commands over the same TCP connection that the replica initiated during the handshake.
  • A true implementation would buffer the commands so that they can be sent to the replica after it loads the RDB file. For the purposes of this challenge, you can assume that the replica is ready to receive commands immediately after receiving the RDB file.

Original stage zn8

12. Multi-replica propagation

In this stage, you’ll extend your implementation of the master to support propagating commands to multiple replicas.

Command Propagation (Recap)

Once a replica completes the handshake and loads the RDB file, it is ready to start receiving live updates from the master.

Every write command executed on the master must be forwarded to all connected replicas, not just one. This ensures that every replica stays in sync with the master.

Tests

The tester will execute your program like this:

./your_program.sh --port <PORT>

It will then start multiple replicas that will each connect to your server, complete the handshake, and receive the initial RDB file.

Next, the tester will send SET commands to the master from a separate client.

$ redis-cli SET foo 1
$ redis-cli SET bar 2
$ redis-cli SET baz 3

It will then assert that each replica received those commands in the correct order.

Original stage hd5

13. Command processing

In this stage, you’ll implement the processing of propagated commands as a replica.

Command Processing

After the replica receives a command from the master, it processes it and applies it to its own state. This will work exactly like a regular command sent by a client. The key difference is that the replica must not send a response back to the master.

For example, if a master propagates SET foo 1 to a replica:

  • The replica must update its database to set the value of foo to 1.
  • Unlike commands from regular clients, the replica does not reply with +OK\r\n.
Tests

The tester will spawn a Redis master and execute your program as a replica like this:

./your_program.sh --port <PORT> --replicaof "<MASTER_HOST> <MASTER_PORT>"

Just like in the previous stages, your replica should complete the handshake with the master and receive an empty RDB file.

Once the RDB file is received, the master will propagate a series of write commands to your program:

SET foo 1 # propagated from master to replica
SET bar 2 # propagated from master to replica
SET baz 3 # propagated from master to replica

The tester will then issue GET commands to your program to check if the commands were processed correctly.

$ redis-cli GET foo # expecting `1` back
$ redis-cli GET bar # expecting `2` back
# ... and so on
Notes
  • The propagated commands are sent as RESP arrays. So the command SET foo 1 will be sent as *3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$1\r\n1\r\n.
  • It is not guaranteed that propagated commands will be sent one at a time. One TCP segment might contain bytes for multiple commands.

Original stage yg4

14. ACKs with no commands

In this stage, you’ll implement support for responding to the REPLCONF GETACK command as a replica.

ACKs

Normally, a replica processes propagated commands silently. However, the master needs a way to verify that a replica is “in sync” and hasn’t fallen behind. This is done using ACKs (acknowledgements).

Redis masters periodically ask replicas to send ACKs to check how much of the replication stream they’ve processed.

The REPLCONF GETACK command

When the master wants an update, it sends the command:

REPLCONF GETACK *

The exact command received by the replica will look something like this: *3\r\n$8\r\nreplconf\r\n$6\r\ngetack\r\n$1\r\n*\r\n. That’s ["replconf", "getack", "*"] encoded as a RESP array.

The replica receives this command over the replication connection (i.e., the connection used for the replication handshake) and responds with:

REPLCONF ACK <offset>

The offset is the number of bytes of commands processed by the replica. For this stage, you can hardcode the offset to 0. We’ll learn how to track offsets and update them in later stages.

Tests

The tester will execute your program like this:

./your_program.sh --port <PORT> --replicaof "<HOST> <PORT>"

Just like in the previous stages, your replica should complete the handshake with the master and receive an empty RDB file.

The tester will then send REPLCONF GETACK * to your replica.

It will expect to receive REPLCONF ACK 0 encoded as a RESP array (*3\r\n$8\r\nREPLCONF\r\n$3\r\nACK\r\n$1\r\n0\r\n).

Notes
  • After the master-replica handshake is complete, a replica should only send responses to REPLCONF GETACK commands. All other propagated commands (like PING, SET, etc.) should be read and processed, but a response should not be sent back to the master.

Original stage xv6

15. ACKs with commands

In this stage, you’ll extend your REPLCONF GETACK implementation to respond with the number of bytes of commands processed by the replica.

ACKs (Recap)

As a recap, a master uses ACKs to verify that its replicas are in sync with it and haven’t fallen behind. Each ACK contains an offset — the number of bytes of commands processed by the replica.

Offset tracking

A replica keeps its offset updated by tracking the total byte size of every command received from its master. This includes both write commands (like SET, DEL) and non-write commands (like PING, REPLCONF GETACK *).

After processing the received command (e.g., ["SET", "foo", "bar]), it adds the full RESP array byte length to its running offset.

An important rule for this process is that the offset should only include commands processed before the current REPLCONF GETACK * request.

For example:

  • A replica connects, completes the handshake, and the master sends REPLCONF GETACK *.
    • The replica responds with REPLCONF ACK 0 since no commands had been processed before this request.
  • Next, the master sends another REPLCONF GETACK *.
    • The replica responds with REPLCONF ACK 37, because the previous REPLCONF command consumed 37 bytes.
  • The master then sends a PING command.
    • The replica silently processes it, increments its offset by 14, and sends no response.
  • The next REPLCONF GETACK * arrives.
    • The replica responds with REPLCONF ACK 88 — that’s 37 (for the first REPLCONF), +37 (for the second REPLCONF), +14 (for the PING).

Notice that the current GETACK request itself is not included in the offset value.

Tests

The tester will execute your program like this:

./your_program.sh --port <PORT> --replicaof "<HOST> <PORT>"

Just like in the previous stages, your replica should complete the handshake with the master and receive an empty RDB file.

The master will then propagate a series of commands to your replica. These commands will be interleaved with REPLCONF GETACK * commands.

REPLCONF GETACK *    # expect: REPLCONF ACK 0

PING                 # replica processes silently
REPLCONF GETACK *    # expect: REPLCONF ACK 51
# 51 = 37 (first REPLCONF) + 14 (PING)

SET foo 1             # replica processes silently
SET bar 2             # replica processes silently
REPLCONF GETACK *    # expect: REPLCONF ACK 146
# 146 = 51 + 37 (second REPLCONF) + 29 (SET foo) + 29 (SET bar)

Your replica must calculate and return the exact offset at each step in the REPLCONF ACK <offset> response. Your response should also be encoded as a RESP array.

Notes
  • The offset should only include the number of bytes of commands processed before receiving the current REPLCONF GETACK command.
  • Although masters don’t propagate PING commands when received from clients (since they aren’t “write” commands), they may send PING commands to replicas to notify replicas that the master is still alive.

Original stage yd3

16. WAIT with no replicas

In this stage, you’ll implement support for the WAIT command on the master.

The WAIT command

The WAIT command is used to check how many replicas have acknowledged all previous write commands. This allows a client to measure the durability of a write command before considering it successful.

The command format is:

WAIT <numreplicas> <timeout>

Here’s what each argument means:

  • <numreplicas>: The minimum number of replicas that must acknowledge all previous write commands.
  • <timeout>: The maximum time (in milliseconds) the client is willing to wait.

For example:

$ redis-cli WAIT 3 5000
(integer) 2

Here, the client is asking the master to wait for 3 replicas (with a maximum timeout of 5000 ms). After the timeout passes, the master has only 2 replicas connected, so it immediately replies with 2 as a RESP integer.

For now, we’ll handle the simplest case: when the client needs 0 replicas and the master also has no replicas connected. In this case, WAIT should immediately return 0.

We’ll get to tracking the number of replicas and responding accordingly in later stages.

Tests

The tester will execute your program like this:

./your_program.sh

It will then connect to your master and send:

$ redis-cli WAIT 0 60000

The tester will expect to receive 0 immediately (as a RESP integer), since no replicas are connected.

Original stage my8

17. WAIT with no commands

In this stage, you’ll extend your WAIT implementation to handle the case where replicas are connected, but no commands have been sent.

WAIT with connected replicas

In previous stages, we handled the case where no replicas were connected, and the master could safely return 0.

Now, we’ll consider the case where some replicas are connected. Each replica will have completed the handshake and received the empty RDB file. But since no write commands have been sent yet, the replication offset is still 0.

In this situation, the master will return the number of connected replicas, since it knows they are all in sync at offset 0:

$ redis-cli WAIT 3 500
(integer) 7
$ redis-cli WAIT 7 500
(integer) 7
$ redis-cli WAIT 9 500
(integer) 7

In the example above, 7 replicas are connected. No matter how many replicas the client asks for, the master will reply with the number of connected replicas (7).

For this stage, you can ignore both arguments (<numreplicas> <timeout>) and simply return the number of connected replicas.

Tests

The tester will execute your program as a master like this:

./your_program.sh

It will then start multiple replicas that connect to your server. Each will complete the handshake and expect to receive an empty RDB file.

It will then connect to your master as a client and send commands like this:

$ redis-cli WAIT 3 500 # (expecting 7 back)
$ redis-cli WAIT 7 500 # (expecting 7 back)
$ redis-cli WAIT 9 500 # (expecting 7 back)

The response to each of these commands should be encoded as a RESP integer (i.e., :7\r\n).

Notes
  • Even if WAIT is called with a number less than the number of connected replicas, the master should return the count of connected replicas.
  • The number of replicas created in this stage will be random, so you can’t hardcode 7 as the response, like in the example above.

Original stage tu8

18. WAIT with multiple commands

In this stage, you’ll extend your WAIT implementation to handle the case where replicas are connected and have received write commands.

WAIT with propagated commands

In previous stages, we handled the cases where:

  • No replicas were connected, and the master could safely return 0.
  • Replicas were connected, but hadn’t received any write commands.

Now, we’ll handle the case where write commands have been sent to replicas. Since replication offsets are no longer 0, the master needs to check which replicas have successfully processed the latest write command before replying.

To do this, the master must send REPLCONF GETACK * to replicas if there are pending write commands since the last WAIT. Each replica will reply with its current offset (REPLCONF ACK <offset>).

The WAIT command should complete when either:

  • The required number of replicas has acknowledged all previous write commands, or
  • The timeout expires.

Either way, the master should return the number of replicas that acknowledged all previous write commands as a RESP integer.

Tests

The tester will execute your program as a master like this:

./your_program.sh

It will then start multiple replicas that connect to your server. Each will complete the handshake and expect to receive an empty RDB file.

Next, the tester will connect to your master as a client and send multiple write commands interleaved with WAIT commands:

$ redis-cli SET foo 123
$ redis-cli WAIT 1 500    # (must wait until either 1 replica has processed previous commands or 500ms have passed)

$ redis-cli SET bar 456
$ redis-cli WAIT 2 500    # (must wait until either 2 replicas have processed previous commands or 500ms have passed)
Notes
  • The returned number of replicas might be less than or greater than the expected number of replicas specified in the WAIT command.

Original stage na2

Back to contents

RDB Persistence

1. RDB file config

Welcome to the RDB Persistence Extension! In this extension, you’ll add support for reading RDB files (Redis Database files).

In this stage, you’ll add support for two configuration parameters related to RDB persistence, as well as the CONFIG GET command.

RDB files

An RDB file is a point-in-time snapshot of a Redis dataset. When RDB persistence is enabled, the Redis server syncs its in-memory state with an RDB file, by doing the following:

  1. On startup, the Redis server loads the data from the RDB file.
  2. While running, the Redis server periodically takes new snapshots of the dataset, in order to update the RDB file.
dir and dbfilename

The configuration parameters dir and dbfilename specify where an RDB file is stored:

  • dir – the path to the directory where the RDB file is stored (example: /tmp/redis-data)
  • dbfilename – the name of the RDB file (example: rdbfile)
The CONFIG GET command

The CONFIG GET command returns the values of configuration parameters.

It takes in one or more configuration parameters and returns a RESP array of key-value pairs:

$ redis-cli CONFIG GET dir
1) "dir"
2) "/tmp/redis-data"

Although CONFIG GET can fetch multiple parameters at a time, the tester will only send CONFIG GET commands with one parameter at a time.

Tests

The tester will execute your program like this:

./your_program.sh --dir /tmp/redis-files --dbfilename dump.rdb

It’ll then send the following commands:

$ redis-cli CONFIG GET dir
$ redis-cli CONFIG GET dbfilename

Your server must respond to each CONFIG GET command with a RESP array containing two elements:

  1. The parameter name, encoded as a RESP Bulk string
  2. The parameter value, encoded as a RESP Bulk string

For example, if the value of dir is /tmp/redis-files, then the expected response to CONFIG GET dir is:

*2\r\n$3\r\ndir\r\n$16\r\n/tmp/redis-files\r\n
Notes
  • You don’t need to read the RDB file in this stage, you only need to store dir and dbfilename. Reading from the file will be covered in later stages.
  • If your repository was created before 5th Oct 2023, it’s possible that your ./your_program.sh script is not passing arguments to your program. To fix this, you’ll need to edit ./your_program.sh. Check the update CLI args PR for details on how to do this.

Original stage zg5

2. Read a key

In this stage, you’ll add support for reading a single key from an RDB file.

RDB file format
Click to expand/collapse
RDB file format overview

Here are the different sections of the RDB file, in order:

  1. Header section
  2. Metadata section
  3. Database section
  4. End of file section

RDB files use special encodings to store different types of data. The ones relevant to this stage are “size encoding” and “string encoding.” These are explained near the end of this page.

The following breakdown of the RDB file format is based on Redis RDB File Format by Jan-Erik Rediger. We’ve only included the parts that are relevant to this stage.

Header section

RDB files begin with a header section, which looks something like this:

52 45 44 49 53 30 30 31 31  // Magic string + version number (ASCII): "REDIS0011".

The header contains the magic string REDIS, followed by a four-character RDB version number. In this challenge, the test RDB files all use version 11. So, the header is always REDIS0011.

Metadata section

Next is the metadata section. It contains zero or more “metadata subsections,” which each specify a single metadata attribute. Here’s an example of a metadata subsection that specifies redis-ver:

FA                             // Indicates the start of a metadata subsection.
09 72 65 64 69 73 2D 76 65 72  // The name of the metadata attribute (string encoded): "redis-ver".
06 36 2E 30 2E 31 36           // The value of the metadata attribute (string encoded): "6.0.16".

The metadata name and value are always string encoded.

Database section

Next is the database section. It contains zero or more “database subsections,” which each describe a single database. Here’s an example of a database subsection:

FE                       // Indicates the start of a database subsection.
00                       /* The index of the database (size encoded).
                            Here, the index is 0. */

FB                       // Indicates that hash table size information follows.
03                       /* The size of the hash table that stores the keys and values (size encoded).
                            Here, the total key-value hash table size is 3. */
02                       /* The size of the hash table that stores the expires of the keys (size encoded).
                            Here, the number of keys with an expiry is 2. */
00                       /* The 1-byte flag that specifies the value’s type and encoding.
                            Here, the flag is 0, which means "string." */
06 66 6F 6F 62 61 72     // The name of the key (string encoded). Here, it's "foobar".
06 62 61 7A 71 75 78     // The value (string encoded). Here, it's "bazqux".
FC                       /* Indicates that this key ("foo") has an expire,
                            and that the expire timestamp is expressed in milliseconds. */
15 72 E7 07 8F 01 00 00  /* The expire timestamp, expressed in Unix time,
                            stored as an 8-byte unsigned long, in little-endian (read right-to-left).
                            Here, the expire timestamp is 1713824559637. */
00                       // Value type is string.
03 66 6F 6F              // Key name is "foo".
03 62 61 72              // Value is "bar".
FD                       /* Indicates that this key ("baz") has an expire,
                            and that the expire timestamp is expressed in seconds. */
52 ED 2A 66              /* The expire timestamp, expressed in Unix time,
                            stored as an 4-byte unsigned integer, in little-endian (read right-to-left).
                            Here, the expire timestamp is 1714089298. */
00                       // Value type is string.
03 62 61 7A              // Key name is "baz".
03 71 75 78              // Value is "qux".

Here’s a more formal description of how each key-value pair is stored:

  1. Optional expire information (one of the following):
    • Timestamp in seconds: 1. FD 2. Expire timestamp in seconds (4-byte unsigned integer)
    • Timestamp in milliseconds: 1. FC 2. Expire timestamp in milliseconds (8-byte unsigned long)
  2. Value type (1-byte flag)
  3. Key (string encoded)
  4. Value (encoding depends on value type)
End of file section

This section marks the end of the file. It looks something like this:

FF                       /* Indicates that the file is ending,
                            and that the checksum follows. */
89 3b b7 4e f8 0f 77 19  // An 8-byte CRC64 checksum of the entire file.
Length encoding

Length-encoded values specify the length or size of something. Here are some examples:

  • The database indexes and hash table sizes are length encoded.
  • String encoding begins with a length-encoded value that specifies the number of characters in the string.
  • List encoding begins with a length-encoded value that specifies the number of elements in the list.

The first (most significant) two bits of a length-encoded value indicate how the value should be parsed. Here’s a guide (bits are shown in both hexadecimal and binary):

/* If the first two bits are 0b00:
   The length is the remaining 6 bits of the byte.
   In this example, the length is 10: */
0A
00001010

/* If the first two bits are 0b01:
   The length is the next 14 bits
   (remaining 6 bits in the first byte, combined with the next byte),
   in big-endian (read left-to-right).
   In this example, the length is 700: */
42 BC
01000010 10111100

/* If the first two bits are 0b10:
   Ignore the remaining 6 bits of the first byte.
   The length is the next 4 bytes, in big-endian (read left-to-right).
   In this example, the length is 17000: */
80 00 00 42 68
10000000 00000000 00000000 01000010 01101000

/* If the first two bits are 0b11:
   The remaining 6 bits specify a type of string encoding.
   See string encoding section. */
String encoding

A string-encoded value consists of two parts:

  1. The size of the string (size encoded).
  2. The string.

Here’s an example:

/* The 0x0D size specifies that the string is 13 characters long.
   The remaining characters spell out "Hello, World!". */
0D 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21

For sizes that begin with 0b11, the remaining 6 bits indicate a type of string format:

/* The 0xC0 size indicates the string is an 8-bit integer.
   In this example, the string is "123". */
C0 7B

/* The 0xC1 size indicates the string is a 16-bit integer.
   The remaining bytes are in little-endian (read right-to-left).
   In this example, the string is "12345". */
C1 39 30

/* The 0xC2 size indicates the string is a 32-bit integer.
   The remaining bytes are in little-endian (read right-to-left),
   In this example, the string is "1234567". */
C2 87 D6 12 00

/* The 0xC3 size indicates that the string is compressed with the LZF algorithm.
   You will not encounter LZF-compressed strings in this challenge. */
C3 ...
The KEYS command
Click to expand/collapse

The KEYS command returns all the keys that match a given pattern, as a RESP array:

$ redis-cli SET foo bar
OK
$ redis-cli SET baz qux
OK
$ redis-cli KEYS "f*"
1) "foo"

When the pattern is *, the command returns all the keys in the database:

$ redis-cli KEYS "*"
1) "baz"
2) "foo"

In this stage, you must add support for the KEYS command. However, you only need to support the * pattern.

Tests

The tester will create an RDB file with a single key and execute your program like this:

$ ./your_program.sh --dir <dir> --dbfilename <filename>

It’ll then send a KEYS "*" command to your server.

$ redis-cli KEYS "*"

Your server must respond with a RESP array that contains the key from the RDB file:

*1\r\n$3\r\nfoo\r\n
Notes
  • The RDB file provided by --dir and --dbfilename might not exist. If the file doesn’t exist, your program must treat the database as empty.
  • RDB files use both little-endian and big-endian to store numbers. See the MDN article on endianness to learn more.
  • To generate an RDB file, use the SAVE command.

Original stage jz6

3. Read a string value

In this stage, you’ll add support for reading the value corresponding to a key from an RDB file.

Just like with previous stages, we’ll stick to supporting RDB files that contain a single key for now.

The tester will create an RDB file with a single key and execute your program like this:

./your_program.sh --dir <dir> --dbfilename <filename>

It’ll then send a GET <key> command to your server.

$ redis-cli GET "foo"

The response to GET <key> should be a RESP bulk string with the value of the key.

For example, let’s say the RDB file contains a key called foo with the value bar. The expected response will be $3\r\nbar\r\n.

Strings can be encoded in three different ways in the RDB file format:

  • Length-prefixed strings
  • Integers as strings
  • Compressed strings

In this stage, you only need to support length-prefixed strings. We won’t cover the other two types in this challenge.

We recommend using this blog post as a reference when working on this stage.

Original stage gc6

4. Read multiple keys

In this stage, you’ll add support for reading multiple keys from an RDB file.

The tester will create an RDB file with multiple keys and execute your program like this:

$ ./your_program.sh --dir <dir> --dbfilename <filename>

It’ll then send a KEYS * command to your server.

$ redis-cli KEYS "*"

The response to KEYS * should be a RESP array with the keys as elements.

For example, let’s say the RDB file contains two keys: foo and bar. The expected response will be:

*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n
  • *2\r\n indicates that the array has two elements
  • $3\r\nfoo\r\n indicates that the first element is a bulk string with the value foo
  • $3\r\nbar\r\n indicates that the second element is a bulk string with the value bar

Original stage jw4

5. Read multiple string values

In this stage, you’ll add support for reading multiple string values from an RDB file.

The tester will create an RDB file with multiple keys and execute your program like this:

$ ./your_program.sh --dir <dir> --dbfilename <filename>

It’ll then send multiple GET <key> commands to your server.

$ redis-cli GET "foo"
$ redis-cli GET "bar"

The response to each GET <key> command should be a RESP bulk string with the value corresponding to the key.

Original stage dq3

6. Read value with expiry

In this stage, you’ll add support for reading values that have an expiry set.

The tester will create an RDB file with multiple keys. Some of these keys will have an expiry set, and some won’t. The expiry timestamps will also be random, some will be in the past and some will be in the future.

The tester will execute your program like this:

$ ./your_program.sh --dir <dir> --dbfilename <filename>

It’ll then send multiple GET <key> commands to your server.

$ redis-cli GET "foo"
$ redis-cli GET "bar"

When a key has expired, the expected response is $-1\r\n (a “null bulk string”).

When a key hasn’t expired, the expected response is a RESP bulk string with the value corresponding to the key.

Original stage sm4

Back to contents

AOF Persistence

1. Default AOF options

In this stage, you’ll set up default values for AOF-related configuration options.

AOF Persistence in Redis

Redis keeps all its data in memory, which makes it fast but vulnerable. If the server crashes, everything is gone. AOF (Append Only File) is one way to solve this. When enabled, the server logs every write command to a file, and on restart, it replays the file to rebuild its state.

The AOF behavior is controlled by several configuration options. For this stage, you’ll set up their default values so they can be retrieved with CONFIG GET. You don’t need to implement any actual persistence logic yet.

Here are the options and their defaults:

Option Purpose Default
dir The base directory where Redis stores its data files Current working directory at startup
appendonly Controls whether AOF persistence is enabled or disabled no
appenddirname The subdirectory under dir where AOF and manifest files are stored appendonlydir
appendfilename The name of the append-only file that records write operations appendonly.aof
appendfsync How often buffered writes are flushed to the AOF file on disk everysec
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then query each option using CONFIG GET:

$ redis-cli CONFIG GET dir
1) "dir"
2) "/path/to/current/directory"

$ redis-cli CONFIG GET appendonly
1) "appendonly"
2) "no"

$ redis-cli CONFIG GET appenddirname
1) "appenddirname"
2) "appendonlydir"

$ redis-cli CONFIG GET appendfilename
1) "appendfilename"
2) "appendonly.aof"

$ redis-cli CONFIG GET appendfsync
1) "appendfsync"
2) "everysec"

Each response is a RESP array with two bulk strings: the option name and its value. For example, CONFIG GET appendonly should return:

*2\r\n$10\r\nappendonly\r\n$2\r\nno\r\n

The tester will verify that:

  • Each CONFIG GET returns a two-element RESP array
  • The option name and default value are correct for each option
Notes
  • You don’t need to implement any AOF persistence logic in this stage. Just store and return the default values.
  • If you’ve already implemented CONFIG GET for other options in a previous challenge, you may just need to add these new keys to your existing configuration.

Original stage uj3

2. AOF options from flags

In this stage, you’ll accept AOF configuration values from command-line flags.

Overriding Defaults With Flags

In previous stages, you set up default values for AOF options. Now you’ll allow those defaults to be overridden by command-line flags: --dir, --appendonly, --appenddirname, --appendfilename, and --appendfsync.

When a flag is provided, its value takes precedence over the default. When a flag is omitted, the default from previous stages still applies.

Tests

The tester will execute your program with some or all of the flags:

$ ./your_program.sh --dir <dir> --appendonly yes --appenddirname <append_dir_name> --appendfilename <append_file_name> --appendfsync everysec

It will then query each option using CONFIG GET:

$ redis-cli CONFIG GET dir
$ redis-cli CONFIG GET appendonly
$ redis-cli CONFIG GET appenddirname
$ redis-cli CONFIG GET appendfilename
$ redis-cli CONFIG GET appendfsync

Each response should return the value passed via the corresponding flag. For example, if the program is started with --appendonly yes, then CONFIG GET appendonly should return:

*2\r\n$10\r\nappendonly\r\n$3\r\nyes\r\n

The tester will verify that:

  • Each CONFIG GET returns the value from the corresponding command-line flag
  • Options without flags still return their default values
Notes
  • You don’t need to implement any AOF persistence logic in this stage. Just parse the flags and return the values from CONFIG GET.
  • If you already parse command-line flags for other options (like --port), you can follow the same approach for these new flags.
  • You don’t need to handle duplicate flags or any specific flag ordering. The tester will pass each flag at most once.

Original stage vd9

3. Create append-only directory

In this stage, you’ll create the append-only directory when AOF persistence is enabled.

Creating the Append-Only Directory

Now that your server can accept AOF configuration from command-line flags, it’s time to start acting on them. When the server starts with --appendonly yes, it needs a directory to store its AOF files in. This directory lives inside the dir path and is named according to the appenddirname option.

For example, if the server is started with:

$ ./your_program.sh --dir /tmp/redis-data --appendonly yes --appenddirname appendonlydir

It should create the directory /tmp/redis-data/appendonlydir/ if it doesn’t already exist.

If --appendonly is not set to yes, the directory should not be created.

Tests

The tester will execute your program like this:

$ ./your_program.sh --dir <dir> --appendonly yes --appenddirname <append_dir_name> --appendfilename <append_file_name>

The tester will verify that:

  • The directory <dir>/<append_dir_name> has been created
  • The directory exists before any client commands are sent (it should be created at startup)
Notes
  • You don’t need to create any files inside the directory yet. That comes in later stages.
  • If the directory already exists, your server should not return an error.

Original stage fm0

4. Create append-only file

In this stage, you’ll create the append-only file when AOF persistence is enabled.

Creating the Append-Only File

Along with the append-only directory, your server also needs to create an empty AOF file inside it at startup.

The file follows a specific naming convention: <appendfilename>.1.incr.aof. The .1.incr suffix indicates this is the first incremental AOF file. Redis uses incremental files to record commands as they come in, which it can replay later to restore state after a restart.

For example, if the server is started with:

$ ./your_program.sh --dir /tmp/redis-data --appendonly yes --appenddirname appendonlydir --appendfilename appendonly.aof

It should create an empty file at /tmp/redis-data/appendonlydir/appendonly.aof.1.incr.aof.

Tests

The tester will execute your program like this:

$ ./your_program.sh --dir <dir> --appendonly yes --appenddirname <append_dir_name> --appendfilename <append_file_name>

The tester will then verify that:

  • The directory <dir>/<append_dir_name> exists
  • An empty file <dir>/<append_dir_name>/<append_file_name>.1.incr.aof is created
Notes
  • The file should be created at startup, not on the first write command.
  • You don’t need to write any content to the file yet. That comes in later stages.

Original stage dw4

5. Create manifest file

In this stage, you’ll create a manifest file alongside the append-only file.

The Manifest File

The manifest file tells Redis which AOF files exist and in what order they should be replayed during recovery. It follows the naming convention <appendfilename>.manifest and lives in the same directory as the AOF file.

The manifest file contains a single line describing the AOF file you created earlier:

file <appendfilename>.1.incr.aof seq 1 type i

Here’s what each part means:

Field Value Meaning
file <appendfilename>.1.incr.aof The name of the AOF file
seq 1 Sequence number for this file
type i An incremental file, meaning it contains write commands appended one by one

For example, if the server is started with --appendfilename appendonly.aof, the manifest file would be named appendonly.aof.manifest and should contain:

file appendonly.aof.1.incr.aof seq 1 type i

You can hardcode the sequence number and type for this stage.

Tests

The tester will execute your program like this:

$ ./your_program.sh --dir <dir> --appendonly yes --appenddirname <append_dir_name> --appendfilename <append_file_name>

It will then verify that:

  • The directory <dir>/<append_dir_name> exists
  • The empty AOF file <dir>/<append_dir_name>/<append_file_name>.1.incr.aof exists
  • The manifest file <dir>/<append_dir_name>/<append_file_name>.manifest exists
  • The manifest file contains the line file <append_file_name>.1.incr.aof seq 1 type i
Notes
  • The manifest file should be created at startup alongside the AOF file.
  • Each token in the manifest line is separated by a single space. No tabs or extra spaces.
  • Make sure the manifest line ends with a newline character.

Original stage pb9

6. Write a single command

In this stage, you’ll write a single modifying command to the append-only file.

Writing to the Append-Only File

So far, you’ve created the AOF directory, file, and manifest at startup. Now you’ll start using them. When --appendonly yes is set and your server processes a write command (like SET), it should append that command to the append-only file in RESP format.

Your server should read the manifest to find the name of the AOF file to write to. The manifest’s type i entry tells you which file is the active incremental file.

For example, if your server receives:

$ redis-cli SET foo 100

It should append the following to the AOF file:

*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\n100\r\n

This is the same RESP encoding your server already uses for communication. The command is stored exactly as it was received, so it can be replayed on restart to rebuild the state.

The appendfsync always Option

When appendfsync is set to always, the server must flush the write to disk before sending a response to the client. This guarantees that no acknowledged write can be lost, even if the server crashes immediately after responding.

Tests

The tester will create the following under <dir>/<append_dir_name>:

  • A manifest whose type i entry names a file <random_file_name>.1.incr.aof
  • The corresponding empty AOF file: <random_file_name>.1.incr.aof

The tester will execute your program like this:

$ ./your_program.sh --dir <dir> --appendonly yes --appenddirname <append_dir_name> --appendfilename <append_file_name> --appendfsync always

It will then send a single write command:

$ redis-cli SET <key> <value>

The tester will verify that:

  • The command is appended to the AOF file named in the manifest (not the default <appendfilename>.1.incr.aof)
  • The command is written in a valid RESP format
  • The write is flushed to disk before the client receives a response
Notes
  • You must read the manifest to determine which file to write to. The tester intentionally uses a non-default filename to make sure your server follows the manifest.
  • You don’t need to handle --appendfsync everysec in this stage. Only always is tested.
  • The RESP encoding of the command is the same format you’re already using for client-server communication. You’re just writing it to a file instead of a socket.

Original stage dc8

7. Write multiple commands

In this stage, you’ll extend AOF logging to handle multiple write commands.

Appending Multiple Commands

Each write command should be appended to the AOF file in the order it was received, so the file builds up a complete log of all modifications. This applies to any command that modifies data (like SET, DEL, INCR, LPUSH, etc.), not just SET.

For example, if the server receives:

$ redis-cli SET foo 100
$ redis-cli SET bar 200

The AOF file should contain both commands in order:

*3\r\n
$3\r\n
SET\r\n
$3\r\n
foo\r\n
$3\r\n
100\r\n
*3\r\n
$3\r\n
SET\r\n
$3\r\n
bar\r\n
$3\r\n
200\r\n

(The \r\n sequences above are shown on separate lines for readability. In the actual file, each command is a continuous sequence of bytes.)

Each command is appended immediately after the previous one with no separators between them. On replay, the RESP framing (*3\r\n...) is enough to tell where one command ends and the next begins.

Tests

The tester will create the following under <dir>/<append_dir_name>:

  • A manifest whose type i entry names a file <random_file_name>.1.incr.aof
  • The corresponding empty AOF file: <random_file_name>.1.incr.aof

The tester will execute your program like this:

$ ./your_program.sh --dir <dir> --appendonly yes --appenddirname <append_dir_name> --appendfilename <append_file_name> --appendfsync always

It will then send two write commands with different keys:

$ redis-cli SET <key1> <value1>
$ redis-cli SET <key2> <value2>

The tester will verify that:

  • Both commands appear in the append-only file in the order they were sent
  • Each command is encoded in a valid RESP format
  • The writes are flushed to disk before the client receives a response (since appendfsync is always)
Notes
  • If your implementation from earlier stages already appends (rather than overwrites), this stage may already pass without changes.
  • You must read the manifest to determine which file to write to. The tester uses a non-default filename.
  • You don’t need to handle --appendfsync everysec in this stage.

Original stage fi1

8. Filter write commands

In this stage, you’ll ensure that only write commands are logged to the append-only file.

Filtering Non-Modifying Commands

Commands that don’t modify data, like PING, GET, and ECHO, should never be written to an AOF file since they don’t change any state.

If the server receives a mix of read and write commands, only the write commands should appear in the AOF file in the order they were received.

For example, if a client sends:

$ redis-cli SET foo 1
$ redis-cli GET foo
$ redis-cli PING
$ redis-cli ECHO hello
$ redis-cli SET bar 2

The AOF file should contain only the two SET commands:

*3\r\n
$3\r\n
SET\r\n
$3\r\n
foo\r\n
$1\r\n
1\r\n
*3\r\n
$3\r\n
SET\r\n
$3\r\n
bar\r\n
$1\r\n
2\r\n

(The \r\n sequences above are shown on separate lines for readability. In the actual file, each command is a continuous sequence of bytes.)

No trace of GET, PING, or ECHO should appear in the file.

Tests

The tester will execute your program like this:

$ ./your_program.sh --dir <dir> --appendonly yes --appenddirname <append_dir_name> --appendfilename <append_file_name> --appendfsync always

It will send a mix of modifying and non-modifying commands, including PING, GET, ECHO, and CONFIG GET interleaved with at least one write command.

The tester will verify that:

  • The append-only file contains only the write commands, in order
  • No bytes from non-modifying commands appear in the file
  • Each logged command is in valid RESP format
Notes
  • If you already have a way to distinguish write commands from read commands (e.g., for replication), you can reuse that logic here.
  • You must read the manifest to determine which file to write to. The tester uses a non-default filename.
  • You don’t need to handle --appendfsync everysec in this stage.

Original stage ep6

9. Replay a single command

In this stage, you’ll restore the state on startup by replaying commands from the append-only file.

Replaying the Append-Only File

In earlier stages, you wrote commands to the AOF file as they came in. Now you’ll do the reverse: on startup, read those commands back and replay them to rebuild the database.

When the server starts with --appendonly yes and the append-only directory already exists, it should:

  1. Read the manifest file at <dir>/<append_dir_name>/<append_file_name>.manifest
  2. Find the entry with type i (the incremental file)
  3. Open that file and parse the RESP-encoded commands inside it
  4. Execute each command as if a client had sent it

After replaying, the database should be in the same state it was in when the commands were originally written. This is how Redis recovers data after a restart.

Tests

The tester will create a directory <dir>/<append_dir_name> containing:

  • An AOF file <random_file_name>.1.incr.aof with a single RESP-encoded SET command
  • A manifest file <append_file_name>.manifest pointing to that AOF file:
file <random_file_name>.1.incr.aof seq 1 type i

The tester will execute your program like this:

$ ./your_program.sh --dir <dir> --appendonly yes --appenddirname <append_dir_name> --appendfilename <append_file_name>

After startup, the tester will send a GET command to verify the replayed data:

$ redis-cli GET <key>

The tester will verify that:

  • The value returned by GET matches the value from the SET command in the AOF file
  • Your server read the AOF file named in the manifest, not a hardcoded filename
Notes
  • You must read the manifest to find which file to replay. The tester intentionally uses a non-default filename (<random_file_name>.1.incr.aof instead of <append_file_name>.1.incr.aof) to make sure your server follows the manifest.
  • The AOF file contains the same RESP format you already parse from client connections. You can reuse your existing RESP parser here.

Original stage xz2

10. Replay multiple commands

In this stage, you’ll extend replay to handle append-only files with multiple commands.

Replaying Multiple Commands

An append-only file typically contains many commands, not just one. Your server needs to parse the file as a sequence of RESP-encoded commands and replay each one in order, just as if a client had sent them live.

Since RESP is self-framing (each command starts with *<n>\r\n indicating its length), you can read commands one after another until you reach the end of the file. Each command you parse should be executed against your server’s state before moving on to the next.

After replaying all commands, your database should reflect the cumulative effect of every write in the file.

Tests

The tester will create a directory <dir>/<append_dir_name> containing:

  • An AOF file <random_file_name>.1.incr.aof with multiple RESP-encoded commands (e.g., several SET commands for different keys)
  • A manifest file <append_file_name>.manifest pointing to that AOF file:
file <random_file_name>.1.incr.aof seq 1 type i

The tester will execute your program like this:

$ ./your_program.sh --dir <dir> --appendonly yes --appenddirname <append_dir_name> --appendfilename <append_file_name>

After startup, the tester will send several GET commands to verify each key was restored:

$ redis-cli GET <key1>
$ redis-cli GET <key2>
...

The tester will verify that:

  • Each GET returns the value from the corresponding command in the AOF file
  • All commands from the AOF file were replayed, not just the first one
Notes
  • If your implementation from earlier stages already loops through the file until EOF, this stage may already pass without changes.
  • You must read and replay from the file named in the manifest, not from the hardcoded filename <append_file_name>.1.incr.aof.
  • RESP is self-framing, so you don’t need any separator between commands. Just keep parsing until you run out of bytes.

Original stage kn2

Back to contents

Pub/Sub

1. Subscribe to a channel

In this stage, you’ll add support for the SUBSCRIBE command.

The SUBSCRIBE Command

The SUBSCRIBE command registers the client as a subscriber to a channel.

Example Usage:

$ redis-cli
> SUBSCRIBE mychan
1) "subscribe"
2) "mychan"
3) (integer) 1
Reading messages... (press Ctrl-C to quit or any key to type command)

The response is a RESP Array which contains three elements:

  1. “subscribe” (as a RESP bulk string)
  2. The channel name (as a RESP bulk string)
  3. The number of channels this client has subscribed to so far (as a RESP integer)
Tests

The tester will run your program like this:

$ ./your_program.sh

It will then send a SUBSCRIBE command with a channel name.

$ redis-cli SUBSCRIBE foo

The tester will then expect the response to be ["subscribe", "foo", 1], which is encoded in RESP as:

*3\r\n
$9\r\n
subscribe\r\n
$3\r\n
foo\r\n
:1\r\n
Notes
  • In this stage, you’ll only need to handle a SUBSCRIBE command being sent once and from a single client. We’ll get to handling multiple SUBSCRIBE commands in later stages.

Original stage mx3

2. Subscribe to multiple channels

In this stage, you’ll add support for subscribing to multiple channels using the SUBSCRIBE command.

Multiple SUBSCRIBE commands

A client can send SUBSCRIBE multiple times to subscribe to different channels. For example:

$ redis-cli
> SUBSCRIBE channel_1
1) "subscribe"
2) "channel_1"
3) (integer) 1

(subscribed mode)> SUBSCRIBE channel_2
1) "subscribe"
2) "channel_2"
3) (integer) 2

A client can also subscribe to the same channel multiple times, but the total subscribed channels count (returned as the 3rd item in the response array) won’t change.

For example:

$ redis-cli
> SUBSCRIBE channel_1
1) "subscribe"
2) "channel_1"
3) (integer) 1

# The count remains 1 since channel is same
(subscribed mode)> SUBSCRIBE channel_1
1) "subscribe"
2) "channel_1"
3) (integer) 1

The subscribed channels count is per-client, i.e. how many channels the current client is subscribed to.

Tests

The tester will run your program like this:

$ ./your_program.sh

It will then spawn a client and send multiple SUBSCRIBE commands specifying a new channel each time.

$ redis-cli
> SUBSCRIBE foo
# Expect ["subscribe", "foo", 1]

> SUBSCRIBE bar
# Expect ["subscribe", "bar", 2]

> SUBSCRIBE bar
# Expect ["subscribe", "bar", 2]

The tester will repeat this with other clients and verify that the subscribed channel counts are maintained per-client.

Original stage zc8

3. Enter subscribed mode

In this stage, you’ll add support for marking a client as having entered Subscribed mode.

Subscribe Mode

After a subscribe command is sent, a client enters “Subscribed mode”. In this mode, only a subset of commands is allowed:

  • SUBSCRIBE
  • UNSUBSCRIBE
  • PSUBSCRIBE
  • PUNSUBSCRIBE
  • PING
  • QUIT

The server will reject any other commands with an error, example:

$ redis-cli
> SUBSCRIBE channel
1) "subscribe"
2) "channel"
3) (integer) 1

(subscribed mode)> ECHO hey
(error) ERR Can't execute 'echo': only (P|S)SUBSCRIBE / (P|S)UNSUBSCRIBE / PING / QUIT / RESET are allowed in this context
Tests

The tester will run your program like this:

$ ./your_program.sh

It will then send a SUBSCRIBE command to your server to enter Subscribed mode:

$ redis-cli
> SUBSCRIBE foo
# Expecting ["subscribe", "foo", 1]

The tester will then send a series of commands, which might be allowed or un-allowed for subscribed mode.

For un-allowed commands (like SET, GET, and ECHO) the tester will verify that your server responds with the following error:

> SET key value
- ERR Can't execute 'set': only (P|S)SUBSCRIBE / (P|S)UNSUBSCRIBE / PING / QUIT / RESET are allowed in this context 

The tester only verifies that error message starts with “ERR Can’t execute ‘<command_name>'”, so you’re free to use a flexible error message and not stick to the exact format that Redis uses.

For the SUBSCRIBE command, the tester will verify that the response is its usual response.

> SUBSCRIBE bar
# Expecting ["subscribe", "bar", 2] as RESP-encoded array
Notes
  • For un-allowed commands, the tester is lenient in checking error messages so you don’t have to stick to the exact format Redis uses. The exact format it checks for is ERR Can't execute '<command>' (case-insensitive). Examples of error message strings that will pass tests:

    • ERR Can't execute 'set' in subscribed mode
    • ERR can't execute 'SET' when one or more subscriptions exist
  • In subscribed mode, PING has a different response (it doesn’t respond with +PONG\r\n). We’ll get to this in later stages.

Original stage aw8

4. PING in subscribed mode

In this stage, you’ll add support for responding to PING when a client is in subscribed mode.

PING in subscribed mode

If a ping command is issued from a client after it enters subscribed mode, Redis does not respond with the usual response (+PONG\r\n). Instead it responds with a RESP array of two elements:

  1. “pong” (encoded as a bulk string)
  2. “” (empty bulk string)
Tests

The tester will run your program like this:

$ ./your_program.sh

It will then send a SUBSCRIBE command to your server to enter Subscribed mode:

$ redis-cli
> SUBSCRIBE foo
# Expecting ["subscribe", "foo", 1]

The tester will then send a PING command.

> PING 

It will expect the response to be an RESP-encoded array ["pong", ""], which would look like this:

*2\r\n
$4\r\n
pong\r\n
$0\r\n
\r\n

The tester will also send a PING command using a separate client, which is not subscribed to any channels.

> PING

It will expect the response to be +PONG\r\n, which is “PONG” encoded as a RESP simple string.

Original stage lf1

5. Publish a message

In this stage, you’ll add support for the PUBLISH command.

The PUBLISH Command

The PUBLISH command delivers a message to all clients subscribed to a channel.

> PUBLISH channel_name message_contents
(integer) 3

The response to the command is the number of clients that are subscribed to the channel.

In this stage, you will only implement responding back to the PUBLISH command. You don’t need to deliver the message to clients yet — we’ll get to this in later stages.

Tests

The tester will run your program like this:

$ ./your_program.sh

It will then spawn multiple clients that listen on multiple channels.

# Client 1 subscribes to channel "foo"
$ redis-cli
> SUBSCRIBE foo

# Client 2 subscribes to channel "bar"
$ redis-cli
> SUBSCRIBE bar

# Client 3 subscribes to channel "bar"
$ redis-cli
> SUBSCRIBE bar

The tester will then publish messages to different channels using PUBLISH and check whether the response matches the number of clients subscribed to the channel.

$ redis-cli PUBLISH bar "msg"
(integer) 2

In the above example, the expected response is 2 (encoded as a RESP integer) since 2 clients are subscribed to channel bar.

Similarly for the foo channel

$ redis-cli PUBLISH foo "msg"
(integer) 1

The tester expects the response to be 1 (encoded as a RESP integer) since only 1 client is subscribed to it.

Original stage hf2

6. Deliver messages

In this stage, you will add support for delivering published messages to subscribed clients.

Delivering messages

When a client runs PUBLISH the command, the message is “delivered” to all clients currently subscribed to the channel.

For example, if a client was subscribed to channel_1 and the message hello was sent, it would see something like this:

$ redis-cli
> SUBSCRIBE channel_1
1) "subscribe"
2) "channel_1"
3) (integer) 1

# (client is now in subscribed mode)

# When a message is published, it receives the following array: 
1) "message"
2) "channel_1"
3) "hello"

Each subscribed client receives an array with 3 elements:

  1. “message”(as a RESP bulk string)
  2. The channel name (as a RESP bulk string)
  3. The message contents (as a RESP bulk string)

In this case, each subscribed client will receive ["message", "channel_1", "hello"], encoded as:

*3\r\n
$7\r\n
message\r\n
$9\r\n
channel_1\r\n
$5\r\n
hello\r\n
Tests

The tester will run your program like this:

$ ./your_program.sh

It will then spawn multiple clients that listen on multiple channels.

# Client 1 subscribes to foo
$ redis-cli
> SUBSCRIBE foo

# Client 2 subscribes to foo
$ redis-cli
> SUBSCRIBE foo

# Client 3 subscribes to bar
$ redis-cli
> SUBSCRIBE bar

The tester will then spawn a separate client and send PUBLISH commands for random channels.

$ redis-cli
> PUBLISH foo "hello"
2
> PUBLISH bar "world"
1

It’ll verify the PUBLISH commands returns the number of clients subscribed to the channel.

For every client, it’ll also assert that the client receives the message if it is subscribed. The tester will verify that each subscribed client receives an array like this: ["message", "foo", "hello"]. When RESP-encoded, this looks like:

*3\r\n
$7\r\n
message\r\n
$3\r\n
foo\r\n
$5\r\n
hello\r\n

If a client isn’t subscribed to a channel, the tester will validate that it doesn’t receive messages sent to that channel.

Original stage dn4

7. Unsubscribe

In this stage, you’ll add support for the UNSUBSCRIBE command, which is used to unsubscribe from a channel.

The UNSUBSCRIBE Command

This command removes the client from one or more channels. Example usage:

$ redis-cli
> SUBSCRIBE foo
1) "subscribe"
2) "foo"
3) (integer) 1
(subscribed mode)> SUBSCRIBE bar
1) "subscribe"
2) "bar"
3) (integer) 2
(subscribed mode)> UNSUBSCRIBE foo
1) "unsubscribe"
2) "foo"
3) (integer) 1
(subscribed mode)> UNSUBSCRIBE bar
1) "unsubscribe"
2) "bar"
3) (integer) 0

When unsubscribed, the server replies with a RESP Array with 3 elements:

  1. “unsubscribe” (as a RESP bulk string)
  2. The channel name (as a RESP bulk string)
  3. Count of remaining channels the client has subscribed to (as a RESP integer)

When unsubscribing from a channel that has not been subscribed yet, it returns the array with no change in the remaining channels count. For eg,

$ redis-cli
> subscribe foo
1) "subscribe"
2) "foo"
3) (integer) 1

(subscribed mode)> unsubscribe bar
1) "unsubscribe"
2) "bar"
3) (integer) 1
Tests

The tester will run your program like this:

$ ./your_program.sh

It will then spawn multiple clients that listen on multiple channels:

# Client 1 subscribes to 'foo' and 'baz'
$ redis-cli
> SUBSCRIBE foo
> SUBSCRIBE baz

# Client 2 subscribes to 'foo' and 'bar'
$ redis-cli
> SUBSCRIBE foo
> SUBSCRIBE bar

The tester will then spawn a separate client that publishes messages to random channels.

$ redis-cli
> PUBLISH foo "before-unsubscribe"

It will verify that any clients subscribed to the channel receive the message, and that other clients don’t.

The tester will then issue random UNSUBSCRIBE commands to the subscribed clients:

# In client 1, which was subscribed to 'foo' and 'baz'
> UNSUBSCRIBE foo
# Expects ["unsubscribed", "foo", 1] as an RESP array

Finally, the tester will again publish messages to random channels:.

> PUBLISH foo "after-unsubscribe"

It will verify that any clients subscribed to the channel receive the message, and that other clients don’t.

Original stage ze9

Back to contents

Sorted Sets

1. Create a sorted set

In this stage, you’ll add support for creating a sorted set using the ZADD command.

Redis Sorted Sets

Sorted sets are one of the data types that Redis supports. A sorted set is a collection of unique elements, where each element is associated with a floating-point score. Unlike regular sets, sorted sets maintain elements in a defined order based on their scores.

This makes them useful for use cases like leaderboards, priority queues, or any scenario where you need fast access to items sorted by a numerical value.

For example, if you were using sorted sets to store user rankings in a game leaderboard, the contents of the sorted set might look like this:

racer_scores:
    - member: "Ford"
      score: 6.1
    - member: "Royce"
      score: 8.2
    - member: "Sam-Bodden"
      score: 8.2
    - member: "Prickett"
      score: 14.5

Sorted sets are ordered based on increasing scores.

The ZADD Command

The ZADD command is used to add a member to a sorted set.

If the sorted set does not exist, it is created and the member is added to it.

Example usage:

> ZADD racer_scores 8.0 "Sam"
(integer) 1

The ZADD command takes the key, a score, and the member name as arguments. It returns an integer representing the number of new members added to the sorted set.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a ZADD command specifying a key, value and score.

$ redis-cli ZADD zset_key 10.0 zset_member

The tester will verify that the response to the command is :1\r\n, which is 1 (the number of members added to the sorted set), encoded as a RESP Integer.

Notes
  • In this stage, you’ll only need to handle creating a new sorted set with a single member. We will get to adding new members to existing sorted set in the later stages.

  • It is recommended to store the score as a 64 bit floating point number for highest precision as the official Redis implementation uses double.

  • We suggest that you implement sorted sets using a data structure where the members are stored in a sorted fashion according to their scores. It’ll come in handy in the later stages.

Original stage ct1

2. Add members

In this stage, you’ll add support for adding elements to an existing sorted set.

Adding elements using ZADD

The ZADD command can be used to add a new member to an existing sorted set, or update the score of an existing member. It returns the count of new members added to the sorted set as an integer.

Example usage:

> ZADD zset_key 0.0043 foo
(integer) 1
> ZADD zset_key 8.0 bar
(integer) 1

# No new members were added
> ZADD zset_key 10.0 bar
(integer) 0
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a ZADD command to create a new sorted set.

$ redis-cli ZADD zset_key 20.0 zset_member1 (Expecting ":1\r\n")

The tester will then send the ZADD command a few times to add new members.

$ redis-cli
> ZADD zset_key 30.1 zset_member2 (Expecting ":1\r\n")
> ZADD zset_key 40.2 zset_member3 (Expecting ":1\r\n")
> ZADD zset_key 50.3 zset_member4 (Expecting ":1\r\n")

The tester expects the response to be :1\r\n whenever a new member is added.

It will then update the score of an existing member.

> ZADD zset_key 100.0 zset_member1 (Expecting ":0\r\n")

The tester expects the response to be :0\r\n whenever an existing member is updated.

Original stage hf1

3. Retrieve member rank

In this stage, you’ll add support for retrieving the rank of a sorted set member using the ZRANK command.

The ZRANK Command

The ZRANK command is used to query the rank of a member in a sorted set. It returns an integer, which is 0-based index of the member when the sorted set is ordered by increasing score. If two members have same score, the members are ordered lexicographically.

Example usage:

> ZADD zset_key 1.0 member_with_score_1
(integer) 1
> ZADD zset_key 2.0 member_with_score_2
(integer) 1
> ZADD zset_key 2.0 another_member_with_score_2
(integer) 1


> ZRANK zset_key member_with_score_1
(integer) 0
> ZRANK zset_key member_with_score_2
(integer) 2
> ZRANK zset_key another_member_with_score_2
(integer) 1

The rank of another_member_with_score_2 is 1, and member_with_score_2 is 2. It is because though the both members have same scores, another_member_with_score_2 preceeds member_with_score_2 lexicographically.

If the member, or the sorted set does not exist, the command returns null bulk string ($-1\r\n).

# Missing sorted set and member
> ZRANK zset_key missing_member
(nil)
> ZRANK missing_key member
(nil)
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a ZADD command to create and add new members to it.

$ redis-cli
> ZADD zset_key 100.0 foo (Expecting ":1\r\n")
> ZADD zset_key 100.0 bar (Expecting ":1\r\n")
> ZADD zset_key 20.0 baz (Expecting ":1\r\n")
> ZADD zset_key 30.1 caz (Expecting ":1\r\n")
> ZADD zset_key 40.2 paz (Expecting ":1\r\n")

# Expected Ranks
# baz -> 0
# caz -> 1
# paz -> 2
# bar -> 3
# foo -> 4

The tester will then send multiple ZRANK commands specifying the members of the sorted set.

> ZRANK zset_key caz (Expecting ":1\r\n")
> ZRANK zset_key baz (Expecting ":0\r\n")
> ZRANK zset_key foo (Expecting ":4\r\n")
> ZRANK zset_key bar (Expecting ":3\r\n")

The tester will also send ZRANK commands where either the member or key doesn’t exist.

> ZRANK zset_key missing_member (Expecting RESP bulk string "$-1\r\n")
> ZRANK missing_key member (Expecting RESP bulk string "$-1\r\n")

Original stage lg6

4. List sorted set members

In this stage, you’ll add support for listing the members of a sorted set using the ZRANGE command.

The ZRANGE command

The ZRANGE command is used to list the members in a sorted set given a start index and an end index. The index of the first element is 0. The end index is inclusive, which means that the element at the end index will be included in the response.

Example usage:

> ZADD racer_scores 8.1 "Sam-Bodden"
(integer) 1
> ZADD racer_scores 10.2 "Royce"
(integer) 1
> ZADD racer_scores 6.0 "Ford"
(integer) 1
> ZADD racer_scores 14.1 "Prickett"
(integer) 1

# List members from index 0 to 2
> ZRANGE racer_scores 0 2
1) "Ford"
2) "Sam-Bodden"
3) "Royce"

Here are some additional notes on how the ZRANGE command behaves with different types of inputs:

  • If the sorted set does not exist, an empty array (*0\r\n) is returned
  • If the start index is greater than or equal to the cardinality of the sorted set, an empty array is returned.
  • If the stop index is greater than the cardinality of the sorted set, the stop index is treated as the last element.
  • If the start index is greater than the stop index, the result is an empty array.
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then create a new sorted set with multiple members.

$ redis-cli
> ZADD zset_key 100.0 foo (Expecting ":1\r\n")
> ZADD zset_key 100.0 bar (Expecting ":1\r\n")
> ZADD zset_key 20.0 baz (Expecting ":1\r\n")
> ZADD zset_key 30.1 caz (Expecting ":1\r\n")
> ZADD zset_key 40.2 paz (Expecting ":1\r\n")

After that the tester will send your program a series of ZRANGE commands. It will expect the response to be a RESP array, or an empty array in each case, depending on the test case.

As an example, the tester might send your program a command like this.

> ZRANGE zset_key 2 4
# Expect RESP Encoded Array: ["paz", "bar", "foo"]

It will expect the response to be an RESP-encoded array ["paz", "bar", "foo"], which would look like this:

*3\r\n
$3\r\n
paz\r\n
$3\r\n
bar\r\n
$3\r\n
foo\r\n

The tester will issue multiple such commands and verify their responses.

Notes
  • In this stage, you will only implement ZRANGE with non-negative indexes. We will get to handling ZRANGE with negative indexes in later stages.

Original stage ic1

5. ZRANGE with negative indexes

In this stage, you’ll add support for negative indexes for the ZRANGE command.

ZRANGE with negative indexes

The ZRANGE command can accept negative indexes too.

Example usage:

> ZADD racer_scores 8.5 "Sam-Bodden"
(integer) 1
> ZADD racer_scores 10.2 "Royce"
(integer) 1
> ZADD racer_scores 6.1 "Ford"
(integer) 1
> ZADD racer_scores 14.9 "Prickett"
(integer) 1
> ZADD racer_scores 10.2 "Ben"
(integer) 1


# List last 2 elements
> ZRANGE racer_scores -2 -1
1) "Royce"
2) "Prickett"

# List all items except last 2
> ZRANGE racer_scores 0 -3
1) "Ford"
2) "Sam-Bodden"
3) "Ben"

An index of -1 refers to the last element, -2 to the second last, and so on. If a absolute value of the negative index is out of range (i.e. >= the cardinality of the sorted set), it is treated as 0 (start of the sorted set).

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a ZADD command to create a sorted set and add members to it.

$ redis-cli
> ZADD zset_key 20.0 foo (Expecting ":1\r\n")
> ZADD zset_key 30.1 bar (Expecting ":1\r\n")
> ZADD zset_key 40.2 baz (Expecting ":1\r\n")
> ZADD zset_key 25.0 paz (Expecting ":1\r\n")
> ZADD zset_key 25.0 caz (Expecting ":1\r\n")

The tester will then send your program a series of ZRANGE commands with one or more negative indexes.

For example, the tester might send you this command:

> ZRANGE zset_key 2 -1
1) "paz"
2) "bar"
3) "baz"

In this case, the tester will verify that the response is the array ["paz", "bar", "baz"], which is RESP Encoded as:

*3\r\n
$3\r\n
paz\r\n
$3\r\n
bar\r\n
$3\r\n
baz\r\n

Original stage bj4

6. Count sorted set members

In this stage, you’ll add support for counting the number of members in a sorted set using the ZCARD command.

The ZCARD Command

The ZCARD command is used to query the cardinality (number of elements) of a sorted set. It returns an integer. The response is 0 if the sorted set specified does not exist.

> ZADD zset_key 1.2 "one"
(integer) 1
> ZADD zset_key 2.2 "two"
(integer) 1
> ZCARD zset_key
(integer) 2

> ZCARD missing_key
(integer) 0
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a ZADD command to create and add members to it.

$ redis-cli
> ZADD zset_key 20.0 zset_member1 (Expecting ":1\r\n")
> ZADD zset_key 30.1 zset_member2 (Expecting ":1\r\n")
> ZADD zset_key 40.2 zset_member3 (Expecting ":1\r\n")
> ZADD zset_key 50.3 zset_member4 (Expecting ":1\r\n")

It will check the number of elements in the sorted set using the ZCARD command.

$ redis-cli ZCARD zset_key (Expecting ":4\r\n")

The tester will then update the score of an existing member.

$ redis-cli ZADD zset_key 100.0 zset_member1 (Expecting ":0\r\n")

It will again check the cardinality of the sorted set using the ZCARD command.

$ redis-cli ZCARD zset_key (Expecting ":4\r\n")

The tester will also check the cardinality of a non existing sorted set.

$ redis-cli ZCARD missing_key (Expecting ":0\r\n")

Original stage kn4

7. Retrieve member score

In this stage, you’ll add support for retrieving the score of a sorted set member using the ZSCORE command.

The ZSCORE Command

The ZSCORE command is used to query the score of a member of a sorted set. If the sorted set and the member both exist, the score of the member is returned as a RESP bulk string.

> ZADD zset_key 24.34 "one"
(integer) 1
> ZADD zset_key 90.34 "two"
(integer) 1
> ZSCORE zset_key "one"
"24.34"

If the member or the sorted set specified in the argument does not exist, RESP null bulk string($-1\r\n) is returned.

> ZSCORE zset_key "three"
(nil)
> ZSCORE missing_key "member"
(nil)
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a ZADD command to create a sorted set and add new members to it.

$ redis-cli
> ZADD zset_key 20.0 zset_member1 (Expecting ":1\r\n")
> ZADD zset_key 30.1 zset_member2 (Expecting ":1\r\n")
> ZADD zset_key 40.2 zset_member3 (Expecting ":1\r\n")
> ZADD zset_key 50.3 zset_member4 (Expecting ":1\r\n")

The tester will then send a ZSCORE command specifying one of the members. For example, the tester may send your program a command like this:

> ZSCORE zset_key zset_member2 (Expecting RESP bulk string "30.1")

It will expect the response to be “30.1”, which is the score of zset_member2. The response is encoded as a RESP bulk string:

$4\r\n
30.1\r\n

The tester will then update the value of the member.

> ZADD zset_key 100.99 zset_member2 (Expecting ":0\r\n")

The tester will then send a ZSCORE command specifying the updated member.

> ZSCORE zset_key zset_member2 (Expecting RESP bulk string "100.99")

The tester will also send ZSCORE commands where either the member or the key doesn’t exist.

> ZSCORE zset_key zset_member100 (Expecting RESP bulk string "$-1\r\n")
> ZSCORE missing_key member (Expecting RESP bulk string "$-1\r\n")

Original stage gd7

8. Remove a member

In this stage, you’ll add support for removing a member of a sorted set using the ZREM command.

The ZREM command

The ZREM command is used to remove a member from a sorted set given the member’s name.

Example Usage:

> ZADD racer_scores 8.3 "Sam-Bodden"
(integer) 1
> ZADD racer_scores 10.5 "Royce"
(integer) 1

# Remove "Royce" from the sorted set
> ZREM racer_scores "Royce"
(integer) 1

# List the remaining members
> ZRANGE racer_scores 0 -1
1) "Sam-Bodden"

# Remove a non-existing member
> ZREM racer_scores "missing_member"
(integer) 0

It returns the number of members removed from the sorted set. If the specified member does not exist, 0 is returned.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then create a new sorted set with multiple members.

$ redis-cli
> ZADD zset_key 80.5 foo (Expecting ":1\r\n")
> ZADD zset_key 50.3 baz (Expecting ":1\r\n")
> ZADD zset_key 80.5 bar (Expecting ":1\r\n")

After that the tester will send your program a ZREM command specifying the member to be removed.

As an example, the tester might send your program a command like this.

> ZREM zset_key "baz"
# Expected: (integer) 1

It will then send your program a ZRANGE command and check for the remaining members.

> ZRANGE zset_key 0 -1
# Expected RESP Encoded Array: ["bar", "foo"]

The tester will also send a ZREM command where the member doesn’t exist.

> ZREM zset_key "missing_member"
# Expected: (integer) 0

Original stage sq7

Back to contents

Bitmaps

1. Create a bitmap

In this stage, you’ll add support for creating a bitmap using the SETBIT command.

Redis Bitmaps

Bitmaps let you store individual bits (0 or 1). Unlike lists or sorted sets, they are not a separate Redis data type. They are strings that you can access and update at the bit level.

Because each value takes only one bit, bitmaps are extremely space-efficient. This makes them useful for use cases like tracking subscriptions, counting daily active users, or any scenario where you need a yes/no flag for a large population.

For example, if you were using a bitmap to track newsletter subscriptions, the contents might look like this:

newsletter_subscribers: 10001010

Here, user numbers 0, 4, and 6 have subscribed. Redis numbers bits from left to right, starting at offset 0.

The SETBIT Command

The SETBIT command is used to set a bit to 0 or 1 in the string value stored at key.

When key does not exist, a new string is created and the bit is set.

Example usage:

> SETBIT bitmap_key 3 1
(integer) 0

The SETBIT command takes the key, an offset, and a value (0 or 1) as arguments. It returns the original bit at that offset. On a new key, that is always 0.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a SETBIT command specifying a key, offset, and value.

$ redis-cli SETBIT bitmap_key 3 1

The tester will verify that the response to the command is :0\r\n, which is 0 (the original bit at that offset), encoded as a RESP integer.

Notes
  • As bitmaps are strings, we suggest that you store them using the same data structure you already use for SET and GET. It’ll come in handy in later stages.
  • Redis treats offset 0 as the most significant bit of the first byte. For example, SETBIT key 1 1 stores the byte 01000000. This will matter when you implement GETBIT and BITCOUNT in later stages.

Original stage bq9

2. Retrieve a bit

In this stage, you’ll add support for retrieving a bit from a bitmap using the GETBIT command.

The GETBIT Command

The GETBIT command returns the bit stored at a given offset in a bitmap.

If the key does not exist, Redis treats the bitmap as all zeros and returns 0 for any offset.

Example usage:

> SETBIT bit_key 2 1
(integer) 0

> GETBIT bit_key 2
(integer) 1
> GETBIT bit_key 3
(integer) 0
> GETBIT new_key 2
(integer) 0
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a SETBIT command to create a bitmap.

$ redis-cli SETBIT bit_key 2 1

The tester will then send a GETBIT command for a bit that was set.

$ redis-cli GETBIT bit_key 2

The tester will expect the response to be :1\r\n, which is 1 encoded as a RESP integer.

It will also send a GETBIT command for an unset offset on the same key.

$ redis-cli GETBIT bit_key 3

The tester will expect the response to be :0\r\n.

The tester will also send a GETBIT command for a key that does not exist.

$ redis-cli GETBIT new_key 2

In this case, your program should also respond with :0\r\n.

Notes
  • Using GETBIT with an offset beyond the current string length should return 0.

Original stage qj1

3. Read a string as bits

In this stage, you’ll add support for using GETBIT on a key created with SET.

Strings and bitmaps

As bitmaps are strings, bitmap commands work on any string value, including keys created with SET.

These two views operate on the same bytes. SET writes the string. GETBIT reads one bit of it.

For example, the ASCII character A is the byte 01000001. Offset 0 is the most significant bit of that byte:

> SET mykey "A"
OK
> GETBIT mykey 1
(integer) 1
> GETBIT mykey 7
(integer) 1
> GETBIT mykey 0
(integer) 0

Here, bits 1 and 7 are set and bit 0 is not.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a SET command to store a one-byte string. For example:

$ redis-cli SET mykey "A"

The tester will then send GETBIT commands for offsets in that string.

$ redis-cli GETBIT mykey 1

The tester will expect the response to be :1\r\n, which is 1 encoded as a RESP integer.

$ redis-cli GETBIT mykey 7

The tester will expect the response to be :1\r\n.

$ redis-cli GETBIT mykey 0

The tester will expect the response to be :0\r\n.

Notes
  • In this stage, you’ll only need to handle GETBIT on a key created with SET. Reading a bitmap back with GET is covered in the later stages.
  • Redis applies GETBIT to the string’s bytes. Keys created with SET and SETBIT share that representation. See the official implementation.

Original stage yj2

4. Read bits as a string

In this stage, you’ll add support for using GET on a key created with SETBIT.

Strings and bitmaps

As bitmaps are strings, string commands work on keys created with SETBIT.

These two views operate on the same bytes. SETBIT writes bits into the string. GET returns that string.

Offset 0 is the most significant bit of the first byte. Setting bit 1 produces the byte 01000000, which is the ASCII character @:

> SETBIT mykey 1 1
(integer) 0
> GET mykey
"@"
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a SETBIT command to create a bitmap.

$ redis-cli SETBIT mykey 1 1

The tester will then send a GET command for that key.

$ redis-cli GET mykey

The tester will expect the response to be $1\r\n@\r\n, which is @ encoded as a RESP bulk string.

Notes
  • In this stage, you’ll only need to handle GET on a key created with a single SETBIT. Growing the string with a larger offset is covered in the later stages.
  • GET returns the string value stored at the key. SETBIT writes that value as bytes. Keys created with SETBIT and SET share that representation.

Original stage pk5

5. Grow a bitmap

In this stage, you’ll add support for growing a bitmap with SETBIT, and for checking its length with STRLEN.

Growing a bitmap

When SETBIT uses an offset past the end of the string, Redis grows the string so that the offset fits. The string is padded with zeros, and the target bit is set.

STRLEN returns the length of that string in bytes, not bits. Offsets 0 through 7 fit in one byte. Offset 8 is the first bit of a second byte. After SETBIT grows a key, STRLEN is floor(offset / 8) + 1. For offset 10, that is 2.

> SETBIT bitmap_key 1 1
(integer) 0

After the SETBIT command runs, Redis creates a one-byte string 01000000.

> SETBIT bitmap_key 10 1
(integer) 0

After the second SETBIT command runs, Redis appends a second byte and then sets offset 10 to 1. The final string becomes 01000000 00100000.

> STRLEN bitmap_key
(integer) 2
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a SETBIT command to create a one-byte bitmap.

$ redis-cli SETBIT bitmap_key 1 1

The tester will send a STRLEN command for that key.

$ redis-cli STRLEN bitmap_key

The tester will expect the response to be :1\r\n, which is 1 encoded as a RESP integer.

It will then send a SETBIT command with an offset in a second byte.

$ redis-cli SETBIT bitmap_key 10 1

The tester will expect the response to be :0\r\n.

The tester will then send GETBIT commands for the new bit

$ redis-cli GETBIT bitmap_key 10

The tester will expect the response to be :1\r\n.

$ redis-cli STRLEN bitmap_key

The tester will expect the response to be :2\r\n.

Notes
  • In this stage, you’ll only need to handle creating or growing a key by a small offset (creating the key if it does not exist). You won’t need to handle out-of-range offsets.
  • STRLEN returns the string’s length in bytes. If the key does not exist, STRLEN returns 0.

Original stage yf6

6. Count set bits

In this stage, you’ll add support for counting set bits in a bitmap using the BITCOUNT command.

The BITCOUNT Command

The BITCOUNT command returns the number of bits set to 1 in a bitmap.

With no extra arguments, it counts the whole string. It can also take a start and end index. These indexes are bytes, not bits. Both are inclusive.

Offset 0 through 7 is byte 0. Offset 8 through 15 is byte 1. BITCOUNT key 0 0 counts only the first byte.

> SETBIT bitmap_key 1 1
(integer) 0
> SETBIT bitmap_key 10 1
(integer) 0

After those SETBIT commands, the string is 01000000 00100000. Byte 0 has one set bit. Byte 1 has one set bit.

> BITCOUNT bitmap_key
(integer) 2
> BITCOUNT bitmap_key 0 1
(integer) 2

Calling BITCOUNT with no arguments counts the 1s in every byte. It is the same as calling BITCOUNT with 0 1 in this example.

> BITCOUNT bitmap_key 0 0
(integer) 1
> BITCOUNT bitmap_key 1 1
(integer) 1

Calling BITCOUNT with 0 0 counts the 1s in the first byte. Calling it with 1 1 counts the 1s in the second byte.

Here are some additional notes on how the BITCOUNT command behaves with different types of inputs:

  • If the key does not exist, BITCOUNT returns 0.
  • If start is past the end of the string, BITCOUNT returns 0.
  • If end is past the end of the string, Redis treats it as the last byte.
  • If start is greater than end, BITCOUNT returns 0.
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send SETBIT commands to create a two-byte bitmap.

$ redis-cli SETBIT bitmap_key 1 1
$ redis-cli SETBIT bitmap_key 10 1

After that, the tester will send your program a series of BITCOUNT commands with no extra arguments, or with non-negative indexes. For each command, it will expect the number of set bits, encoded as a RESP integer.

As an example, the tester might send your program a command like this:

$ redis-cli BITCOUNT bitmap_key 0 0

The tester will expect the response to be :1\r\n.

Notes
  • In this stage, you’ll only need to handle BITCOUNT with no range, and with non-negative indexes. We won’t deal with negative indexes in this challenge.
  • BITCOUNT supports the BYTE and BIT optional arguments, but we won’t deal with them in this challenge.

Original stage nx3

7. AND two bitmaps

In this stage, you’ll add support for combining bitmaps with BITOP AND.

The BITOP Command

The BITOP command runs a bitwise operation on one or more bitmaps and stores the result at a destination key.

BITOP AND sets a bit in the destination only when that bit is set in every source bitmap.

In this example, we have two bitmaps: key1 is 10001000 and key2 is 10000010 , created using SETBIT commands.

> BITOP AND dest key1 key2
(integer) 1
> GETBIT dest 0
(integer) 1
> GETBIT dest 4
(integer) 0
> GETBIT dest 6
(integer) 0

After performing a BITOP AND operation on key1 and key2 , we get another bitmap dest with the value 10000000 . Only bit 0 is set in both.

BITOP returns the length of the destination string in bytes, encoded as a RESP integer. Here the destination string is 1 byte, so the return value is 1.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send SETBIT commands to create two bitmaps of the same length.

$ redis-cli SETBIT key1 0 1
$ redis-cli SETBIT key1 4 1
$ redis-cli SETBIT key2 0 1
$ redis-cli SETBIT key2 6 1

The tester will send a BITOP AND command that stores the result at a new key.

$ redis-cli BITOP AND dest key1 key2

The tester will expect the response to be :1\r\n.

It will then send GETBIT commands for the destination key.

$ redis-cli GETBIT dest 0

The tester will expect the response to be :1\r\n.

$ redis-cli GETBIT dest 4

The tester will expect the response to be :0\r\n.

Notes
  • In this stage, you’ll only need to handle BITOP AND with two source keys of the same length. Combining bitmaps of different lengths is covered in later stages.
  • BITOP also supports other operations like OR, XOR, and NOT. The BITOP OR operation is covered in later stages. We won’t deal with XOR and NOT in this challenge.

Original stage hv4

8. AND bitmaps of different lengths

In this stage, you’ll add support for BITOP AND when the source bitmaps have different lengths.

BITOP AND with different lengths

When the source strings have different lengths, Redis treats the shorter ones as if they were padded with zeros up to the length of the longest string. The destination is as long as that longest string.

> SETBIT key1 1 1
(integer) 0
> SETBIT key1 10 1
(integer) 0
> SETBIT key2 1 1
(integer) 0

In this example, we have two bitmaps: key1 is 01000000 00100000 (2 bytes) and key2 is 01000000 (1 byte), created using SETBIT commands.

> BITOP AND dest key1 key2
(integer) 2
> GETBIT dest 1
(integer) 1
> GETBIT dest 10
(integer) 0

During the BITOP AND operation, Redis treats the shorter string as zero-padded. In this example, key2 is treated as 01000000 00000000 (second byte is padded with 0s).

Only bit 1 is set in both keys. So dest will hold the value 01000000 00000000. BITOP returns 2, the length of the destination.

Additional notes:

  • A missing key is treated as a string of zeros of the same length as the longest source.
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send SETBIT commands to create two bitmaps of different lengths.

$ redis-cli SETBIT key1 1 1
$ redis-cli SETBIT key1 10 1
$ redis-cli SETBIT key2 1 1

The tester will send a BITOP AND command that stores the result at a new key.

$ redis-cli BITOP AND dest key1 key2

The tester will expect the response to be :2\r\n, which is 2 encoded as a RESP integer.

It will then send GETBIT commands for the destination key.

$ redis-cli GETBIT dest 1

The tester will expect the response to be :1\r\n.

$ redis-cli GETBIT dest 10

The tester will expect the response to be :0\r\n.

Notes
  • BITOP also supports other operations like OR, XOR, and NOT. The BITOP OR operation is covered in later stages. We won’t deal with XOR and NOT in this challenge.

Original stage dk2

9. OR two bitmaps

In this stage, you’ll add support for combining bitmaps with BITOP OR.

The BITOP OR Command

BITOP OR sets a bit in the destination when that bit is set in at least one source bitmap.

In this example, we have two bitmaps: key1 is 10001000 and key2 is 10000010, created using SETBIT commands.

> BITOP OR dest key1 key2
(integer) 1
> GETBIT dest 0
(integer) 1
> GETBIT dest 4
(integer) 1
> GETBIT dest 6
(integer) 1

After performing a BITOP OR operation on key1 and key2, we get another bitmap dest with the value 10001010 because bits 0, 4, and 6 are set in at least one source.

BITOP returns the length of the destination string in bytes. Here that is 1.

When the source strings have different lengths, Redis treats the shorter ones as if they were padded with zeros up to the length of the longest string.

In this example, we have two bitmaps: key1 is 01000000 00100000 (2 bytes) and key2 is 01000000 (1 byte).

> BITOP OR dest key1 key2
(integer) 2
> GETBIT dest 1
(integer) 1
> GETBIT dest 10
(integer) 1

key2 is treated as 01000000 00000000. Bit 10 is set in key1 and padded to 0 in key2, so it is set in the destination. dest holds 01000000 00100000. BITOP returns 2, the length of the destination.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send SETBIT commands to create two bitmaps of the same length.

$ redis-cli SETBIT key1 0 1
$ redis-cli SETBIT key1 4 1
$ redis-cli SETBIT key2 0 1
$ redis-cli SETBIT key2 6 1

The tester will send a BITOP OR command that stores the result at a new key.

$ redis-cli BITOP OR dest key1 key2

The tester will expect the response to be :1\r\n.

It will then send a GETBIT command for a bit that is set in only one source.

$ redis-cli GETBIT dest 4

The tester will expect the response to be :1\r\n.

The tester will then send SETBIT commands to create two bitmaps of different lengths.

$ redis-cli SETBIT key3 1 1
$ redis-cli SETBIT key3 10 1
$ redis-cli SETBIT key4 1 1

The tester will send a BITOP OR command that stores the result at a new key.

$ redis-cli BITOP OR dest2 key3 key4

The tester will expect the response to be :2\r\n, which is 2 encoded as a RESP integer.

It will then send a GETBIT command for a bit that is past the end of the shorter source.

$ redis-cli GETBIT dest2 10

The tester will expect the response to be :1\r\n.

Notes
  • BITOP also supports other operations like XOR and NOT, but we won’t deal with them in this challenge.

Original stage fr8

Back to contents

Geospatial Commands

1. Respond to GEOADD

In this stage, you’ll add support for responding to the GEOADD command.

Extension prerequisites

This stage depends on the Sorted Sets extension. Before attempting this extension, please make sure you’ve completed the Sorted Sets extension.

The GEOADD command

The GEOADD command adds a location (with longitude, latitude, and name) to a key.

Example usage:

> GEOADD places -0.0884948 51.506479 "London"
(integer) 1

The arguments GEOADD accepts are:

  1. key: The key to store the location in.
  2. longitude: The longitude of the location.
  3. latitude: The latitude of the location.
  4. member: The name of the location.

It returns the count of elements added, encoded as a RESP Integer.

In this stage, you’ll only implement the response to the GEOADD command. We’ll get to validating arguments and storing locations in later stages.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a GEOADD command:

$ redis-cli GEOADD places 11.5030378 48.164271 Munich

The tester will expect the response to be :1\r\n, which is 1 (number of locations added) encoded as a RESP integer.

Notes
  • In this stage, you only need to implement responding to the GEOADD command. We’ll get to validating arguments and storing locations in later stages.

Original stage zt4

2. Validate coordinates

In this stage, you’ll add support for validating the latitude and longitude values provided in a GEOADD command.

Validating latitude and longitude values

The latitude and longitude values used in the GEOADD command should be in a certain range as per EPSG:3857.

  • Valid longitudes are from -180° to +180°
    • Both these limits are inclusive, so -180° and +180° are both valid.
  • Valid latitudes are from -85.05112878° to +85.05112878°
    • Both of these limits are inclusive, so -85.05112878° and +85.05112878° are both valid.
    • The reason these limits are not -/+90° is because of the Web Mercator projection that Redis uses.

If either of these values aren’t within the appropriate range, GEOADD returns an error. Examples:

# Invalid latitude
> GEOADD places 180 90 test1
(error) ERR invalid longitude,latitude pair 180.000000,90.000000

# Invalid longitude
> GEOADD places 181 0.3 test2
(error) ERR invalid longitude,latitude pair 181.000000,0.300000

In this stage, you’ll implement validating latitude and longitude values and returning error messages as shown above. The tester is lenient with error message formats, so you don’t have to use the exact error message format mentioned above.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send multiple GEOADD commands.

If the coordinates are invalid, it will expect an error response. For example:

# Expecting error
$ redis-cli GEOADD location_key 200 100 foo
(error) ERR invalid longitude,latitude pair 200,100

The returned value must:

  • Be a RESP simple error i.e. start with - and end with \r\n
  • The error message must start with ERR, like standard Redis error messages
  • The error message must contain the word “latitude” if the latitude is invalid
  • The error message must contain the word “longitude” if the longitude is invalid

For example, if the latitude is invalid, valid error messages that the tester will accept are:

-ERR invalid latitude argument\r\n
-ERR invalid latitude value\r\n
-ERR latitude value (200.0) is invalid\r\n
Notes
  • You don’t need to implement storing locations yet, we’ll get to that in later stages.
  • The boundary of latitude are clipped at -/+85.05112878° instead of -/+90°. This is because of the Web Mercator projection that Redis uses.

Original stage ck3

3. Store a location

In this stage, you’ll add support for storing locations in a sorted set.

Storing locations in sorted set

The locations added using the GEOADD command are stored in a sorted set. Redis internally calculates a score for the specified location using a location’s latitude and longitude.

For example, the following two commands are equivalent in Redis.

# Adding a location
$ redis-cli GEOADD places_key 2.2944692 48.8584625 location

# This command is equivalent to the command above
$ redis-cli ZADD places_key 3663832614298053 location

In this stage, you’ll implement adding locations to a sorted set when a GEOADD command is run.

You can hardcode the score to be 0 for now, we’ll get to calculating the score in later stages.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send a GEOADD command:

$ redis-cli GEOADD places 2.2944692 48.8584625 Paris
# Expect: (integer) 1

The tester will then send a ZRANGE command to validate that the location was added to the sorted set:

$ redis-cli ZRANGE places 0 -1
# Expect RESP Array: ["Paris"]
Notes
  • In this stage, you can hardcode the score of the location to be 0. We’ll get to calculating the value of score using latitude and longitude in later stages.
  • The implementation of the ZRANGE command is covered in the sorted sets extension.

Original stage tn5

4. Calculate location score

In this stage, you’ll add support for calculating the score of a location.

Location scores

To store locations in a sorted set, Redis converts latitude and longitude values to a single “score”.

We’ve created a GitHub repository that explains how this conversion is done. It includes:

  • A description of the algorithm used, along with pseudocode
  • Code samples in multiple languages.
  • A set of locations & scores to test against

Here’s the repository link.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send multiple GEOADD commands:

$ redis-cli GEOADD places 2.2944692 48.8584625 Paris
# Expect: (integer) 1
$ redis-cli GEOADD places -0.127758 51.507351 London
# Expect: (integer) 1

The tester will validate that scores are calculated correctly by sending multiple ZSCORE commands:

$ redis-cli ZSCORE places Paris
# Expecting bulk string: "3663832614298053"

The calculated scores must match the expected values as described in this repository.

Original stage cr3

5. Respond to GEOPOS

In this stage, you’ll add support for responding to the GEOPOS command.

The GEOPOS command

The GEOPOS command returns the longitude and latitude of the specified location.

Example usage:

> GEOADD places -0.0884948 51.506479 "London"
> GEOADD places 11.5030378 48.164271 "Munich"

> GEOPOS places London
1) 1) "-0.08849412202835083"
   2) "51.50647814139934"

> GEOPOS places Munich
1) 1) "11.503036916255951"
   2) "48.16427086232978"

It returns an array with one entry for each location requested.

  • If a location exists under the key, its entry is an array of two items:
  • If either the location or key don’t exist, the corresponding entry is a null array (*-1\r\n).

To return the latitude and longitude values, Redis decodes the “score” back to latitude and longitude values. We’ll cover this process in later stages, for now you can hardcode the returned latitude and longitude values to be 0 (or any number).

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then add multiple locations using the GEOADD command.

$ redis-cli
> GEOADD location_key -0.0884948 51.506479 "London"
# Expect: (integer) 1
> GEOADD location_key 11.5030378 48.164271 "Munich"
# Expect: (integer) 1

The tester will then send multiple GEOPOS commands:

> GEOPOS location_key London Munich
# Expecting: [["0", "0"], ["0", "0"]], encoded as "*2\r\n*2\r\n$1\r\n0\r\n$1\r\n0\r\n*2\r\n$1\r\n0\r\n$1\r\n0\r\n"

> GEOPOS location_key missing_location
# Expecting: [nil], encoded as "*1\r\n*-1\r\n"

The tester will assert that:

  • The response is a RESP array that contains as many elements as the number of locations requested
  • For each location requested:
    • If the location exists:
      • The corresponding element is a RESP array with two elements (i.e. longitude and latitude)
      • Both elements are “0” (or any other valid floating point number), encoded as a RESP bulk string
    • If the location doesn’t exist:
      • The corresponding element is a null array (*-1\r\n).

The tester will also send a GEOPOS command using a key that doesn’t exist:

> GEOPOS missing_key London Munich
# Expecting [nil, nil], encoded as "*2\r\n*-1\r\n*-1\r\n"

The tester will assert that:

  • The response is a RESP array that contains as many elements as the number of locations requested
  • Each element of the array is a null array (*-1\r\n)
Notes
  • In this stage, you can hardcode the returned latitude and longitude values to be 0 (or any other valid floating point number). We’ll get to testing actual latitude and longitude values in later stages.

Original stage xg4

6. Decode coordinates

In this stage, you’ll add support for decoding the coordinates of a location.

Decoding latitude and longitude from score

The algorithm to get back the latitude and longitude is essentially the reverse of the one used to compute the score from them.

The GitHub repository we referenced earlier explains how this conversion is done. It includes:

  • A description of the algorithm used, along with pseudocode
  • Code samples in multiple languages.
  • A set of locations & scores to test against

Here’s the repository link.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will add multiple locations using the ZADD command. The scores used are valid scores that can be converted back to latitude and longitude values.

$ redis-cli
> ZADD location_key 3663832614298053 "Foo"
> ZADD location_key 3876464048901851 "Bar"
> ZADD location_key 3468915414364476 "Baz"
> ZADD location_key 3781709020344510 "Caz"

The tester will then send multiple GEOPOS commands:

> GEOPOS location_key Foo
# Expecting [["2.294471561908722", "48.85846255040141"]]

The tester will validate that the response is a RESP array, which is encoded as:

*1\r\n
*2\r\n
$17\r\n
2.294471561908722\r\n
$17\r\n
48.85846255040141\r\n
Notes
  • The conversion from latitude/longitude to score and back is lossy, so the tester will be lenient in checking the coordinates provided – it will accept any coordinates that are within 6 decimal places of the original values. For example, for the example shown above, any of the following values will be accepted:
    • ["2.2944715", "48.8584625"]
    • ["2.294472", "48.858463"]
    • ["2.294471594", "48.858462987"]

Original stage hb5

7. Calculate distance

In this stage, you’ll add support for calculating the distance between two locations using the GEODIST command.

The GEODIST command

The GEODIST command returns the distance between two members of a key.

Example usage:

> GEODIST places Munich Paris
"682477.7582"

The distance is returned in meters, encoded as a RESP bulk string.

Redis uses the Haversine’s Formula to calculate the distance between two points. You can see how this is done in the Redis source code here.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then add multiple locations using the GEOADD command:

$ redis-cli
> GEOADD places 11.5030378 48.164271 "Munich"
> GEOADD places 2.2944692 48.8584625 "Paris"

The tester will then send multiple GEODIST commands specifying two locations:

> GEODIST places Munich Paris
# Expecting "682477.7582"

The tester will validate that the response is a RESP bulk string that contains the distance between the two locations, for example:

$11\r\n682477.7582\r\n
Notes
  • When computing distance, set the value of Earth’s radius to 6372797.560856 meters. This is the exact value used by Redis.

  • The distance should match the actual distance between the provided locations with a precision of up to 4 decimal places after rounding. For example, if the expected distance is 12345.6789, any of the following returned values will be accepted:

    • 12345.67891
    • 12345.6789
    • 12345.67889

Original stage ek6

8. Search within radius

In this stage, you’ll add support for searching locations within a given radius using the GEOSEARCH command.

The GEOSEARCH command

The GEOSEARCH command lets you search for locations within a given radius.

It supports several search modes. In our implementation, we’ll focus only on the FROMLONLAT mode. The FROMLONLAT mode searches by directly specifying longitude and latitude.

Example usage:

> GEOSEARCH places FROMLONLAT 2 48 BYRADIUS 100 m
1) "Paris"

The example command above searches for locations in the places key that are within 100 meters of the point (longitude: 2, latitude: 48).

The response is a RESP array containing the names of the locations that match the search criteria, each encoded as a RESP bulk string.

Note that there are two options we passed to the command:

  • FROMLONLAT <longitude> <latitude> — This option specifies the center point for the search.
  • BYRADIUS <radius> <unit> — This option searches within a circular area of the given radius and unit (m, km, mi, etc.).

Redis supports other such options, but in this challenge we’ll only use FROMLONLAT and BYRADIUS.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will add multiple locations using the GEOADD command.

$ redis-cli
> GEOADD places 11.5030378 48.164271 "Munich"
> GEOADD places 2.2944692 48.8584625 "Paris"
> GEOADD places -0.0884948 51.506479 "London"

The tester will then send multiple GEOSEARCH commands:

> GEOSEARCH places FROMLONLAT 2 48 BYRADIUS 100000 m
# Expecting ["Paris"]

> GEOSEARCH places FROMLONLAT 2 48 BYRADIUS 500000 m
# Expecting ["Paris, "London"] (Any order)

> GEOSEARCH places FROMLONLAT 11 50 BYRADIUS 300000 m
# Expecting ["Munich"]

The tester will validate that the response is a RESP array, for example

*2\r\n
$5\r\n
Paris\r\n
$6\r\n
London\r\n

Locations can be returned in any order.

Notes
  • The tester will always use the FROMLONLAT and BYRADIUS options when sending a GEOSEARCH command.

Original stage rm9

Back to contents

Authentication

1. Respond to ACL WHOAMI

In this stage, you’ll add support for responding to the ACL WHOAMI command.

The ACL WHOAMI Command

The ACL WHOAMI command returns the username associated with the current connection.

By default, every new connection in Redis is automatically authenticated as the default user.

For example:

> ACL WHOAMI
"default"

The command returns the username of the currently authenticated user, encoded as a RESP bulk string.

This default authentication behavior can be changed so that new connections start out unauthenticated. We’ll cover that in later stages.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send an ACL WHOAMI command:

# Expect RESP bulk string: "default"
$ redis-cli ACL WHOAMI
"default"

The tester will expect to receive $7\r\ndefault\r\n as a response. That’s the string default encoded as a bulk string.

Notes
  • In this stage, you can hardcode the response of the ACL WHOAMI command to be default. We’ll get to enforcing authentication in the later stages.

Original stage jn4

2. Respond to ACL GETUSER

In this stage, you’ll add support for the ACL GETUSER command.

The ACL GETUSER Command

The ACL GETUSER command retrieves the properties of a specified user. In Redis, the default user is present from the start and does not need to be created.

For example:

> ACL GETUSER default
1) "flags"
2) (empty array)
...

The return value is a nested RESP array of property name-value pairs for the user:

[property_name_1, property_value_1, property_name_2, property_value_2, ...]

For this stage, you’ll implement just the flags property.

The flags Property

The flags property represents a set of attributes that describe how a user behaves or what special permissions they have. Each flag is a short label that defines part of the user’s configuration.

For example, after creating or modifying a user, the flags array might look like this:

> ACL GETUSER alice
1) "flags"
2) 1) "on"
   2) "allkeys"
   3) "allcommands"

For this stage, since the default user has no flags to report yet, you will hardcode the value to be an empty RESP array ([]).

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send an ACL GETUSER command specifying the default user:

# Expect RESP array: ["flags", []]
$ redis-cli
> ACL GETUSER default
1) "flags"
2) (empty array)

The tester will verify that the response is a RESP array with two elements:

  1. The first element is the bulk string flags.
  2. The second element is an empty RESP array.

Original stage gx8

3. The nopass flag

In this stage, you’ll add support for responding to the ACL GETUSER command with the nopass flag set.

The nopass flag

The nopass flag is one of the user flags in Redis. It controls the password authentication behaviour:

  • If nopass is set for a user, authentication succeeds with any password (or no password)
  • Setting nopass clears any passwords associated with the user

The default user has nopass set by default, which is why new connections are automatically authenticated.

For example:

> ACL GETUSER default
1) "flags"
2) 1) "nopass"
...

The flags are encoded as a RESP array of bulk strings.

For this stage, you only need to respond to the ACL GETUSER command with the nopass flag set. We’ll get to enforcing the behavior of the nopass flag in later stages.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send an ACL GETUSER command specifying the default user.

# Expect RESP array: ["flags", ["nopass"]]
$ redis-cli
> ACL GETUSER default
1) "flags"
2) 1) "nopass"

The tester will verify that the response is a RESP array with two elements:

  1. The first element is the bulk string flags.
  2. The second element is a RESP array containing one element: the bulk string nopass.

Original stage ql6

4. The passwords property

In this stage, you’ll add support for responding to the ACL GETUSER command with the passwords property.

The passwords Property

The passwords property lists all hash-encoded passwords associated with a user.

The default user does not have any associated passwords unless explicitly configured:

> ACL GETUSER default
 1) "flags"
 2) 1) "nopass"
 3) "passwords"
 4) (empty array)

Your ACL GETUSER response must now include the following:

  1. The string passwords, encoded as a bulk string.
  2. A RESP array containing the list of passwords. Since the default user has none, you must hardcode this to be an empty array.
Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send an ACL GETUSER command specifying the default user:

# Expect RESP array: ["flags", ["nopass"], "passwords", []]
$ redis-cli ACL GETUSER default
 1) "flags"
 2) 1) "nopass"
 3) "passwords"
 4) (empty array)

The tester will validate that the response is a RESP array with four elements:

  1. The first element of the array is the string flags, encoded as a RESP bulk string.
  2. The second element of the array is a RESP array and contains the nopass flag.
  3. The third element of the array is the string passwords, encoded as a bulk string.
  4. The fourth element of the array is an empty array.

Original stage pl7

5. Setting default user password

In this stage, you’ll add support for setting the default user’s password.

The ACL SETUSER Command

The ACL SETUSER command modifies the properties of an existing user.

When the command is used with the > rule, it adds a password for the specified user:

> ACL SETUSER default >mypassword
OK

The server responds with OK encoded as a RESP simple string (+OK\r\n).

Password Storage

Adding a password for a user with ACL SETUSER has two effects:

  • The password is stored as a SHA-256 hash.
  • The nopass flag is automatically removed.

For example:

> ACL SETUSER default >mypassword
OK

> ACL GETUSER default
 1) "flags"
 2) (empty array)
 3) "passwords"
 4) 1) "89e01536ac207279409d4de1e5253e01f4a1769e696db0d6062ca9b8f56767c8"

Notice that the nopass flag is now gone from the flags array. Also, the mypassword SHA-256 hash is stored as a bulk string in the passwords array.

Storing only the SHA-256 hash is a security best practice Redis uses to prevent password leaks if the database is compromised.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send an ACL GETUSER command, specifying the default user:

# Expect RESP array: ["flags", ["nopass"], "passwords", []]
$ redis-cli ACL GETUSER default
1) "flags"
2) 1) "nopass"
3) "passwords"
4) (empty array)

The tester will verify that:

  • The nopass flag is present in the flags array.
  • The passwords array is empty.

Next, the tester will send a ACL SETUSER command, specifying the default user and a password:

# Expect: +OK\r\n
> ACL SETUSER default >mypassword
OK

Your server must respond with +OK\r\n.

Finally, the tester will send a ACL GETUSER command, specifying the default user:

# Expect RESP array: ["flags", ["nopass"], "passwords", ["89e01536ac207279409d4de1e5253e01f4a1769e696db0d6062ca9b8f56767c8"]]
> ACL GETUSER default
1) "flags"
2) 1) "nopass"
3) "passwords"
4) 1) "89e01536ac207279409d4de1e5253e01f4a1769e696db0d6062ca9b8f56767c8"

The tester will validate the following for your response:

  • The nopass flag is no longer present.
  • The passwords array contains the SHA-256 hash of mypassword encoded as a bulk string.
Notes
  • Redis uses the SHA-256 hashing algorithm for password storage. You’ll need to compute the SHA-256 hash of the provided password and store it.
  • The password hash should be stored as a lowercase hexadecimal string.

Original stage uv9

6. The AUTH command

In this stage, you’ll add support for the AUTH command.

The AUTH Command

The AUTH command authenticates the current connection with a specified username and password.

The command format is:

AUTH <username> <password>

For example:

# Authentication failure
> AUTH default wrongpassword
(error) WRONGPASS invalid username-password pair or user is disabled.

# Authentication success
> AUTH default correctpassword
OK

The server responds with +OK\r\n if the specified password’s hash matches any of the hashes in the user’s password list.

If no match is found, the server responds with the RESP simple error: WRONGPASS invalid username-password pair or user is disabled.

For this stage, you just need to respond to the AUTH command appropriately. You don’t need to actually authenticate the connection. We’ll get to that in later stages.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send an ACL SETUSER command, specifying the default user and a password:

$ redis-cli ACL SETUSER default >mypassword
OK

Your server should respond with OK encoded as a simple string (+OK\r\n).

Next, the tester will send two AUTH commands: one with a wrong password and another with a correct password.

# Expect error starting with: WRONGPASS
> AUTH default wrongpassword
(error) WRONGPASS invalid username-password pair or user is disabled.

# Expect: +OK\r\n
> AUTH default mypassword
OK

The tester will verify that:

  • Wrong passwords return a simple error starting with WRONGPASS.
  • Correct passwords return +OK\r\n.
Notes
  • The tester will be lenient in checking error messages. Any authentication failure starting with WRONGPASS is valid. For example:
    • WRONGPASS wrong password
    • WRONGPASS invalid authentication

Original stage hz3

7. Enforce authentication

In this stage, you’ll add support for enforcing authentication for the default user.

Enforcing default User Authentication

When you create a new connection, it is automatically authenticated as the default user. This happens because the nopass flag is set for the default user from the start.

Once you set a password for the default user, new connections will no longer be automatically authenticated. However, any connections that were already authenticated will stay logged in.

For example:

# Client 1
$ redis-cli ACL SETUSER default >password
OK

# This connection remains authenticated as the default user
> ACL WHOAMI
"default"

# Client 2
# This connection is not authenticated
$ redis-cli ACL WHOAMI
(error) NOAUTH Authentication required.

When an unauthenticated connection tries to execute a command, return the simple error: NOAUTH Authentication required.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send commands to two different clients:

# Client 1
$ redis-cli
# Expect: +OK\r\n
> ACL SETUSER default >newpassword
OK

# Expect RESP bulk string: "default"
> ACL WHOAMI
"default"

# Client 2 (new connection)
$ redis-cli
# Expect error starting with: "NOAUTH"
> ACL WHOAMI
(error) NOAUTH Authentication required.

The tester will verify that:

  • Client 1 can still execute commands and remains authenticated as the default user.
  • Client 2 receives a NOAUTH error when trying to execute commands without authentication.

Original stage nm2

8. Authenticate using AUTH

In this stage, you’ll implement enforcing authentication using the AUTH command.

Enforcing Authentication Using AUTH

After the AUTH command succeeds, the connection becomes authenticated as the specified user. Once authenticated, the connection can execute commands that previously returned NOAUTH errors:

For example:

# Client 1
$ redis-cli
> ACL SETUSER default >newpassword
OK

> ACL WHOAMI
"default"

# Client 2 (new connection)
$ redis-cli
> ACL WHOAMI
(error) NOAUTH Authentication required.

> AUTH default newpassword
OK

# Client 2 is now authenticated as the 'default' user
> ACL WHOAMI
"default"

The authentication lasts for the entire connection, so the client does not need to re-authenticate for every command.

Tests

The tester will execute your program like this:

$ ./your_program.sh

It will then send commands to two different clients:

# Client 1
$ redis-cli
> ACL SETUSER default >newpassword
OK

> ACL WHOAMI
"default"  # Still authenticated

# Client 2 (new connection)
$ redis-cli
> PING
(error) NOAUTH Authentication required.

> AUTH default newpassword
OK

> PING
PONG

The tester will verify that:

  1. A new client receives a NOAUTH error when attempting to execute commands before authenticating.
  2. The AUTH command returns OK as a simple string on successful authentication.
  3. The client can execute commands successfully after authentication.
Notes
  • All commands except AUTH should return NOAUTH errors when executed by an unauthenticated connection. This rule applies to every command you have implemented, not only to ACL commands.

Original stage ws7

Back to contents

Source and licence

Stage material by CodeCrafters. Source snapshot · Original licence.

MIT License

Copyright (c) 2022 CodeCrafters

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.