Blog

Part 30 · Capstone: A Multi-threaded Key-Value Server in Rust

The last part builds a small key-value server over TCP with only the standard library. It has a line protocol, a shared map, a pool of worker threads, a clean shutdown, and tests that talk to it over real sockets.

This last part puts the series to work on one program: a key-value server. Clients connect over TCP and send one command per line, like SET name Ana or GET name. The server keeps the data in memory, in one map shared by every thread. It’s small, about 650 lines with its tests and demo, but it’s the same shape as real servers: it parses untrusted input, shares state between threads, and must keep running when a client misbehaves.

We’ll build it one file at a time, in the order you’d write it, and say why each design choice was made. Almost every part of the series shows up somewhere, and a table near the end links each piece back to the part that taught it. The project is a cargo package with modules (Part 18), tests (Part 19), threads (Part 23) and Arc, Mutex and channels (Part 24). Every program here was run on Rust 1.95, and its output is pasted from the run.

Try this first

Here’s the simplest server we could write. One thread accepts a connection, answers every line that client sends, and only takes the next client when this one hangs up. Two clients, a and b, use it from main:

use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:0")?;
    let addr = listener.local_addr()?;

    // A server with one thread: it serves one client until that client
    // hangs up, then takes the next.
    thread::spawn(move || {
        for stream in listener.incoming() {
            let mut stream = stream.unwrap();
            let reader = BufReader::new(stream.try_clone().unwrap());
            for line in reader.lines() {
                let reply = format!("you said: {}\n", line.unwrap());
                stream.write_all(reply.as_bytes()).unwrap();
            }
        }
    });

    let mut a = TcpStream::connect(addr)?;
    a.write_all(b"hello from a\n")?;
    let mut reply = String::new();
    BufReader::new(a.try_clone()?).read_line(&mut reply)?;
    print!("a got {reply}");

    let mut b = TcpStream::connect(addr)?;
    println!("b connected");
    b.write_all(b"hello from b\n")?;
    b.set_nonblocking(true)?;
    let mut buf = [0; 64];
    match b.read(&mut buf) {
        Err(e) if e.kind() == ErrorKind::WouldBlock => println!("b has no reply yet"),
        other => println!("b: {other:?}"),
    }

    drop(a);
    b.set_nonblocking(false)?;
    let mut reply = String::new();
    BufReader::new(b).read_line(&mut reply)?;
    print!("b got {reply}");
    Ok(())
}

Before you read on, guess two things. The server thread is busy with a when b calls connect. Does b‘s connect succeed? And when does b get its reply?

It prints:

a got you said: hello from a
b connected
b has no reply yet
b got you said: hello from b

b connects at once. The operating system accepts new connections into a waiting list, called the backlog, before the program calls accept. So b is connected, and its line is sitting in a buffer, but nobody is reading it. The one server thread is still inside the for line in reader.lines() loop for a, waiting for a‘s next line.

set_nonblocking(true) makes read return at once instead of waiting. It returns the error WouldBlock, which means “nothing to read yet”. Only when main drops a does the server’s loop end, accept hand over b, and b get its answer.

That’s the problem with one thread: one slow client stops everybody. The rest of this part fixes it with a pool of worker threads, and then makes sure that a bad client can’t stop the server in other ways.

Three new standard library types appear here. TcpListener waits for connections on an address. TcpStream is one connection, which you read from and write to like a file. 127.0.0.1 is this machine, and port 0 asks the operating system for any free port. local_addr tells us which one it picked. The program never prints the port, because it changes on every run.

What we’re building

The protocol is plain text, one command per line, and one reply line per command:

Client sends Server replies
SET key value OK
GET key VALUE v, or NOT_FOUND
DEL key OK, or NOT_FOUND
COUNT VALUE n, the number of keys
QUIT OK, then the server closes the connection
anything else ERR and a reason, and the connection stays open

A key is one word. A value is the rest of the line, so it may hold spaces. A plain-text protocol like this is easy to type by hand and easy to test.

The package is called kv, and it’s laid out the way Part 18 showed:

kv/
  Cargo.toml
  src/
    lib.rs        declares the modules
    protocol.rs   a line of text -> a Command; a Reply -> a line of text
    store.rs      the shared map
    server.rs     the accept loop, the worker pool, one client's session
    client.rs     a tiny client, for the demo and the tests
    main.rs       runs the server on port 7878
  examples/
    demo.rs       a scripted session, printed
  tests/
    server.rs     integration tests over real sockets

Here are the threads and what each one holds while the server runs:

one acceptor, one channel, four workers, one store acceptor thread owns the Sender send mpsc channel (queue) stream E recv Arc<Mutex<Receiver>> one receiving end, shared worker 1 serving client A client A worker 2 serving client B client B worker 3 serving client C client C worker 4 serving client D client D Store: Arc<Mutex<HashMap<String, String>>> one map behind one lock, shared by every worker owns (the TcpStream moves along these) shared through a clone of an Arc

The acceptor moves each new connection into the channel. Whichever worker is free takes it out and owns it until the client leaves. The receiver and the store are each shared by all four workers through an Arc.

Here’s the figure in words:

  1. The acceptor thread loops over listener.incoming(). Each new connection is a TcpStream, and the acceptor sends it into an mpsc channel. Sending moves the stream: the acceptor no longer owns it.
  2. The channel queues the streams. In the picture, client E’s stream is waiting because all four workers are busy.
  3. The channel has one receiving end. All four workers share it, through an Arc<Mutex<Receiver<TcpStream>>>.
  4. A worker that’s free takes the next stream out of the channel. From then on that worker owns the stream and talks to that client, until the client sends QUIT or hangs up.
  5. Every worker also holds a clone of the Store. All the clones point at one HashMap behind one Mutex.

