Reading — step 1 of 3
The Real RESP Wire Protocol
RESP Array Parsing — The Real Wire Protocol
So far we've been pretending Redis takes commands as space-separated text lines. That's a teaching simplification. Real Redis clients never do that.
A real redis-cli SET foo bar actually sends these bytes over the wire:
*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n
That's a RESP array of three bulk strings. The same format we've been using for responses — Redis uses it for requests too. Every Redis command is just an array of bulk strings.
Why Bulk-String Requests?
Three reasons:
1. Binary safety. What if your value is "hello\r\nworld"? Or a JPEG? Or contains spaces? Space-splitting would mangle it. Length-prefixed bulk strings carry any bytes — no escaping, no quoting.
2. Streaming. The server knows exactly how many bytes to read for each argument before it sees the next one. Parsers don't need to look ahead.
3. Uniformity. Request and response use the same protocol. Clients reuse the same encoder/decoder for both directions. Beautiful.
Anatomy of a Request
For SET foo bar:
| Bytes | Meaning |
|---|---|
*3\r\n | Array of 3 elements |
$3\r\n | Next element is a 3-byte bulk string |
SET\r\n | The 3 bytes |
$3\r\n | Next bulk string, 3 bytes |
foo\r\n | The bytes |
$3\r\n | Next, 3 bytes |
bar\r\n | The bytes |
Inline Commands (Legacy)
Real Redis also accepts a "human-readable" inline form for telnet debugging: a plain text line like PING\r\n. We've been using a stripped version of this. But the bulk-array form is what every real client sends.
What You'll Build
A parser that:
- Reads
*N\r\nand extracts N - Loops N times, each time reading
$len\r\n<bytes>\r\n - Builds the args list
[cmd, arg1, ...] - Calls your existing command handler
The parser must read bytes, not lines. Bulk-string contents can contain newlines, nulls, anything. Length-prefix discipline is the whole point.
Why This Lesson Matters
Without this, your "Redis" can't talk to redis-cli, jedis, go-redis, node-redis, or any other real client. After this lesson, you have a server that speaks the same wire format as the real thing.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…