Build your own Redis-compatible server in Go

How I built respkv, a key-value server that redis-cli can talk to, and how you can build one too, starting from a TCP echo server.

gonetworkingredis
Contents

I am interested in low-level systems and networking: what happens between a socket and a reply, and how a server keeps data safe on disk. A Redis-compatible server was a good first project for that. It is small enough to finish, and it touches all of it: TCP, a wire protocol, concurrency and persistence.

respkv is a key-value server in Go that speaks the Redis protocol. redis-cli, redis-benchmark and Redis client libraries work with it, as if it were Redis. You can try it on its project page, where it runs in your browser.

I built it in about three weeks, one layer at a time: a TCP echo server, commands, a shared store, key expiration, the Redis protocol, persistence. This post follows the same path. Each part has a small piece of code that you can run, and a note on what the full respkv does on top of it.

The snippets leave out most error handling to stay short. The complete code is on GitHub. You need basic Go, and Docker if you do not have redis-cli installed.

A server that talks

First, a server that accepts connections and answers simple commands. No storage yet, and no Redis protocol.

An echo server

Every server starts the same way: listen on a port, accept connections, and handle each one. Here is a server that sends back every line it receives:

package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
)

func main() {
	listener, err := net.Listen("tcp", "127.0.0.1:9000")
	if err != nil {
		log.Fatal(err)
	}
	log.Println("listening on", listener.Addr())

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Println("accept:", err)
			continue
		}
		go handle(conn)
	}
}

func handle(conn net.Conn) {
	defer conn.Close()
	scanner := bufio.NewScanner(conn)
	for scanner.Scan() {
		fmt.Fprintln(conn, scanner.Text())
	}
}

Run it with go run . and connect with nc 127.0.0.1 9000. Type a line, and it comes back.

The key line is go handle(conn). Each connection gets its own goroutine, a lightweight thread managed by the Go runtime. A thousand clients mean a thousand goroutines, and that is fine: each one starts with a few kilobytes of stack.

In respkv: starting goroutines is easy, stopping them is harder. A goroutine waiting in Read does not notice that the server is shutting down. respkv makes the read fail on purpose: when the server gets Ctrl+C or SIGTERM, it sets every connection’s read deadline to “now”, so blocked reads return and handlers exit. The server then waits for all of them before it quits. It also drops clients that stay silent for 5 minutes, or that do not read their replies for 5 seconds.

Commands

An echo server only repeats. Let us make it answer. Split each line into words, treat the first word as a command, and reply:

func execute(args []string) string {
	if len(args) == 0 {
		return ""
	}
	switch strings.ToUpper(args[0]) {
	case "PING":
		return "PONG"
	case "ECHO":
		if len(args) != 2 {
			return "ERR wrong number of arguments for 'echo' command"
		}
		return args[1]
	default:
		return fmt.Sprintf("ERR unknown command '%s'", args[0])
	}
}

In handle, replace the echo with:

fmt.Fprintln(conn, execute(strings.Fields(scanner.Text())))

Now PING answers PONG, and ECHO hello answers hello.

In respkv: TCP gives you a stream of bytes, not a series of messages. One Read can return half a command, or three commands at once. bufio.Scanner hides this by collecting bytes until a full line arrives. One question remains: what if the client disconnects in the middle of a line? respkv drops an incomplete command instead of running it, so a cut connection can never run half of a SET.

Keeping data

Now the server needs to remember things: keys and values shared by all clients, and keys that disappear after a while.

A shared store

A key-value server needs somewhere to keep the keys. A Go map is the obvious choice, but every connection runs in its own goroutine, and a map is not safe to change from several goroutines at once. Go detects this and crashes with concurrent map writes.

The fix is a mutex around the map:

type Store struct {
	mu   sync.RWMutex
	data map[string]string
}

func NewStore() *Store {
	return &Store{data: make(map[string]string)}
}

func (s *Store) Set(key, value string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data[key] = value
}

func (s *Store) Get(key string) (string, bool) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	value, ok := s.data[key]
	return value, ok
}

func (s *Store) Delete(key string) bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	_, ok := s.data[key]
	delete(s.data, key)
	return ok
}

RWMutex lets many readers in at once, but a writer gets the map to itself. That suits a cache, where reads are far more common than writes.