Solid arrows are owners and dashed blue arrows are shared access, as everywhere in this series. Here the sharing goes through Arc clones instead of & borrows, because each thread needs a handle it owns (Part 23 explained why thread::spawn needs that).

Step 1: the protocol

We start with the part that has no threads and no sockets at all: turning a line of text into a command. That’s the code most likely to meet bad input, so it should be easy to test on its own.

A command is an enum, one variant per command (Part 11). The ways a line can be wrong are a second enum, our own error type (Part 12):

/// One line from a client, after parsing.
#[derive(Debug, PartialEq)]
pub enum Command {
    Set { key: String, value: String },
    Get(String),
    Del(String),
    Count,
    Quit,
}

/// Why a line isn't a command.
#[derive(Debug, PartialEq)]
pub enum ParseError {
    Empty,
    Unknown(String),
    Usage(&'static str),
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ParseError::Empty => write!(f, "empty line"),
            ParseError::Unknown(word) => write!(f, "unknown command {word}"),
            ParseError::Usage(usage) => write!(f, "usage: {usage}"),
        }
    }
}

impl std::error::Error for ParseError {}

Usage holds a &'static str, a piece of fixed text such as "GET key". Part 25 explained 'static: the text is built into the program, so it lives as long as the program does. Display decides what the client will see after ERR. The empty std::error::Error impl marks ParseError as a proper error type, so it works with ? and Box<dyn Error>.

To parse, we implement the standard trait FromStr. It’s the trait behind str::parse: once Command implements it, "GET name".parse::<Command>() works, the same as "42".parse::<i32>(). type Err = ParseError is an associated type (Part 22): each type that implements FromStr names its own error type.

impl FromStr for Command {
    type Err = ParseError;

    /// Parses one line. Spaces and the line ending around it are ignored.
    fn from_str(line: &str) -> Result<Command, ParseError> {
        let line = line.trim();
        let (word, rest) = match line.split_once(' ') {
            Some((word, rest)) => (word, rest.trim_start()),
            None => (line, ""),
        };
        match word {
            "" => Err(ParseError::Empty),
            "SET" => {
                let (key, value) = rest
                    .split_once(' ')
                    .ok_or(ParseError::Usage("SET key value"))?;
                Ok(Command::Set {
                    key: key.to_string(),
                    value: value.trim_start().to_string(),
                })
            }
            "GET" => one_key(rest, "GET key").map(Command::Get),
            "DEL" => one_key(rest, "DEL key").map(Command::Del),
            "COUNT" => no_args(rest, "COUNT").map(|()| Command::Count),
            "QUIT" => no_args(rest, "QUIT").map(|()| Command::Quit),
            other => Err(ParseError::Unknown(other.to_string())),
        }
    }
}

fn one_key(rest: &str, usage: &'static str) -> Result<String, ParseError> {
    if rest.is_empty() || rest.contains(' ') {
        return Err(ParseError::Usage(usage));
    }
    Ok(rest.to_string())
}

fn no_args(rest: &str, usage: &'static str) -> Result<(), ParseError> {
    if rest.is_empty() {
        Ok(())
    } else {
        Err(ParseError::Usage(usage))
    }
}

It splits off the first word, then each command checks what’s left. split_once(' ') returns None when there’s no space at all, so "COUNT" becomes the word COUNT and an empty rest. For SET, a second split_once separates the key from the value, and everything after the key is the value. A SET with no value fails that split_once, and ok_or turns the None into a Usage error that ? returns. The two helpers keep GET, DEL, COUNT and QUIT to one line each. .map(Command::Get) uses the variant Command::Get as a function that wraps a String.

The reply side is the mirror image: an enum, and a Display impl that writes the exact text the client sees.

/// What the server sends back: one line per command.
#[derive(Debug, PartialEq)]
pub enum Reply {
    Ok,
    Value(String),
    NotFound,
    Err(String),
}

impl fmt::Display for Reply {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Reply::Ok => write!(f, "OK"),
            Reply::Value(v) => write!(f, "VALUE {v}"),
            Reply::NotFound => write!(f, "NOT_FOUND"),
            Reply::Err(reason) => write!(f, "ERR {reason}"),
        }
    }
}

Our variants Reply::Ok and Reply::Err share their names with Result‘s Ok and Err. That’s allowed, because ours always appear as Reply::Ok and Reply::Err, with the enum’s name in front.

What happens on a malformed line

Nothing special, and that’s the point. A malformed line is just a line whose parse returns Err. The server turns the error into a Reply::Err, sends ERR and the reason, and reads the next line. No panic, no closed connection. The parser’s unit tests pin down every kind of bad line:

    #[test]
    fn rejects_bad_lines() {
        assert_eq!(parse(""), Err(ParseError::Empty));
        assert_eq!(parse("   "), Err(ParseError::Empty));
        assert_eq!(parse("FETCH x"), Err(ParseError::Unknown("FETCH".into())));
        assert_eq!(parse("get x"), Err(ParseError::Unknown("get".into())));
        assert_eq!(parse("SET name"), Err(ParseError::Usage("SET key value")));
        assert_eq!(parse("GET"), Err(ParseError::Usage("GET key")));
        assert_eq!(parse("GET a b"), Err(ParseError::Usage("GET key")));
        assert_eq!(parse("COUNT 3"), Err(ParseError::Usage("COUNT")));
    }

Commands are case-sensitive: get x is an unknown command. We chose that to keep the parser short. Matching on word.to_ascii_uppercase().as_str() instead of word would change it.

Step 2: the store

The data is one HashMap<String, String>, and every worker thread must be able to read and change it. Part 24 gave us the tool: an Arc so several threads can own it, and a Mutex so only one changes it at a time. We wrap both in a struct, so the rest of the program never sees a lock:

