Learn how Redis clients and servers communicate
REdis Serialization Protocol is the protocol Redis servers & clients use to communicate with each other.
REdis Serialization Protocol is the protocol Redis servers & clients use to communicate with each other.
RESP2 (the default) supports encoding 5 data types:
Each data type encoding begins with a different prefix:
+
denotes a simple string-
denotes a simple error:
denotes an integer$
denotes a bulk string*
denotes an arrayIn the encoding +PONG\r\n
:
+
denotes a simple string.PONG
is the string value\r\n
is the CRLF terminatorUsed to send simple, human readable messages.
They are encoded as: +<data>\r\n
Examples:
hello
would be encoded as +hello\r\n
hello world
would be encoded as +hello world\r\n
Used to return error messages.
They are encoded as: -<error message>\r\n
Example:
ERR unknown command "SETT"
would be encoded as -ERR unknown command "SETT"\r\n
Integers are encoded as :<value>\r\n
Examples:
42
would be encoded as :42\r\n
-52
would be encoded as :-52\r\n
Used to represent binary strings (aka "byte string").
Unlike simple strings, bulk strings can contain any type of character, including newlines and control characters.
Bulk strings are encoded as $<length>\r\n<data>\r\n
.
Examples:
hello
would be encoded as $5\r\nhello\r\n
hello world
would be encoded as $11\r\nhello world\r\n$
""
would be encoded as $0\r\n\r\n
Aside: RESP2 does not have a dedicated type for null values.
A special null bulk string can be used to represent a null value.
It is encoded as:
$-1\r\n
Arrays are encoded as *<number-of-elements>\r\n<element-1>...<element-n>
where <element-1>
, <element-2>
are the RESP encoded values of the elements in the list.
Examples:
[42,52]
would be encoded as *2\r\n:42\r\n:52\r\n
["hello",42]
, where hello
is a bulk string, would be encoded as *2\r\n$5\r\nhello\r\n:42\r\n
All commands are sent to the server as a RESP Array of Bulk Strings. The first (and sometimes second) element of the RESP array is the command name and the rest are its arguments.
The server replies to clients with any valid RESP data type.
For e.g. the command SET foo bar
would have this structure:
[SET, "foo", "bar"]
and would be encoded as:
*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n
If the operation was successful, the server would respond with a simple OK
encoded as:
+OK\r\n
We covered the 5 data types supported by RESP:
hello
-> +hello\r\n
)ERR
-> -ERR\r\n
)42
-> :42\r\n
)hello
-> $5\r\nhello\r\n
)[42, 52]
-> *2\r\n:42\r\n:52\r\n
)We also discussed how clients send commands to Redis servers and how the server responds to them:
If you want to learn more about RESP, check out the official spec.