Create one store in main, pass it to every handle, and add SET, GET and DEL to execute:

case "GET":
	value, ok := store.Get(args[1])
	if !ok {
		return "(nil)"
	}
	return value

In respkv: Go mutexes are not reentrant. If Set holds the lock and calls Get, which tries to take it again, the goroutine waits for itself forever. If you come from Python, this is the difference between Lock and RLock. respkv follows a simple rule: public methods take the lock, and shared logic lives in private helpers named ...Locked, which expect the caller to hold it already.

Keys that expire

Redis keys can have a time to live: EXPIRE session 60 deletes session after a minute. To support that, store a deadline next to each value:

type entry struct {
	value     string
	expiresAt time.Time // zero means no expiration
}

func (e entry) expired(now time.Time) bool {
	return !e.expiresAt.IsZero() && !now.Before(e.expiresAt)
}

With data map[string]entry, Get treats an expired key as missing:

func (s *Store) Get(key string) (string, bool) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	e, ok := s.data[key]
	if !ok || e.expired(time.Now()) {
		return "", false
	}
	return e.value, true
}

This alone is enough for clients, but expired keys still take memory. A background goroutine cleans them up once a second:

func (s *Store) DeleteExpired() {
	s.mu.Lock()
	defer s.mu.Unlock()
	now := time.Now()
	for key, e := range s.data {
		if e.expired(now) {
			delete(s.data, key)
		}
	}
}
go func() {
	for range time.Tick(time.Second) {
		store.DeleteExpired()
	}
}()

Deleting from a map while you range over it is allowed in Go, which surprises people coming from other languages.

In respkv: this is how Redis does it too: expired keys are hidden on read and removed in the background. Redis samples random keys instead of scanning all of them, which matters with millions of keys. The harder part was testing. Tests that sleep for a second are slow and flaky, so the store reads the time through a function field: time.Now in production, a fake clock in tests. Go 1.25 also added testing/synctest, which runs the background loop on a fake clock. And one trap: time.Duration counts nanoseconds in an int64, so EXPIRE key 99999999999 overflows unless you check the range before you multiply.

Speaking Redis

So far, we invented our own protocol. To make redis-cli work, the server has to speak the one Redis clients use.

The RESP format

RESP, the Redis serialization protocol, is a text protocol that is easy to read. A client sends SET greeting hello as an array of three bulk strings:

*3\r\n
$3\r\nSET\r\n
$8\r\ngreeting\r\n
$5\r\nhello\r\n

*3 means “an array of 3 items”, and $8 means “a string of 8 bytes follows”. Because the length comes first, values can hold anything, including spaces and line breaks. The lines are split here for reading; on the wire it is one stream.

Replies carry their type in the first byte:

+OK\r\n                          simple string
-ERR unknown command 'FOO'\r\n   error
:1\r\n                           integer
$5\r\nhello\r\n                  bulk string
$-1\r\n                          null: the key does not exist

Encoding replies and parsing commands

Encoding replies takes one line per type:

func simpleString(s string) string { return "+" + s + "\r\n" }
func errorReply(s string) string   { return "-" + s + "\r\n" }
func integer(n int) string         { return ":" + strconv.Itoa(n) + "\r\n" }
func bulkString(s string) string   { return "$" + strconv.Itoa(len(s)) + "\r\n" + s + "\r\n" }

const nullBulk = "$-1\r\n"

Parsing a command is a little longer. Read the array header, then read each string by its length:

func readCommand(r *bufio.Reader) ([]string, error) {
	n, err := readHeader(r, '*')
	if err != nil {
		return nil, err
	}
	args := make([]string, 0, n)
	for range n {
		size, err := readHeader(r, '$')
		if err != nil {
			return nil, err
		}
		buf := make([]byte, size+2) // the value and its \r\n
		if _, err := io.ReadFull(r, buf); err != nil {
			return nil, err
		}
		args = append(args, string(buf[:size]))
	}
	return args, nil
}

func readHeader(r *bufio.Reader, prefix byte) (int, error) {
	line, err := r.ReadString('\n')
	if err != nil {
		return 0, err
	}
	line = strings.TrimSuffix(line, "\r\n")
	if len(line) == 0 || line[0] != prefix {
		return 0, fmt.Errorf("expected %q, got %q", prefix, line)
	}
	return strconv.Atoi(line[1:])
}