/// A handle to the shared map. Cloning it clones the `Arc`, not the map,
/// so every clone sees the same keys.
#[derive(Clone, Default)]
pub struct Store {
    map: Arc<Mutex<HashMap<String, String>>>,
}

impl Store {
    pub fn new() -> Store {
        Store::default()
    }

    /// Stores the value, and returns the old one if the key was there.
    pub fn set(&self, key: String, value: String) -> Option<String> {
        self.map.lock().unwrap().insert(key, value)
    }

    /// Returns a copy of the value, so the lock is free again at once.
    pub fn get(&self, key: &str) -> Option<String> {
        self.map.lock().unwrap().get(key).cloned()
    }

    /// Removes the key. Returns false if it wasn't there.
    pub fn del(&self, key: &str) -> bool {
        self.map.lock().unwrap().remove(key).is_some()
    }

    pub fn len(&self) -> usize {
        self.map.lock().unwrap().len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

Each worker gets its own Store value, and all of them lead to the same map. Default gives us new for free: an empty map in a new Arc<Mutex<...>>.

Each method takes the lock, does one thing, and lets the guard go at the end of the line. get returns a copy of the value with .cloned(). It could return a reference into the map, but that reference would have to keep the lock held for as long as the caller used it. A copy lets the lock go at once.

The last method turns a Command into a Reply:

    /// Runs one command and says what to send back.
    pub fn apply(&self, command: Command) -> Reply {
        match command {
            Command::Set { key, value } => {
                self.set(key, value);
                Reply::Ok
            }
            Command::Get(key) => match self.get(&key) {
                Some(value) => Reply::Value(value),
                None => Reply::NotFound,
            },
            Command::Del(key) => {
                if self.del(&key) {
                    Reply::Ok
                } else {
                    Reply::NotFound
                }
            }
            Command::Count => Reply::Value(self.len().to_string()),
            Command::Quit => Reply::Ok,
        }
    }

Why a Mutex and not an RwLock

Part 24 showed RwLock, which lets many readers in at once. GET and COUNT only read, so it’s tempting. We picked Mutex for three reasons:

  • Each lock is held for one quick HashMap operation and then let go. Readers barely wait for each other, so there’s little for an RwLock to win.
  • An RwLock does more bookkeeping for each lock and unlock, so for short locks it can be slower, not faster.
  • With a Mutex there’s one rule to think about. Exercise 2 swaps in an RwLock, so you can see that the change is small if a measurement ever says it’s worth it.

Because the lock lives inside Store, that swap touches one file and nothing else.

Step 3: a pool of workers

Now the threads. The Try-this-first server had one thread, and one slow client stopped everyone. There are two common fixes:

  • A thread per connection. Every accept spawns a new thread. It’s simple, and it works well for a few hundred clients. But nothing limits the number of threads, and each one has its own stack, currently 2 MiB by default for spawned threads. Ten thousand idle connections become ten thousand threads.
  • A fixed pool. Start a few worker threads once. The acceptor hands each new connection to whichever worker is free. The number of threads never grows. When all workers are busy, new connections wait in a queue.

We’ll build the pool, because it puts Part 23 and Part 24 together: threads, a channel to hand out work, and Arc<Mutex<...>> to share the channel’s receiving end.

That last piece needs a moment. An mpsc channel has many senders and one receiver, but we have four workers that all want to receive. Sharing the receiver with only an Arc doesn’t compile:

use std::sync::Arc;
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel::<String>();
    let rx = Arc::new(rx);
    let mut workers = Vec::new();
    for id in 0..2 {
        let rx = Arc::clone(&rx);
        workers.push(thread::spawn(move || {
            for job in rx.iter() {
                println!("worker {id} got {job}");
            }
        }));
    }
    tx.send("hello".to_string()).unwrap();
    drop(tx);
    for w in workers {
        w.join().unwrap();
    }
}

It prints:

error[E0277]: `std::sync::mpsc::Receiver<String>` cannot be shared between threads safely
...
    = help: the trait `Sync` is not implemented for `std::sync::mpsc::Receiver<String>`
    = note: required for `Arc<std::sync::mpsc::Receiver<String>>` to implement `Send`

Read the help and note lines together. An Arc<T> may cross to another thread only if T is Sync, because the threads will use the same T at the same time (Part 23 covered Send and Sync). A Receiver isn’t Sync: it isn’t built for two threads calling recv at once. A Mutex fixes that. Mutex<T> is Sync whenever T is Send, because the lock lets only one thread at a time reach the T. So the workers share an Arc<Mutex<Receiver<TcpStream>>>, and whoever holds the lock is the one receiver for that moment.

Here’s the acceptor thread’s whole job:

fn accept_loop(listener: TcpListener, workers: usize, store: Store, stop: &AtomicBool) {
    let (sender, receiver) = mpsc::channel::<TcpStream>();
    let receiver = Arc::new(Mutex::new(receiver));

    let mut pool = Vec::new();
    for _ in 0..workers {
        let receiver = Arc::clone(&receiver);
        let store = store.clone();
        pool.push(thread::spawn(move || worker(&receiver, &store)));
    }

    for stream in listener.incoming() {
        if stop.load(Ordering::SeqCst) {
            break;
        }
        match stream {
            Ok(stream) => {
                if sender.send(stream).is_err() {
                    eprintln!("no workers left");
                    break;
                }
            }
            Err(e) => eprintln!("accept failed: {e}"),
        }
    }

    // No more senders: each worker's recv() returns Err once the queue
    // is empty, and the worker ends.
    drop(sender);
    for handle in pool {
        if handle.join().is_err() {
            eprintln!("a worker panicked");
        }
    }
}

It makes the channel, wraps the receiving end, and starts the workers. Each worker gets its own clone of the Arc and its own clone of the Store, moved into its closure (Part 16). Then it loops over incoming(), an iterator (Part 17) that waits for the next connection each time round. Each new TcpStream is moved into the channel with send.

Errors are handled at each step instead of ignored:

