𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗥𝗘𝗦𝗣: 𝗧𝗵𝗲 𝗣𝗿𝗼𝘁𝗼𝗰𝗼𝗹 𝗕𝗲𝗵𝗶𝗻𝗱 𝗥𝗲𝗱𝗶𝘀

In my previous post, I shared an overview of my Redis clone built with Node.js. Now, I want to explain a critical part of this project: RESP, or the Redis Serialization Protocol.

Redis does not receive nice JavaScript arrays. It receives raw bytes over a TCP socket. To work, these bytes need a structure. The server must know where a command starts and ends. It must know how many arguments exist and how long each one is.

RESP provides this structure. It is the language clients and servers use to talk.

For example, the command GET name looks like this in RESP: *2\r\n$3\r\nGET\r\n$4\r\nname\r\n

Here is the breakdown:

  • *2 means an array with 2 elements.
  • $3 means the next part is 3 bytes long: GET.
  • $4 means the next part is 4 bytes long: name.

The parser turns these bytes into ["GET", "name"]. Now the engine can run the command.

Why not just split strings by spaces? Simple splitting fails with values that contain spaces, like SET message "hello world". It also fails with binary data. RESP solves this by including the length of every value. The server reads exactly the number of bytes specified. This makes it binary-safe and reliable.

The hardest lesson was learning that TCP is stream-based, not message-based. A server does not always receive one complete command at a time. A command might arrive in two separate chunks. Or, multiple commands might arrive in one single chunk.

This means the parser cannot assume one data event equals one command. The parser must use an internal buffer.

My RESP parser works like this:

  1. Receive bytes from the socket.
  2. Add bytes to a buffer.
  3. Try to parse a complete command.
  4. If the command is incomplete, wait for more data.
  5. If a command is complete, return it.
  6. If extra data remains, keep it in the buffer for the next parse.

A database starts at the protocol layer. Before Redis can store data, it must understand the command. Before it returns a value, it must encode the response.

Implementing RESP turned a simple TCP server into a true Redis-compatible system. It changed how I see backend systems. A protocol is more than a format. It is a contract between two systems.

In my next post, I will cover the in-memory storage layer.

מאגר (Repo): https://github.com/Abhinov007/redis_clone סביבת Sandbox חיה: https://abhinov007.github.io/Redis_Clone/ מקור: https://dev.to/abhinov007/understanding-resp-the-protocol-behind-redis-50p4