Nyx by Example

RESP Protocol

RESP (REdis Serialization Protocol) is the text-based wire format used by Redis and nyx-kv. Each data type has a single-character prefix: + simple string, - error, : integer, $ bulk string, * array. All lines are terminated with \r\n. This recipe shows how to manually construct RESP messages.

Code

// RESP protocol — Redis serialization format

fn main() -> int {
    // Simple string: +OK\r\n
    let simple: String = "+OK\r\n"
    print("simple string: " + simple.trim())

    // Error: -ERR unknown command\r\n
    let error: String = "-ERR unknown command\r\n"
    print("error: " + error.trim())

    // Integer: :42\r\n
    let integer: String = ":" + int_to_string(42) + "\r\n"
    print("integer: " + integer.trim())

    // Bulk string: $5\r\nhello\r\n
    let data: String = "hello"
    let bulk: String = "$" + int_to_string(data.length()) + "\r\n" + data + "\r\n"
    print("bulk string: " + bulk.trim())

    // Array: *3\r\n$3\r\nSET\r\n$4\r\nname\r\n$3\r\nNyx\r\n
    let cmd: String = "*3\r\n$3\r\nSET\r\n$4\r\nname\r\n$3\r\nNyx\r\n"
    print("SET command: " + cmd.replace("\r\n", " ").trim())

    return 0
}

Output

simple string: +OK
error: -ERR unknown command
integer: :42
bulk string: $5 hello
SET command: *3 $3 SET $4 name $3 Nyx

Explanation

RESP is deliberately simple: every message is human-readable text terminated by \r\n. Bulk strings include a length prefix ($5\r\nhello\r\n), which allows binary-safe values. Arrays use *N to indicate the count of elements that follow.

Redis commands are sent as RESP arrays of bulk strings. For example, SET name Nyx becomes *3\r\n$3\r\nSET\r\n$4\r\nname\r\n$3\r\nNyx\r\n. This is the same format that nyx-kv speaks on port 6380, compatible with redis-cli.

← Previous Next →

Source: examples/by-example/54-resp-protocol.nx