  • accept itself can fail, for example when the process runs out of file descriptors. We print the error and keep accepting. One failed connection shouldn’t stop the server.
  • send fails only if every receiver is gone, which means every worker has ended. Then there’s nobody to serve anyone, so the acceptor stops too.

The stop flag and drop(sender) are the shutdown; Step 5 explains them.

Each worker runs this loop:

fn worker(receiver: &Mutex<Receiver<TcpStream>>, store: &Store) {
    loop {
        // The guard is a temporary, dropped at the end of this statement,
        // so the lock is free again before we serve the client.
        let next = receiver.lock().unwrap().recv();
        let Ok(stream) = next else {
            return;
        };
        if let Err(e) = serve(stream, store) {
            eprintln!("client error: {e}");
        }
    }
}

The lock is held only while recv waits for a stream. As the comment says, the guard that lock() returns is a temporary, and Rust drops temporaries at the end of the statement they’re in. So by the time the worker calls serve, the lock is free, and the next idle worker can wait on recv instead. That detail is easy to get wrong in a way that compiles and passes simple tests; the second worked example below shows how.

let ... else (Part 11) handles the end: recv returns Err once the channel is empty and every Sender is gone. That’s the signal to stop, and the worker returns.

Step 4: talking to one client

serve runs one client’s whole session. It reads a line, works out the reply, writes it, and goes round again:

/// Talks to one client until it sends QUIT or hangs up.
pub fn serve(stream: TcpStream, store: &Store) -> io::Result<()> {
    let mut reader = BufReader::new(stream.try_clone()?);
    let mut writer = stream;
    let mut line = Vec::new();
    loop {
        line.clear();
        let n = reader.read_until(b'\n', &mut line)?;
        if n == 0 || line.last() != Some(&b'\n') {
            // 0 bytes: the client hung up. No newline at the end: it hung
            // up halfway through a line, and half a command isn't one.
            return Ok(());
        }
        let (reply, quit) = respond(&line, store);
        writer.write_all(format!("{reply}\n").as_bytes())?;
        if quit {
            return Ok(());
        }
    }
}

try_clone gives us a second handle to the same connection: one for the BufReader to read from and one to write to. We can’t hand the single stream to both, because BufReader::new takes ownership of what it reads from.

We read with read_until(b'\n', ...) into a Vec<u8>, not with lines() into a String. That’s deliberate. lines() returns an error for a line that isn’t valid UTF-8 (Part 5), and an error there would end the session. Reading bytes lets us decide what invalid text means ourselves:

/// Turns the bytes of one line into a reply. The bool says "hang up now".
pub fn respond(line: &[u8], store: &Store) -> (Reply, bool) {
    let Ok(line) = std::str::from_utf8(line) else {
        return (Reply::Err("line is not valid UTF-8".to_string()), false);
    };
    match line.parse::<Command>() {
        Ok(Command::Quit) => (Reply::Ok, true),
        Ok(command) => (store.apply(command), false),
        Err(e) => (Reply::Err(e.to_string()), false),
    }
}

std::str::from_utf8 checks the bytes without copying them. If they aren’t valid UTF-8, the client gets an ERR line and the session goes on. If they are, parse runs, and its error becomes an ERR line too. QUIT is the one command that ends the session, so respond returns true beside its reply.

respond takes bytes and returns a reply, with no socket in sight. That makes it easy to unit-test, which server.rs‘s own test module does.

Why one client’s error doesn’t kill the server

Here’s every way a client can go wrong, and what happens:

  • It sends a malformed line. parse returns Err, the client gets ERR ..., and the session goes on.
  • It sends bytes that aren’t UTF-8. The client gets ERR line is not valid UTF-8, and the session goes on.
  • It hangs up. read_until returns 0 bytes, and serve returns Ok(()).
  • It hangs up halfway through a line. read_until returns what it got, without a \n at the end. Half a command might be SET name A from a client that meant SET name Ana, so we don’t run it. serve returns Ok(()).
  • It vanishes while we’re writing. The write returns an Err. When we tried it on Linux, the first write to a closed connection still succeeded, and the next one returned BrokenPipe. Rust programs on Unix ignore the SIGPIPE signal that would otherwise kill the process, so this is an ordinary error. ? passes it up out of serve.

In every case, the problem ends at most one session. serve returns, and the worker’s loop prints any error to stderr and goes back to recv for the next client. The only thing that could kill a worker is a panic, and there’s no unwrap on client data anywhere in serve or respond. Tips and traps comes back to this.

Step 5: starting and stopping

Server is what the rest of the program holds. It keeps the address, the stop flag and the acceptor thread’s handle:

/// A running server. Drop it and the threads keep running;
/// call `shutdown` to stop them.
pub struct Server {
    addr: SocketAddr,
    stop: Arc<AtomicBool>,
    acceptor: JoinHandle<()>,
}

impl Server {
    /// Starts serving on a listener that is already bound.
    pub fn start(listener: TcpListener, workers: usize, store: Store) -> io::Result<Server> {
        let addr = listener.local_addr()?;
        let stop = Arc::new(AtomicBool::new(false));
        let flag = Arc::clone(&stop);
        let acceptor = thread::spawn(move || accept_loop(listener, workers, store, &flag));
        Ok(Server {
            addr,
            stop,
            acceptor,
        })
    }

    /// The address the server is listening on, with the real port.
    pub fn addr(&self) -> SocketAddr {
        self.addr
    }

    /// Blocks until the server stops. Nothing in main stops it,
    /// so there this waits until you press Ctrl+C.
    pub fn wait(self) {
        self.acceptor.join().expect("the accept thread panicked");
    }

