builds / redis / stage-2SHEET 2 / 6 · REV ASIGN IN
ASSEMBLY DIAGRAM — YOUR REDISSCALE: LEARNING
clientthe outside worldPORT JACK✓ builtRESP CODEC⚙ buildingMEMORY BANKstage 3INTERLOCKstage 4CLOCK UNITstage 5FLIGHT RECORDERstage 6
BUILTUNDER CONSTRUCTIONNOT YET IMAGINED INTO EXISTENCE
STAGE 2 · THE PROTOCOL CODEC

Speaking in Frames

RESP: the first byte tells you the type, lengths are declared up front.

What you're wiring up

RESP is Redis's wire format, and it's beautifully learnable: the first byte gives the type (+ simple string, - error, : integer, $ bulk string, * array), and lengths are declared before payloads so you never guess where a message ends. Every client command is an array of bulk strings.

This stage replaces Stage 1's "contains PING" hack with an honest parser and serializer — the same "schema on the wire" idea DDIA's encoding chapter is about. The parser must survive the stream reality: a frame may arrive split across two reads, or ten frames may arrive in one.

# SET name ansh, on the wire:
*3\r\n$3\r\nSET\r\n$4\r\nname\r\n$4\r\nansh\r\n

Assembly steps

[ 01 ]
Write ReadCommand(r *bufio.Reader) ([]string, error) — parse one RESP array of bulk strings into a slice of args.
hint

bufio.Reader.ReadString('\n') handles the partial-read problem for you — it blocks until the delimiter arrives. Strip the \r.

hint

After a $N length line, read exactly N bytes then consume the trailing \r\n — bulk strings may legally contain \r\n inside.

[ 02 ]
Write the serializer side: helpers for simple string, error, integer, bulk string, and the null bulk string $-1\r\n.
hint

You'll need the null bulk constantly from Stage 3 on.

[ 03 ]
Dispatch on the first arg, case-insensitively: PING (now parsed properly, incl. PING <msg>) and ECHO <msg>.
hint

strings.ToUpper(args[0]) in a switch is enough — resist building a command-registry framework.

[ 04 ]
Reply -ERR unknown command for anything else, and keep the connection alive afterwards.
hint

Only tear down the connection on a malformed frame (unparseable bytes), not on an unknown command.

Go deeper (after it passes)

Pairs with DDIA M4 — Wire Formats That Survive Change, and Clean Code M5 — Errors Without the Clutter.