io.ReadFull is what makes this work over TCP: it keeps reading until it has exactly size + 2 bytes, however they arrive.

Talking to redis-cli

Now execute returns encoded replies, for example for GET:

value, ok := store.Get(args[1])
if !ok {
	return nullBulk
}
return bulkString(value)

Start the server and connect with the real Redis client:

docker run --rm -it --network host redis:7 redis-cli -p 9000
127.0.0.1:9000> SET greeting "hello world"
OK
127.0.0.1:9000> GET greeting
"hello world"
127.0.0.1:9000> GET missing
(nil)

For me, this was the best moment of the project.

In respkv: never trust a length that comes from the network. In the parser above, a client can send $-5 and make make panic, or $9999999999 and make the server try to allocate gigabytes. respkv allows at most 1024 arguments and 1 MiB per argument, and closes the connection on anything malformed. Two fuzz tests feed the parser random bytes to find inputs I did not think of. respkv also accepts inline commands, plain lines like the ones our first version split with strings.Fields, because Redis does too. That brought the first compatibility bug: redis-cli --pipe sends an empty line, and Redis ignores it without a reply. respkv now does the same.

Pipelining for free

A client does not have to wait for each reply before it sends the next command. It can send 16 commands at once, which is called pipelining. Our server already handles that: readCommand reads them one by one from the buffer. But it writes 16 replies with 16 system calls.

The fix is to buffer replies and send them when there is nothing more to read:

func handle(conn net.Conn, store *Store) {
	defer conn.Close()
	reader := bufio.NewReader(conn)
	writer := bufio.NewWriter(conn)
	for {
		args, err := readCommand(reader)
		if err != nil {
			return
		}
		writer.WriteString(execute(store, args))
		if reader.Buffered() == 0 {
			if err := writer.Flush(); err != nil {
				return
			}
		}
	}
}

reader.Buffered() tells how many received bytes are still waiting. Zero means the client has sent everything it had, so it is time to answer. Sixteen commands now get sixteen replies in one write. The benchmark below shows how much this matters.

Surviving a restart

Everything so far lives in memory and is gone when the server stops. Redis solves this with an append-only file (AOF): every change is written to a file as a command, and on startup the server runs the file again.

We already have everything we need: commands are RESP, so the file can be RESP too, and readCommand can read it back.

Logging changes

The AOF type opens the file in append mode and writes each command as a RESP array:

type AOF struct {
	mu   sync.Mutex
	file *os.File
}

func OpenAOF(path string) (*AOF, error) {
	file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
	if err != nil {
		return nil, err
	}
	return &AOF{file: file}, nil
}

func (a *AOF) Append(args ...string) error {
	a.mu.Lock()
	defer a.mu.Unlock()
	var b strings.Builder
	fmt.Fprintf(&b, "*%d\r\n", len(args))
	for _, arg := range args {
		b.WriteString(bulkString(arg))
	}
	_, err := a.file.WriteString(b.String())
	return err
}

The store logs each change while it holds its lock, so the file keeps the same order as the changes:

func (s *Store) Set(key, value string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data[key] = entry{value: value}
	if s.aof != nil {
		s.aof.Append("SET", key, value)
	}
}

Replaying the file on startup

On startup, replay the file before you attach it to the store, so the replay does not write every command again:

func loadAOF(path string, store *Store) error {
	file, err := os.Open(path)
	if errors.Is(err, os.ErrNotExist) {
		return nil
	}
	if err != nil {
		return err
	}
	defer file.Close()

	reader := bufio.NewReader(file)
	for {
		args, err := readCommand(reader)
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		execute(store, args)
	}
}

Set a key, stop the server, start it again: the key is still there.

In respkv: the details took longer than the idea.

  • Expirations are saved as absolute times. If the file said EXPIRE session 60, a replay a day later would give the key another minute. respkv writes PEXPIREAT session <Unix time in ms> instead, so downtime counts.
  • A crash can cut off the last record. On startup, respkv drops an incomplete last record and trims the file. A broken record in the middle means corruption, and the server refuses to start.
  • Write the file before you reply. My first version sometimes sent OK before the record reached the file, so a crash could lose a write the client was told had succeeded.
  • WriteString does not mean “on disk”. The data goes to the operating system, which survives a crash of the server but not a power loss. To be safe from that, you call fsync, which is slow. Like Redis, respkv lets you choose: after every change, once a second (the default) or never. Even once a second, pipelined SET drops from 1.42 million to 564 thousand requests per second.