    /// Stops taking new clients, lets each worker finish the client it
    /// is serving, and waits for every thread to end.
    pub fn shutdown(self) -> io::Result<()> {
        self.stop.store(true, Ordering::SeqCst);
        // accept() is waiting for a client. Be that client, so it wakes
        // up and sees the flag.
        TcpStream::connect(self.addr)?;
        self.acceptor.join().expect("the accept thread panicked");
        Ok(())
    }

start takes a listener that’s already bound, instead of an address. That small choice is what makes the tests easy: a test binds 127.0.0.1:0, gets a free port, and can run beside other tests without any of them fighting over one port. main binds a fixed port, so you know where to connect.

Stopping a thread that’s blocked in accept is the awkward part. There’s no “stop waiting” method on TcpListener in the standard library. So shutdown does it in three steps:

  1. It sets the stop flag, an AtomicBool (Part 24), so it needs no lock.
  2. It connects to the server itself. That wakes accept, the acceptor’s loop checks the flag and breaks out, and the wake-up connection is dropped.
  3. The acceptor drops its Sender and joins the workers. With the sender gone, each worker’s recv returns Err once the queue is empty. A worker in the middle of a session finishes that session first. When all of them have returned, the acceptor’s thread ends, and join in shutdown returns.

That’s a graceful shutdown: no new clients, but nobody already connected gets cut off. It also means shutdown waits for connected clients to leave. The tests always close their clients before calling it.

Step 6: lib.rs, main.rs and the demo

lib.rs declares the modules and re-exports the three types users need, as in Part 18:

//! A tiny key-value server: a line protocol over TCP, one shared map,
//! and a fixed pool of worker threads.

pub mod client;
pub mod protocol;
pub mod server;
pub mod store;

pub use client::Client;
pub use server::Server;
pub use store::Store;

main.rs is short, because the library does the work:

use std::net::TcpListener;

use kv::{Server, Store};

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:7878")?;
    let server = Server::start(listener, 4, Store::new())?;
    println!("listening on {}", server.addr());
    println!("in another terminal: nc 127.0.0.1 7878");
    server.wait();
    Ok(())
}

Run it with cargo run in one terminal. In a second terminal, nc 127.0.0.1 7878 (netcat) connects, and each line you type is sent to the server. Type the commands from the demo below and you’ll get the same replies, one line each. Press Ctrl+C in the first terminal to stop the server. We haven’t pasted a session like that here, because a session typed by hand can’t be checked automatically. The demo is the same conversation, scripted, and we can check it:

use std::net::TcpListener;

use kv::{Client, Server, Store};

fn main() -> std::io::Result<()> {
    // Port 0: the operating system picks a free port.
    let listener = TcpListener::bind("127.0.0.1:0")?;
    let store = Store::new();
    let server = Server::start(listener, 4, store.clone())?;

    let mut a = Client::connect(server.addr())?;
    let script = [
        "SET name Ana",
        "SET city Lisbon",
        "GET name",
        "GET age",
        "SET city Porto",
        "GET city",
        "COUNT",
        "DEL name",
        "DEL name",
        "FETCH name",
        "SET city",
        "get city",
        "QUIT",
    ];
    for line in script {
        println!("a> {line}");
        println!("a< {}", a.send(line)?);
    }

    let mut b = Client::connect(server.addr())?;
    for line in ["GET city", "COUNT", "QUIT"] {
        println!("b> {line}");
        println!("b< {}", b.send(line)?);
    }

    server.shutdown()?;
    println!("server stopped, the store holds {} key", store.len());
    Ok(())
}

client.rs, not shown, is a small struct around a TcpStream. Its send writes a line and reads one reply line. In the kv folder, cargo run --example demo prints:

a> SET name Ana
a< OK
a> SET city Lisbon
a< OK
a> GET name
a< VALUE Ana
a> GET age
a< NOT_FOUND
a> SET city Porto
a< OK
a> GET city
a< VALUE Porto
a> COUNT
a< VALUE 2
a> DEL name
a< OK
a> DEL name
a< NOT_FOUND
a> FETCH name
a< ERR unknown command FETCH
a> SET city
a< ERR usage: SET key value
a> get city
a< ERR unknown command get
a> QUIT
a< OK
b> GET city
b< VALUE Porto
b> COUNT
b< VALUE 1
b> QUIT
b< OK
server stopped, the store holds 1 key

Lines starting a> are what client a sent, and a< lines are the replies. Read it from the top:

