
Part 1: Overall System Architecture & RESP Protocol Parsing
Before looking at the parser code, let's look at the lifecycle of a request in our server.
📡 The Runtime Context Flow
+-----------------------------+ | TCP Client | +-----------------------------+ │ ▲ 1. Raw RESP Command │ │ 6. Serialized RESP Response (e.g., *2\r\n$4\r\n...)│ │ (e.g., +PONG\r\n) ▼ │ +-----------------------------+ | Network Socket | +-----------------------------+ │ ▲ ▼ │ +------------------------------+ │ | BufferedInputStream | │ +------------------------------+ │ │ │ ▼ │ +------------------------------+ │ | RespParser.RespReader | │ +------------------------------+ │ │ │ ▼ │ +------------------------------+ │ | RespValue (Type.ARRAY) | │ +------------------------------+ │ │ │ ▼ │ +------------------------------+ │ | Database Engine | │ +------------------------------+ │ │ │ ▼ │ +------------------------------+ │ | RespValue (Type.SIMPLE_STR) ────┘ +------------------------------+
How Execution Flows at Runtime:
- Network Layer: A client (like
redis-cli) connects to our server on port6379. The Operating System's TCP stack establishes a connection, represented in Java as aSocket. - Buffering: The
Socketgives us anInputStream(raw bytes). We wrap it in aBufferedInputStreamto prevent making expensive system calls for every single byte read. - Parsing: The
RespReaderprocesses the stream byte-by-byte. It reads the prefix (*,$,:, etc.), determines the type, parses the payload, and produces a structuredRespValueobject. - Routing: The
RedisServerextracts the command name and arguments from theRespValuearray and routes them to theDatabaseengine. - Execution: The
Databaseruns the command against a thread-safeConcurrentHashMapstore and returns a responseRespValueobject (e.g.,+OK\r\n). - Serialization: The response
RespValueis serialized back to a raw byte array (byte[]) and written directly to the socket'sOutputStream.