Testing over a real socket

Unit tests for execute and readCommand are easy. I also wanted tests that talk to a real server over TCP, the way a client does. Move the accept loop from main into a function serve(listener, store), and a test can start the server on a free port:

func TestPing(t *testing.T) {
	listener, err := net.Listen("tcp", "127.0.0.1:0") // port 0: any free port
	if err != nil {
		t.Fatal(err)
	}
	defer listener.Close()
	go serve(listener, NewStore())

	conn, err := net.Dial("tcp", listener.Addr().String())
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()

	fmt.Fprint(conn, "*1\r\n$4\r\nPING\r\n")
	got, err := bufio.NewReader(conn).ReadString('\n')
	if err != nil {
		t.Fatal(err)
	}
	if want := "+PONG\r\n"; got != want {
		t.Errorf("got %q, want %q", got, want)
	}
}

Run the tests with go test -race. The race detector reports two goroutines that touch the same memory without a lock, the kind of bug that otherwise shows up once a month in production.

In respkv: I added these tests and CI on day four, before the server understood a single command. It felt early, but every later layer ran against them, with the race detector on.

How fast is it?

redis-benchmark comes with Redis and works against any server that speaks RESP. With respkv running on port 9000:

docker run --rm --network host redis:7 redis-benchmark -p 9000 \
  -t set,get -n 1000000 -c 50 -r 100000 -d 64 -P 16 -q

Here is respkv against Redis 7 on my laptop:

ops/s SET GET SET ×16 GET ×16
respkv 241k 257k 1.42M 2.69M
respkv + AOF 236k 256k 564k 2.54M
Redis 7 288k 307k 1.89M 2.02M
Redis 7 + AOF 298k 307k 1.09M 1.99M

50 clients, 100k random keys, 64-byte values; ×16 = pipelines of 16 commands. Same machine over loopback: AMD Ryzen AI 7 PRO 350, 8 cores, 16 threads.

Two things stand out. Pipelining multiplies the throughput of both servers by five to ten times, because most of the time goes to network round trips, not to the commands. And pipelined GET is faster in respkv than in Redis. Redis runs commands on one thread, while respkv runs reads on all cores at once, thanks to the RWMutex.

Writes are the weak spot. Every SET takes the exclusive lock, so writes run one at a time. A CPU profile with pprof showed respkv using less than two of sixteen cores under pipelined SET with the AOF. The profile also showed where the time went: building each AOF record while holding the lock. Writing records straight into the file buffer gave about 30% more in a quick test.

Going further

A few more features make respkv usable outside a terminal. Each one is small in Go:

  • TLS. tls.NewListener wraps the listener, and the rest of the server does not change. redis-cli --tls connects to it.
  • Metrics. The Prometheus client library counts commands, measures their duration and exposes it all over HTTP, next to pprof.
  • Docker. A static Go binary needs no operating system, so the image is the binary on a minimal base: about 22 MB.
  • WebAssembly. Go compiles to WebAssembly. Build tags leave out the network code, and the browser calls the store and commands directly. That is how the playground on the project page works.

How I worked

I built respkv together with an AI agent, but not by asking it to write the server.

First, we talked the project through and planned it: what respkv should do, in what order to build it, and what to leave out. The agent then split the plan into small steps, much like the parts of this post. At the start of each step, it gave me an introduction: what the step is for, which parts of Go and of the protocol it needs, and what to watch out for.

Then I wrote the code. When I got stuck, I asked the agent for help, and when a step was done, it reviewed my code before I committed it. The reviews also checked the tests: the agent put a bug back into a copy of the code and made sure a test failed.

What is next

respkv supports PING, ECHO, SET, GET, DEL, EXPIRE, PEXPIREAT and TTL. If you build your own, good next steps are more commands, such as INCR, EXISTS and MGET, and rewriting the AOF to a compact form, since it grows with every change, even to the same key.

The full code, with tests and benchmarks, is on GitHub.