  • SET city Porto replaced Lisbon, and COUNT says 2 keys, not 3.
  • The second DEL name is NOT_FOUND, because the first one removed it.
  • The three bad lines each got an ERR, and the session carried on.
  • Client b is a separate connection, served by whichever worker was free. It sees a‘s data, because all workers share one store.
  • After shutdown, the demo still has its own Store clone, so it can check what’s left.

Step 7: the tests

The parser and the store have unit tests in their own files. The server is tested from outside, in tests/server.rs, as an integration test (Part 19): each test starts a real server on a free port and talks to it over real sockets. Each test gets its own server and its own store, so tests running in parallel can’t see each other’s keys:

/// Starts a server on a free port, with its own empty store.
fn start() -> (Server, Store) {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let store = Store::new();
    let server = Server::start(listener, 4, store.clone()).unwrap();
    (server, store)
}

This test is the one for a client that hangs up halfway through a line:

#[test]
fn a_client_that_hangs_up_mid_line_changes_nothing() {
    let (server, store) = start();

    let mut rude = TcpStream::connect(server.addr()).unwrap();
    rude.write_all(b"SET half a line").unwrap();
    rude.shutdown(Shutdown::Write).unwrap();
    // The server closes its end once it has dealt with us, so this read
    // ends only after the worker has seen the half line.
    let mut rest = String::new();
    rude.read_to_string(&mut rest).unwrap();
    assert_eq!(rest, "");

    let mut polite = Client::connect(server.addr()).unwrap();
    assert_eq!(polite.send("COUNT").unwrap(), "VALUE 0");
    drop(polite);
    server.shutdown().unwrap();
    assert!(store.is_empty());
}

shutdown(Shutdown::Write) closes the sending half of the connection, so the server reads a line with no \n and then the end of the stream. The test then reads until the server closes its end. That only happens after the worker has dealt with the half line, so when read_to_string returns, we know the server has made its decision. The test doesn’t sleep and doesn’t guess how long the server needs. Then a second client checks that nothing was stored, and that the server is still answering.

The concurrency test runs 8 client threads, twice as many as there are workers. Each one sets 50 keys of its own and reads them back:

#[test]
fn many_clients_at_once() {
    const CLIENTS: usize = 8;
    const KEYS: usize = 50;
    let (server, store) = start();
    let addr = server.addr();

    let handles: Vec<_> = (0..CLIENTS)
        .map(|c| {
            thread::spawn(move || {
                let mut client = Client::connect(addr).unwrap();
                for k in 0..KEYS {
                    let reply = client.send(&format!("SET c{c}-k{k} {k}")).unwrap();
                    assert_eq!(reply, "OK");
                }
                for k in 0..KEYS {
                    let reply = client.send(&format!("GET c{c}-k{k}")).unwrap();
                    assert_eq!(reply, format!("VALUE {k}"));
                }
                client.send("QUIT").unwrap()
            })
        })
        .collect();
    for h in handles {
        assert_eq!(h.join().unwrap(), "OK");
    }

    let mut client = Client::connect(addr).unwrap();
    let want = format!("VALUE {}", CLIENTS * KEYS);
    assert_eq!(client.send("COUNT").unwrap(), want);
    drop(client);
    server.shutdown().unwrap();
    assert_eq!(store.len(), CLIENTS * KEYS);
}

The keys never collide, because each holds its client’s number. So the final COUNT must be exactly 8 times 50, every run. If two SETs ever overwrote each other’s change to the map, it would come out short. Four of the eight clients also show the queue at work: they connect at once, but their first replies come only when a worker is free.

In the kv folder, cargo test prints:

     Running unittests src/lib.rs

running 10 tests
test protocol::tests::a_value_may_hold_spaces ... ok
test protocol::tests::extra_spaces_and_line_endings_are_ignored ... ok
test protocol::tests::parses_every_command ... ok
test protocol::tests::rejects_bad_lines ... ok
test protocol::tests::replies_print_as_one_line_each ... ok
test server::tests::invalid_utf8_is_an_error_reply_not_a_panic ... ok
test server::tests::respond_runs_commands_and_reports_errors ... ok
test store::tests::apply_turns_commands_into_replies ... ok
test store::tests::clones_share_one_map ... ok
test store::tests::set_get_del ... ok

test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running unittests src/main.rs

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/server.rs

running 6 tests
test a_bad_line_gets_an_error_and_the_session_goes_on ... ok
test a_client_that_hangs_up_mid_line_changes_nothing ... ok
test a_whole_session ... ok
test invalid_utf8_gets_an_error_reply ... ok
test many_clients_at_once ... ok
test two_clients_share_one_store ... ok

test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests kv

running 1 test
test src/protocol.rs - protocol (line 3) ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

As in Part 19, we cut the Compiling and Finished lines, the build path after each Running line, and the doc-test timing line. The tests finish in a different order on each run, so we sorted the test lines within each group. src/main.rs has no tests, so its section says running 0 tests. The doc test is the example at the top of protocol.rs.

A test of threads that passes once has proved very little. The project’s run-checks.sh runs the whole suite 20 more times, and the demo 20 more times. Every run must pass with exactly the output above. It also checks the tests catch real bugs: it removes the half-line check from a copy of serve, and a_client_that_hangs_up_mid_line_changes_nothing must fail.

Worked example: a store that can’t cross threads

Before Arc<Mutex<...>>, a natural first try for a shared map is the single-threaded version from Part 20: Rc for several owners and RefCell to change it through a shared handle.

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::thread;

#[derive(Clone, Default)]
struct Store {
    map: Rc<RefCell<HashMap<String, String>>>,
}

impl Store {
    fn set(&self, key: &str, value: &str) {
        self.map
            .borrow_mut()
            .insert(key.to_string(), value.to_string());
    }
}

fn main() {
    let store = Store::default();
    let mut workers = Vec::new();
    for id in 0..4 {
        let store = store.clone();
        workers.push(thread::spawn(move || {
            store.set(&format!("worker{id}"), "ready");
        }));
    }
    for w in workers {
        w.join().unwrap();
    }
    println!("{} keys", store.map.borrow().len());
}

It prints:

error[E0277]: `Rc<RefCell<HashMap<String, String>>>` cannot be sent between threads safely
...
    = help: within `{closure@src/main.rs:24:36: 24:43}`, the trait `Send` is not implemented for `Rc<RefCell<HashMap<String, String>>>`
note: required because it appears within the type `Store`
...
note: required by a bound in `spawn`

Read it from the bottom up. spawn requires its closure to be Send. The closure captures a Store, so Store must be Send. And Store holds an Rc, which isn’t. The error points at the field’s type, deep inside our own struct, which is exactly where the fix goes.

Rc‘s count isn’t safe to change from two threads, and neither is RefCell‘s borrow flag. Swap each for its thread-safe partner: Arc for Rc, and Mutex for RefCell. The only other change is borrow_mut() becoming lock().unwrap(). That’s exactly the Store from Step 2, which four worker threads share in every test of Step 7.

Worked example: the worker that kept the lock

Here’s a worker loop that looks tidier than ours:

while let Ok(stream) = receiver.lock().unwrap().recv() {
    serve(stream, &store);
}

It compiles, has no warnings, and handles one client at a time correctly. But with two clients connected at once, the second one gets no reply until the first one hangs up. The reason is where the guard is dropped. In a while let, temporaries in the condition live until the end of the loop body. So the worker holds the receiver’s lock for the whole of serve. Every other worker waits in lock(), and nobody takes the next connection.

We can see it without any sockets. try_lock asks for the lock without waiting, and tells us whether someone else holds it:

use std::sync::Mutex;
use std::sync::mpsc::{self, Receiver};

fn queue(jobs: &[&'static str]) -> Mutex<Receiver<&'static str>> {
    let (tx, rx) = mpsc::channel();
    for job in jobs {
        tx.send(*job).unwrap();
    }
    Mutex::new(rx)
}

fn main() {
    let rx = queue(&["job 1", "job 2"]);
    println!("while let:");
    while let Ok(job) = rx.lock().unwrap().recv() {
        let free = rx.try_lock().is_ok();
        println!("  doing {job}, could another worker get the lock? {free}");
    }

    let rx = queue(&["job 1", "job 2"]);
    println!("loop with a let statement:");
    loop {
        let next = rx.lock().unwrap().recv();
        let Ok(job) = next else { break };
        let free = rx.try_lock().is_ok();
        println!("  doing {job}, could another worker get the lock? {free}");
    }
}

It prints:

while let:
  doing job 1, could another worker get the lock? false
  doing job 2, could another worker get the lock? false
loop with a let statement:
  doing job 1, could another worker get the lock? true
  doing job 2, could another worker get the lock? true

queue sends the jobs and then drops its Sender as it returns, so recv returns Err after the last job and both loops end. In the first loop, the lock is still held while each job runs. In the second, let next = ...; is a whole statement, so the guard is dropped at its semicolon, before the job runs.

The Rust 2024 edition changed this rule for if let: there, temporaries are now dropped before the else branch. It didn’t change while let. This program was built with edition 2024, and the lock is still held.

run-checks.sh checks this on the real server too. It puts the while let into a copy of server.rs, runs the test with two clients, and expects it to hang until a 20-second timeout stops it.

What we used from each part

Part Where it shows up
5 Strings std::str::from_utf8 checks a line before we parse it
6 Ownership each TcpStream is moved: acceptor, channel, then one worker
7 Borrowing serve and respond borrow the Store and the line
10 Structs Store, Server and Client, with &self and self methods
11 Enums Command and Reply, match, let else
12 Errors ParseError with Display, io::Result and ? everywhere
13 Collections the HashMap inside the store
14 Traits Display, FromStr, and derive for Clone, Default, PartialEq
16 Closures move closures for every thread
17 Iterators listener.incoming(), and map / collect in the tests
18 Modules lib.rs, four modules, pub use, and main.rs as a second crate
19 Testing unit, integration and doc tests
20 Smart pointers why Rc and RefCell can’t be the store
22 Advanced traits type Err in FromStr, an associated type
23 Threads spawn, JoinHandle, Send and Sync
24 Shared state Arc, Mutex, mpsc, AtomicBool, the lock held too long
25 Lifetimes, part 2 &'static str in ParseError, and spawn‘s 'static bound

Tips and traps

  • A lock held across I/O. A guard that lives through a network read or write makes every other thread wait for a slow client. It shows up as a server that works with one client and stalls with two. Keep each lock to one short operation, and return copies, as Store::get does.
  • while let keeps the guard. while let Ok(x) = m.lock().unwrap().recv() holds the lock for the whole body. Nothing warns you. Take the value in its own let statement first, as our worker does.
  • unwrap on client data. A panic in a worker kills that worker. Our pool doesn’t replace it, so four panics would leave a server that accepts connections and never answers. Turn client mistakes into ERR replies, and keep unwrap for things that are bugs if they fail, such as a poisoned lock.
  • lines() on a socket. It ends the session at the first line that isn’t UTF-8. Read bytes with read_until and decide for yourself, as respond does.
  • A fixed port in tests. Two tests that bind port 7878 can’t run at once, and the second fails with “address in use”. Bind port 0 and ask local_addr for the real port.
  • sleep in a network test. “Wait 100 ms and the server will have finished” is true on your machine and false on a busy CI runner. Wait for something the server does instead, as the half-line test waits for the server to close its end.
  • No limit on line length. A client that sends gigabytes with no newline makes read_until grow its buffer until memory runs out. Exercise 1 caps it.

Parse at the edge, share behind one small lock, and make every client mistake a reply instead of a panic.

Exercises

Exercise 1. serve will read a line of any length. Write a function that reads one line of at most 16 bytes, newline included, using Read::take. It should say whether it got a whole line, a line that was too long, or the end of the stream. Try it on an in-memory input: a &[u8] implements BufRead, so you don’t need a socket.

Exercise 2. Rewrite Store with an RwLock instead of a Mutex. Which methods take read(), and which take write()? Show that two readers can hold the lock at once.

Exercise 3. A friend adds INCR key, which adds 1 to a number stored at key (a missing key counts as 0), like this:

let n: i64 = store.get(key).unwrap_or("0".to_string()).parse()?;
store.set(key.to_string(), (n + 1).to_string());

Four clients each send INCR hits 1000 times. Every call to get and set takes the lock, so is the final count always 4000? If not, write an incr method on Store that is.

Answers

1. take(16) makes a reader that stops after 16 bytes, so read_until can’t read more than that. Then the three cases are: the line ends in \n (a whole line); we got fewer than 16 bytes and no \n (the stream ended); or we got all 16 and still no \n (too long).

use std::io::{self, BufRead, Read};

const MAX_LINE: u64 = 16;

#[derive(Debug)]
enum Line {
    Whole,
    TooLong,
    End,
}

fn read_limited(reader: &mut impl BufRead, line: &mut Vec<u8>) -> io::Result<Line> {
    line.clear();
    let n = reader.by_ref().take(MAX_LINE).read_until(b'\n', line)?;
    if line.last() == Some(&b'\n') {
        Ok(Line::Whole)
    } else if (n as u64) < MAX_LINE {
        Ok(Line::End)
    } else {
        Ok(Line::TooLong)
    }
}

fn main() -> io::Result<()> {
    let inputs: [&[u8]; 2] = [b"GET a\nSET name a-very-long-name\n", b"GET a\nGET b"];
    for mut input in inputs {
        let mut line = Vec::new();
        loop {
            let kind = read_limited(&mut input, &mut line)?;
            println!("{kind:?}: {:?}", String::from_utf8_lossy(&line));
            if !matches!(kind, Line::Whole) {
                break;
            }
        }
    }
    Ok(())
}

It prints:

Whole: "GET a\n"
TooLong: "SET name a-very-"
Whole: "GET a\n"
End: "GET b"

In the server, TooLong would send ERR line too long and close the connection, because the rest of that line is still unread. End is the half line from Step 4. by_ref() lets take borrow the reader instead of taking ownership of it, so we can call read_limited again on the same input.

2. get and len only read, so they take read(). set and del change the map, so they take write(). Nothing else changes, because the lock is private to Store.

use std::collections::HashMap;
use std::sync::{Arc, RwLock};

#[derive(Clone, Default)]
struct Store {
    map: Arc<RwLock<HashMap<String, String>>>,
}

impl Store {
    fn set(&self, key: String, value: String) -> Option<String> {
        self.map.write().unwrap().insert(key, value)
    }

    fn get(&self, key: &str) -> Option<String> {
        self.map.read().unwrap().get(key).cloned()
    }

    fn del(&self, key: &str) -> bool {
        self.map.write().unwrap().remove(key).is_some()
    }

    fn len(&self) -> usize {
        self.map.read().unwrap().len()
    }
}

fn main() {
    let store = Store::default();
    store.set("name".into(), "Ana".into());
    store.set("city".into(), "Porto".into());
    println!("del city: {}", store.del("city"));

    let r1 = store.map.read().unwrap();
    let r2 = store.map.read().unwrap();
    println!("two readers at once: {} and {} keys", r1.len(), r2.len());
    println!("can a writer get in? {}", store.map.try_write().is_ok());
    drop(r1);
    drop(r2);

    println!("get name: {:?}, len: {}", store.get("name"), store.len());
}

It prints:

del city: true
two readers at once: 1 and 1 keys
can a writer get in? false
get name: Some("Ana"), len: 1

Whether this is faster for our server is a question for a benchmark, not for reasoning. With locks this short, it may not be.

3. No. Each call is safe on its own, but the pair isn’t. Two clients can both get 41, both add 1, and both set 42: two increments, one counted. This is a lost update, and the locks don’t prevent it, because the lock is let go between the get and the set. The fix is to read, change and write under one guard:

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;

#[derive(Clone, Default)]
struct Store {
    map: Arc<Mutex<HashMap<String, String>>>,
}

impl Store {
    fn set(&self, key: &str, value: &str) {
        self.map
            .lock()
            .unwrap()
            .insert(key.to_string(), value.to_string());
    }

    /// Adds 1 to the number at `key`, under one lock, and returns it.
    fn incr(&self, key: &str) -> Result<i64, String> {
        let mut map = self.map.lock().unwrap();
        let value = map.entry(key.to_string()).or_insert("0".to_string());
        let n: i64 = value
            .parse()
            .map_err(|_| format!("{key} is not a number"))?;
        let n = n.checked_add(1).ok_or("number too big")?;
        *value = n.to_string();
        Ok(n)
    }
}

fn main() {
    let store = Store::default();
    let clients: Vec<_> = (0..4)
        .map(|_| {
            let store = store.clone();
            thread::spawn(move || {
                for _ in 0..1000 {
                    store.incr("hits").unwrap();
                }
            })
        })
        .collect();
    for c in clients {
        c.join().unwrap();
    }
    println!("hits: {:?}", store.incr("hits"));

    store.set("name", "Ana");
    println!("name: {:?}", store.incr("name"));
}

It prints:

hits: Ok(4001)
name: Err("name is not a number")

The last incr adds the 4001st hit, so 4000 came from the four threads, every run. The entry API (Part 13) puts "0" in for a missing key. checked_add (Part 2) turns an overflow into an error instead of a panic. ? turns the &str error from ok_or into a String, because String implements From<&str>. In the server, both errors would become ERR replies.

Where to go next

This server is a starting point, and each of its limits is a direction to take it:

  • Async. Our pool has four threads, so a fifth client waits. Part 26 showed how async code serves many waiting connections on a few threads. With tokio, TcpListener::accept and read_line become .await calls, a tokio::spawn per connection replaces the pool, and tokio::sync::Mutex or a plain std::sync::Mutex guards the map. The protocol and store modules wouldn’t change at all.
  • Persistence. Everything is lost when the process stops. The simplest fix is an append-only log: write each SET and DEL to a file before replying, and replay the file at start-up. Redis’s append-only file (AOF) is built on the same idea.
  • A real protocol. Our values can’t contain a newline, and keys can’t contain a space. Real protocols send a length before each value. Redis’s RESP is a readable example. For structured data, serde is the standard crate; we didn’t use it here, because the series uses only the standard library.
  • Limits and timeouts. Cap the line length (Exercise 1), and use TcpStream::set_read_timeout so a client that connects and says nothing can’t keep a worker forever.

That’s the end of the series. You’ve gone from cargo new to a threaded server with tests, and every program on the way was run. The best next step is to pick one item from the list above and build it.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.