---
title: "Project: A Key-Value Server"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 31
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/31-project-a-key-value-server
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 31 — Project: A Key-Value Server

The server of this chapter listens on `127.0.0.1:44310` and keeps a map from string keys to string values. It speaks a line-based text protocol: a client sends `SET k v`, `GET k`, `DEL k`, `COUNT` or `QUIT`, one per line, and receives one line for each, `OK`, `VALUE v`, `NOTFOUND`, `COUNT n` or `ERR` followed by a reason. It serves many clients at once, it survives a restart by replaying an [append-only log](#def-b2-project-key-value-server-log), and it is measured under a [load test](#def-b2-project-key-value-server-load-test). It is written in Rust with the standard library only, in six milestones, each with its code, its output and its tests; the Year 3 volume will make the same server survive the loss of a machine.

**You already know.**

[Ownership](https://one-course.com/books/computer-science/4/en/chapter/6-rust-ownership-and-borrowing#def-b2-rust-ownership-ownership), borrowing and lifetimes ([Chapter 6](https://one-course.com/books/computer-science/4/en/chapter/6-rust-ownership-and-borrowing#ch-b2-rust-ownership)); `Result` and the `?` operator ([Chapter 7](https://one-course.com/books/computer-science/4/en/chapter/7-enums-pattern-matching-and-error-handling#ch-b2-rust-enums-and-errors)); [traits](https://one-course.com/books/computer-science/4/en/chapter/8-traits-and-generics#def-b2-rust-traits-and-generics-trait) and [trait objects](https://one-course.com/books/computer-science/4/en/chapter/8-traits-and-generics#def-b2-rust-traits-and-generics-trait-object) ([Chapter 8](https://one-course.com/books/computer-science/4/en/chapter/8-traits-and-generics#ch-b2-rust-traits-and-generics)). [Threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread), mutexes, reader–writer [locks](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock), and the lock-order rule that prevents deadlock ([Proposition 15.18](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#prop-b2-threads-and-synchronisation-order)). A [TCP connection](https://one-course.com/books/computer-science/4/en/chapter/19-the-transport-layer-udp-and-tcp#def-b2-transport-layer-tcp) carries a stream of bytes with no message boundaries, so a protocol must frame its messages ([Section 16.3](https://one-course.com/books/computer-science/4/en/chapter/16-sockets#sec-b2-sockets-framing), [Section 19.3](https://one-course.com/books/computer-science/4/en/chapter/19-the-transport-layer-udp-and-tcp#sec-b2-transport-layer-tcp)). The CRC-32 detects every [burst](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#def-b2-link-layer-burst) of errors up to 32 bits long ([Theorem 17.9](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#thm-b2-link-layer-crc-burst)). The Year 1 volume: hash tables, whose operations take expected constant time.

**Definition 31.1 (Key–value store).**

A *key–value store* is a service that keeps a finite map from keys to values and offers three operations on it: set the value of a key, get the value of a key, and delete a key. It offers no query over the values, no join and no schema: a client that needs them builds them from keys.

![The server’s architecture at the end of milestone 4. The listener accepts connections and puts them in a queue; a fixed set of workers take them, one each, and answer the requests. A request locks the one shard that holds its key; a change is appended to the log under that shard’s lock.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-project-key-value-server/fig-840ffdd4d5a0.svg)

*The server’s architecture at the end of milestone 4. The listener accepts connections and puts them in a queue; a fixed set of workers take them, one each, and answer the requests. A request [locks](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) the one shard that holds its key; a change is appended to the log under that shard’s [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock).*

## 31.1 Milestone 1: the protocol

A request is one line of text; the parser turns it into a value of an enum, or into the reason it is not one. Keys and values are words without spaces, so the arguments are the words of the line.

```rust
pub const MAX_LINE: usize = 1024;

/// One line, without its newline, to a command, or the reason it is not one.
pub fn parse(line: &str) -> Result<Command, String> {
    if line.len() > MAX_LINE {
        return Err(format!("line longer than {MAX_LINE} bytes"));
    }
    let (word, rest) = line.split_once(' ').unwrap_or((line, ""));
    let args: Vec<&str> = rest.split(' ').filter(|a| !a.is_empty()).collect();
    match (word, args.as_slice()) {
        ("", _) => Err("empty line".to_string()),
        ("SET", [key, value]) => Ok(Command::Set(key.to_string(), value.to_string())),
        ("GET", [key]) => Ok(Command::Get(key.to_string())),
        ("DEL", [key]) => Ok(Command::Del(key.to_string())),
        ("COUNT", []) => Ok(Command::Count),
        ("QUIT", []) => Ok(Command::Quit),
        ("SET", _) => Err("SET takes a key and a value".to_string()),
        ("GET" | "DEL", _) => Err(format!("{word} takes one key")),
        ("COUNT" | "QUIT", _) => Err(format!("{word} takes no argument")),
        _ => Err(format!("unknown command {word}")),
    }
}
```

***Listing 31.1.** The parser: one line to a `Command`, or the reason in an `Err` code/bachelor-2/31-project-key-value-server/listings/protocol.rs*

The match on the pair (first word, list of arguments) lists the valid forms first, then one error per command with the wrong number of arguments; the last arm catches every unknown word, lower-case ones included. The enums `Command` and `Reply` implement `Display`, so that a reply is printed by `writeln!` as it is, and a command is written back as the line it came from: the log of milestone 4 will store commands that way. The unit tests check every command and eleven malformed lines covering every error reason, and one line that is too long, and that printing a thousand random commands and parsing them gives the same commands back.

## 31.2 Milestone 2: one client at a time

A connection is a stream of bytes. The server reads it through a buffer, up to the next newline, so that a request split over two TCP segments, or two requests in one segment, are both handled: the framing is the newline. A line longer than the limit, or a stream that ends in the middle of a line, cannot be resynchronised, and the connection is closed after one `ERR`.

```rust
/// Read lines until QUIT or end of stream; answer each with one line.
pub fn handle(stream: TcpStream, shared: &Shared) -> io::Result<()> {
    let mut reader = BufReader::new(stream.try_clone()?);
    let mut writer = BufWriter::new(stream);
    let mut line = Vec::new();
    loop {
        line.clear();
        let limit = MAX_LINE as u64 + 2; // the line, "\r" and "\n"
        let n = (&mut reader).take(limit).read_until(b'\n', &mut line)?;
        if n == 0 {
            return Ok(()); // the client closed the connection
        }
        if line.last() != Some(&b'\n') {
            let reason = if n as u64 == limit { "line too long" } else { "no newline" };
            writeln!(writer, "{}", Reply::Err(reason.to_string()))?;
            return writer.flush(); // the stream cannot be resynchronised: close it
        }
        let text = String::from_utf8_lossy(&line);
        let cmd = parse(text.trim_end_matches(['\r', '\n']));
        let reply = match &cmd {
            Ok(cmd) => shared.store.apply(cmd, shared.log.as_ref()),
            Err(reason) => Reply::Err(reason.clone()),
        };
        writeln!(writer, "{reply}")?;
        if cmd == Ok(Command::Quit) {
            return writer.flush();
        }
        if reader.buffer().is_empty() {
            writer.flush()?; // no request waiting: send the replies now
        }
    }
}
```

***Listing 31.2.** One connection: read a line, parse it, apply it, answer it code/bachelor-2/31-project-key-value-server/listings/server.rs*

The replies go through a `BufWriter` and are flushed when no request is waiting in the reader’s buffer: one `write` for a burst of requests, and no reply left waiting while the client waits for it. The simplest server calls `handle` for each accepted connection in turn:

```rust
/// A failed accept (a client gone before it was accepted, no descriptor left) costs one
/// client, not the server: report it and go on.
fn accepted(stream: io::Result<TcpStream>) -> Option<TcpStream> {
    stream.map_err(|e| eprintln!("accept: {e}")).ok()
}

/// M2: one connection at a time; the next client waits for the previous one.
pub fn serve_one_at_a_time(listener: TcpListener, shared: Arc<Shared>) -> io::Result<()> {
    for stream in listener.incoming().filter_map(accepted) {
        let _ = handle(stream, &shared);
    }
    Ok(())
}
```

***Listing 31.3.** Milestone 2: one connection at a time code/bachelor-2/31-project-key-value-server/listings/server.rs*

`accepted` keeps the server running when one `accept` fails, as it does when a client resets its connection before the server takes it, or when no [file descriptor](https://one-course.com/books/computer-science/4/en/chapter/14-files-pipes-and-signals#def-b2-files-pipes-signals-descriptor) is left under load: writing `stream?` instead would end the whole server on the first such error, and in the pool below it would also close the queue and send every worker home.

The client of `client.rs` connects (retrying while the server starts), sends a line and reads one line back. The demonstration program starts the server of the next milestones in a [thread](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) of its own [process](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process), runs a scripted session against it, and reads the log back:

```rust
fn main() -> std::io::Result<()> {
    let (log, map, recovery) = Log::open(Path::new("kv.log"), Flush::EveryRecord)?;
    println!("started with {} keys from {} records", map.len(), recovery.records);
    let shared = Arc::new(Shared {
        store: Box::new(store::Sharded::new(16, map)),
        log: Some(Mutex::new(log)),
    });
    let listener = TcpListener::bind("127.0.0.1:44310")?;
    thread::spawn(move || server::serve_pool(listener, shared, 4));
```

***Listing 31.4.** The demonstration: open the log, build the store from it, serve on port 44310 code/bachelor-2/31-project-key-value-server/listings/demo.rs*

```
$ rustc --edition 2021 -O -o demo demo.rs && ./demo
started with 0 keys from 0 records
> SET loan:3 out             < OK
> SET member:55 Garden-Lane  < OK
> GET loan:3                 < VALUE out
> GET loan:4                 < NOTFOUND
> SET loan:3 returned        < OK
> GET loan:3                 < VALUE returned
> DEL loan:4                 < NOTFOUND
> DEL member:55              < OK
> COUNT                      < COUNT 1
> get loan:3                 < ERR unknown command get
> SET loan:5                 < ERR SET takes a key and a value
> COUNT now                  < ERR COUNT takes no argument
>                            < ERR empty line
> QUIT                       < OK
the log: 4 records, 103 bytes; replayed: [("loan:3", "returned")]
```

***Output 31.1.** A scripted session, then the log read back: four records, one key.*

Two `SET`s, one more that replaces a value, and one `DEL` that removes a key: four records, since a `DEL` of a missing key changes nothing and is not logged. Their [replay](#def-b2-project-key-value-server-log) leaves one key. With one connection at a time, a second client waits until the first sends `QUIT`: a client that connects and stays idle stops the server for everybody.

## 31.3 Milestone 3: many clients

The first remedy gives every connection a [thread](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) of its own:

```rust
/// M3: a new thread for every connection.
pub fn serve_thread_per_connection(listener: TcpListener, shared: Arc<Shared>)
    -> io::Result<()> {
    for stream in listener.incoming().filter_map(accepted) {
        let shared = Arc::clone(&shared);
        thread::spawn(move || handle(stream, &shared));
    }
    Ok(())
}
```

***Listing 31.5.** A [thread](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) per connection code/bachelor-2/31-project-key-value-server/listings/server.rs*

The compiler checks the sharing: the closure moves an `Arc<Shared>` into the [thread](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread), and `Shared` holds a `Box<dyn Store>` whose [trait](https://one-course.com/books/computer-science/4/en/chapter/8-traits-and-generics#def-b2-rust-traits-and-generics-trait) requires `Send + Sync`, so a store that could not be shared safely between [threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) would not compile. A [thread](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) per connection costs a stack and a creation per client, and nothing bounds the number of [threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread): ten thousand clients make ten thousand [threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread).

**Definition 31.2 (Thread pool).**

A *thread pool* is a fixed set of [threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread), the *workers*, that take tasks from a shared queue and run them one after another. Submitting a task puts it in the queue; no [thread](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) is created per task.

```rust
/// M3: a fixed pool of workers takes the connections from one queue.
pub fn serve_pool(listener: TcpListener, shared: Arc<Shared>, workers: usize)
    -> io::Result<()> {
    let (queue, jobs) = mpsc::channel::<TcpStream>();
    let jobs = Arc::new(Mutex::new(jobs));
    for _ in 0..workers {
        let (jobs, shared) = (Arc::clone(&jobs), Arc::clone(&shared));
        thread::spawn(move || loop {
            let next = jobs.lock().unwrap().recv(); // the guard is dropped here
            match next {
                Ok(stream) => {
                    let _ = handle(stream, &shared);
                }
                Err(_) => return, // the queue is closed
            }
        });
    }
    for stream in listener.incoming().filter_map(accepted) {
        queue.send(stream).expect("a worker is alive");
    }
    Ok(())
}
```

***Listing 31.6.** A pool of workers fed by one channel code/bachelor-2/31-project-key-value-server/listings/server.rs*

The receiving end of the channel is behind a mutex, since one worker at a time may take from it; the guard is a temporary of the statement that calls `recv`, so the [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) is released before the connection is handled, not after. Here a task is a whole connection, so a pool of $w$ workers serves $w$ clients at once and the others wait in the queue: the pool bounds the resources, at the price of the idle-client problem for the $(w + 1)$-th client. An [event loop](https://one-course.com/books/computer-science/4/en/chapter/16-sockets#def-b2-sockets-event-loop) ([Definition 16.12](https://one-course.com/books/computer-science/4/en/chapter/16-sockets#def-b2-sockets-event-loop)) serves any number of idle clients with one [thread](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread); the Year 3 volume returns to it.

The store itself must be shared. The first version puts the whole map behind one `Mutex`; every request, from every worker, takes that one [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock).

```rust
/// What every store does; Send + Sync so that threads can share it.
pub trait Store: Send + Sync {
    /// Run one command; a SET or DEL is appended to the log, if any, under the
    /// same lock as the change, so that the log order is the order of changes.
    fn apply(&self, cmd: &Command, log: Option<&Mutex<Log>>) -> Reply;
    /// Rewrite the log as one SET per key, no write allowed meanwhile.
    fn compact(&self, log: &Mutex<Log>) -> io::Result<u64>;
}

/// SET or DEL on a map the caller has locked: log first, then change.
pub fn write(map: &mut Map, cmd: &Command, log: Option<&Mutex<Log>>) -> Reply {
    if let Command::Del(k) = cmd {
        if !map.contains_key(k) {
            return Reply::NotFound; // nothing changes: nothing to log
        }
    }
    if let Some(log) = log {
        if log.lock().unwrap().append(cmd).is_err() {
            return Reply::Err("log write failed".to_string());
        }
    }
    match cmd {
        Command::Set(k, v) => {
            map.insert(k.clone(), v.clone());
            Reply::Ok
        }
        Command::Del(k) => {
            map.remove(k);
            Reply::Ok
        }
        _ => unreachable!("write is called for SET and DEL only"),
    }
}
```

***Listing 31.7.** The store’s [trait](https://one-course.com/books/computer-science/4/en/chapter/8-traits-and-generics#def-b2-rust-traits-and-generics-trait), and a change made under a [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) the caller holds code/bachelor-2/31-project-key-value-server/listings/store.rs*

**Definition 31.3 (Sharding, lock striping).**

*Sharding* splits a map into $N$ parts, the *shards*, and puts each key in the shard numbered by a hash of the key modulo $N$. With one [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) per shard, *lock striping*, two requests on keys of different shards proceed in parallel.

```rust
impl Store for Sharded {
    fn apply(&self, cmd: &Command, log: Option<&Mutex<Log>>) -> Reply {
        match cmd {
            Command::Get(k) => read(&self.shard(k).read().unwrap(), k),
            Command::Set(k, _) | Command::Del(k) => {
                write(&mut self.shard(k).write().unwrap(), cmd, log)
            }
            // The shards are read in increasing order, one at a time.
            Command::Count => {
                Reply::Count(self.shards.iter().map(|s| s.read().unwrap().len()).sum())
            }
            Command::Quit => Reply::Ok,
        }
    }
```

***Listing 31.8.** The sharded store: a read [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) for `GET`, a write [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) for `SET` and `DEL` code/bachelor-2/31-project-key-value-server/listings/store.rs*

Each shard is behind a reader–writer [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock), so that many `GET`s on one shard also proceed together. `COUNT` takes the [shards](#def-b2-project-key-value-server-shard)’ read [locks](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) one at a time; its answer is a sum of counts taken at slightly different instants, which is the exact count at no single instant if writes happen meanwhile ([Exercise 31.5](#exo-b2-project-key-value-server-5) looks at what an unlocked client sees). Compaction, in the next milestone, holds every shard and then the log: several [locks](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) at once.

**Proposition 31.4 (Lock order).**

Number the [locks](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock): shard $i$ is [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) $i$ for $0 \le i < N$, and the log is [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) $N$. If every operation that holds several of them acquired them in increasing order, as `SET`, `DEL`, compaction and the `MSET` of [Exercise 31.10](#exo-b2-project-key-value-server-10) do, the server cannot deadlock.

**Proof.** A `SET` or `DEL` takes one shard [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock), then the log: increasing. `COUNT` holds one [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) at a time. Compaction takes the [shards](#def-b2-project-key-value-server-shard) in the order $0, 1, \dots, N-1$, then the log. By [Proposition 15.18](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#prop-b2-threads-and-synchronisation-order), a set of [threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) waiting for each other would form a circle, in which each [thread](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) holds a [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) with a smaller number than the one it waits for; following the circle, the numbers would increase strictly all the way round and come back to the first one, which is impossible. ∎

[Exercise 31.6](#exo-b2-project-key-value-server-6) shows the deadlock that two `MSET`s produce when each takes the [locks](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) in the order of its own keys.

## 31.4 Milestone 4: persistence

A map in memory disappears with the [process](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process). The server writes every change to a file before it applies it, and rebuilds the map from that file when it starts.

**Definition 31.5 (Append-only log, replay, compaction).**

An *append-only log* is a file to which records are only ever added at the end. To *replay* a log of changes is to apply its records in order to an empty state. To *compact* it is to replace it by a shorter log whose replay gives the same state.

A record must be found again even if the file ends in the middle of one, so it is framed by its length, and checked by its CRC-32:

![The record of SET a 1, byte by byte: four bytes of length, four of CRC, then the command as it is printed. A record is 8 bytes longer than its command.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-project-key-value-server/fig-1818bd8ff816.svg)

*The record of `SET a 1`, byte by byte: four bytes of length, four of CRC, then the command as it is printed. A record is 8 bytes longer than its command.*

```rust
/// Rebuild the map from the bytes of a log; stop at the first record that is
/// short, fails its CRC or does not parse, and drop everything from there.
pub fn replay(bytes: &[u8]) -> (Map, Recovery) {
    let mut map = Map::new();
    let (mut at, mut records) = (0usize, 0usize);
    while let Some((cmd, size)) = next_record(&bytes[at..]) {
        match &cmd {
            Command::Set(k, v) => map.insert(k.clone(), v.clone()),
            Command::Del(k) => map.remove(k),
            _ => unreachable!("next_record returns SET and DEL only"),
        };
        at += size;
        records += 1;
    }
    let dropped = (bytes.len() - at) as u64;
    (map, Recovery { records, kept_bytes: at as u64, dropped_bytes: dropped })
}

fn next_record(b: &[u8]) -> Option<(Command, usize)> {
    let len = u32::from_le_bytes(b.get(0..4)?.try_into().ok()?) as usize;
    let crc = u32::from_le_bytes(b.get(4..8)?.try_into().ok()?);
    let payload = b.get(8..8 + len.min(MAX_LINE + 1))?;
    if payload.len() != len || crc32(payload) != crc {
        return None;
    }
    match parse(std::str::from_utf8(payload).ok()?) {
        Ok(cmd @ (Command::Set(..) | Command::Del(_))) => Some((cmd, 8 + len)),
        _ => None, // a zeroed tail has len 0 and the CRC of nothing, 0: it fails here
    }
}
```

***Listing 31.9.** [Replay](#def-b2-project-key-value-server-log): apply each complete record, stop at the first one that is short, damaged or not a change code/bachelor-2/31-project-key-value-server/listings/log.rs*

The CRC alone would not be enough. A file system may leave zeros at the end of a file after a crash, and four bytes of length 0 followed by four bytes of CRC 0 form a valid frame, since the CRC-32 of no bytes is 0. The parser catches it: an empty line is not a command.

```rust
impl Log {
    /// Replay the log at path, cut off a torn tail, and open it for appending.
    pub fn open(path: &Path, policy: Flush) -> io::Result<(Log, Map, Recovery)> {
        let bytes = fs::read(path).or_else(|e| match e.kind() {
            io::ErrorKind::NotFound => Ok(Vec::new()),
            _ => Err(e),
        })?;
        let (map, recovery) = replay(&bytes);
        let file = OpenOptions::new().create(true).append(true).open(path)?;
        file.set_len(recovery.kept_bytes)?;
        file.sync_all()?;
        Ok((Log { path: path.to_path_buf(), file, policy }, map, recovery))
    }

    pub fn append(&mut self, cmd: &Command) -> io::Result<()> {
        self.file.write_all(&record(cmd))?;
        if self.policy == Flush::EveryRecord {
            self.file.sync_data()?;
        }
        Ok(())
    }
```

***Listing 31.10.** Open: [replay](#def-b2-project-key-value-server-log), cut off the torn tail, append from there code/bachelor-2/31-project-key-value-server/listings/log.rs*

Cutting the tail off matters: without it, the next record would be appended after the torn bytes, and the following [replay](#def-b2-project-key-value-server-log) would stop at the torn bytes and lose the new record too. The policy decides when `OK` is sent: after `sync_data`, the record is on the disk; without it, it is in the operating system’s memory and lost if the machine loses power, though not if only the server crashes.

```rust
fn main() -> std::io::Result<()> {
    let path = Path::new("kv.log");
    let (mut log, _, _) = Log::open(path, Flush::EveryRecord)?;
    for (k, v) in [("a", "1"), ("b", "2"), ("a", "3")] {
        log.append(&set(k, v))?;
    }
    drop(log);
    println!("three records: {} bytes", fs::metadata(path)?.len());

    // The crash: only the first 11 of the 4th record's 15 bytes reached the file.
    let torn = record(&set("c", "4"));
    OpenOptions::new().append(true).open(path)?.write_all(&torn[..11])?;
    restart(path, "torn last record:")?;
    println!("after the restart the file has {} bytes again", fs::metadata(path)?.len());

    // A file system may leave zeros after a crash: len 0 and CRC 0 look valid.
    OpenOptions::new().append(true).open(path)?.write_all(&[0u8; 16])?;
    restart(path, "zeroed tail:")?;

    // A bit flipped in the value of the 2nd record: its CRC no longer matches.
    let mut bytes = fs::read(path)?;
    bytes[15 + 14] ^= 0x01;
    fs::write(path, &bytes)?;
    restart(path, "flipped bit in record 2:")?;
    Ok(())
}
```

***Listing 31.11.** Three damaged logs, made by hand code/bachelor-2/31-project-key-value-server/listings/crash_demo.rs*

```
$ rustc --edition 2021 -O -o crash_demo crash_demo.rs && ./crash_demo
three records: 45 bytes
torn last record:          3 records kept, 11 bytes dropped: [("a", "3"), ("b", "2")]
after the restart the file has 45 bytes again
zeroed tail:               3 records kept, 16 bytes dropped: [("a", "3"), ("b", "2")]
flipped bit in record 2:   1 record kept, 30 bytes dropped: [("a", "1")]
```

***Output 31.2.** Each restart keeps the longest prefix of complete, undamaged records.*

![A crash in the middle of an append. The restart replays the three complete records, cuts the file after them, and the next change is appended there.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-project-key-value-server/fig-9e1f07eff9db.svg)

*A crash in the middle of an append. The restart [replays](#def-b2-project-key-value-server-log) the three complete records, cuts the file after them, and the next change is appended there.*

**Proposition 31.6 (Replay).**

Let a log hold the records $r_1, \dots, r_n$ followed by any bytes that do not begin with a complete, undamaged record. Its [replay](#def-b2-project-key-value-server-log) is the map obtained by applying $r_1, \dots, r_n$ in order to the empty map, which is the map the server held after its $n$-th change.

**Proof.** [Exercise 31.8](#exo-b2-project-key-value-server-8), by induction on $n$. ∎

The proposition assumes that the damage is at the end. A flipped bit in the middle of the log, as in the third case of [Output 31.2](#out-b2-project-key-value-server-crash), also stops the [replay](#def-b2-project-key-value-server-log), and the intact records after it are dropped with it: a crash cannot cause that, a failing disk can, and the honest behaviour is to report it. A crash damages only the end because the log is only appended to: whatever a crash interrupts is the record being appended, the last one, since the records before it were complete before it began. POSIX does not promise that a `write` cut short by a signal is all or nothing, so a killed [process](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process) may leave that last record short, and so may the machine stopping between the operating system’s memory and the disk; the [replay](#def-b2-project-key-value-server-log) stops there and `open` cuts it. The kill test of the next milestone checks this on real runs.

The log grows with every change, even when the map does not: a thousand `SET`s of one key leave a thousand records for one value. Compaction rewrites it:

```rust
    /// Compaction: write one SET per key, sorted, to a new file, make it durable,
    /// and rename it over the log; a crash leaves either the old log or the new one.
    pub fn rewrite(&mut self, maps: &[&Map]) -> io::Result<u64> {
        let mut entries: Vec<(&String, &String)> =
            maps.iter().flat_map(|m| m.iter()).collect();
        entries.sort();
        let tmp = self.path.with_extension("compacting");
        let mut out = File::create(&tmp)?;
        let mut size = 0u64;
        for (k, v) in entries {
            let rec = record(&Command::Set(k.clone(), v.clone()));
            out.write_all(&rec)?;
            size += rec.len() as u64;
        }
        out.sync_all()?;
        fs::rename(&tmp, &self.path)?;
        let dir = self.path.parent().filter(|d| !d.as_os_str().is_empty());
        File::open(dir.unwrap_or(Path::new(".")))?.sync_all()?; // the rename itself
        self.file = OpenOptions::new().append(true).open(&self.path)?;
        Ok(size)
    }
```

***Listing 31.12.** Compaction: a new file, made durable, renamed over the old one code/bachelor-2/31-project-key-value-server/listings/log.rs*

**Proposition 31.7 (Compaction).**

If no change happens during the rewrite, the compacted [log replays](#def-b2-project-key-value-server-log) to the same map as the log it replaces.

**Proof.** The compacted log holds one `SET k v` for each pair of the map $M$, in sorted order, and no `DEL`. Replaying it inserts each pair once into an empty map, and no two records have the same key, so the order does not matter and the result is $M$. By [Proposition 31.6](#prop-b2-project-key-value-server-replay), the old [log replays](#def-b2-project-key-value-server-log) to the map held after its last change, which is $M$, since no change happens during the rewrite: the store’s `compact` holds every shard’s [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) until the new log is in place. ∎

The rename is what makes compaction safe against a crash: `rename` replaces the old name by the new file at once, so a crash leaves either the old log or the new one, never half of each; syncing the directory makes the rename itself durable.

## 31.5 Milestone 5: the load test

**Definition 31.8 (Load test, latency percentile).**

A *load test* runs a fixed, reproducible workload of requests against a system and measures its *throughput*, the requests completed per second, and the latency of each request. The *$p$-th latency percentile* is the latency below which a fraction $p$ of the requests fall: $p_{50}$ is the median, $p_{99}$ the latency that one request in a hundred exceeds.

The workload is seeded: each client draws its requests from a generator started at its own number, nine `GET`s for one `SET` over a thousand keys. It is run twice, once against the store directly from [threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) of the same [process](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process), to measure the [locks](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) alone, and once through TCP:

```rust
fn over_tcp(addr: &str, clients: u64, requests: u64) -> (f64, f64, f64) {
    let start = Instant::now();
    let workers: Vec<_> = (0..clients).map(|t| {
        let addr = addr.to_string();
        thread::spawn(move || {
            let (mut rng, mut c) = (Lcg(t + 1), client::Client::connect(&addr).unwrap());
            let mut times = Vec::with_capacity(requests as usize);
            for _ in 0..requests {
                let line = rng.command().to_string();
                let sent = Instant::now();
                c.request(&line).unwrap();
                times.push(sent.elapsed().as_secs_f64() * 1e6);
            }
            c.request("QUIT").unwrap();
            times
        })
    }).collect();
    let mut all: Vec<f64> = workers.into_iter().flat_map(|w| w.join().unwrap()).collect();
    let rate = all.len() as f64 / start.elapsed().as_secs_f64() / 1e3;
    all.sort_by(|a, b| a.total_cmp(b));
    let pct = |p: f64| all[((all.len() - 1) as f64 * p) as usize];
    (rate, pct(0.50), pct(0.99))
}
```

***Listing 31.13.** One run over TCP: each client times every request; the percentiles come from the sorted times code/bachelor-2/31-project-key-value-server/listings/load.rs*

```
$ rustc --edition 2021 -O -o load load.rs && ./load
in process: 400000 operations per thread, 90 % GET, 1000 keys (M ops/s)
threads  one lock  16 shards
      1      4.48       2.91
      2      2.20       5.04
      4      1.21       4.81
      8      0.98       7.09
over TCP: 8 workers, 20000 requests per client (k req/s; p50, p99 in us)
clients  one lock    p50    p99  16 shards    p50    p99
      1       6.3    148    369        6.5    141    381
      2      12.4    155    327       11.8    162    339
      4      34.0     91    413       56.8     65    128
      8     100.3     76    135      112.7     68    122
SET with the log, one client, 2000 requests (k req/s)
 sync every record       0.8
leave it to the OS      28.3
```

***Output 31.3.** One run on the author’s laptop: in process, over TCP, and the cost of syncing the log.*

![The in-process part of , measured on a laptop. With one lock, more threads do less work in all: they spend their time handing the lock to each other. With 16 shards, the throughput grows with the threads, though not at every step.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-project-key-value-server/fig-924679434da0.svg)

*The in-process part of [Output 31.3](#out-b2-project-key-value-server-load), measured on a laptop. With one [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock), more [threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) do less work in all: they spend their time handing the [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) to each other. With 16 [shards](#def-b2-project-key-value-server-shard), the throughput grows with the [threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread), though not at every step.*

Three things stand out. In process, one [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) gets *slower* as [threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) are added, from about 4.5 million operations per second with one [thread](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) to about 1 million with eight, while the sharded store reaches about 7 million; with a single [thread](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) the [shards](#def-b2-project-key-value-server-shard) cost something, a hash and a reader–writer [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) instead of a plain mutex. Over TCP the two stores are mostly within noise of each other (the 4-client row is the exception, and a single run does not tell why): a request costs on the order of 100 microseconds of [system calls](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-syscall) and loopback, and a [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) held for a fraction of a microsecond is not the bottleneck; the throughput grows with the clients because each waits for its own round trip. And the policy of the log dominates everything when it syncs: a `sync_data` per `SET` costs milliseconds, and the server writes some tens of times fewer `SET`s than when it leaves the records to the operating system. Measurements on another machine give other numbers; these three shapes are what to look for.

**In practice.**

A server that must sync can batch the syncs, a technique called *group commit*: the changes that arrive within a millisecond share one `sync`, and every client in the group receives `OK` after it. The latency of a `SET` grows a little, and the throughput comes back. Clients also send several requests before reading the replies ([Exercise 31.12](#exo-b2-project-key-value-server-12)).

![A small machine room. A server like this chapter’s runs on one of the machines in the rack; the network cables bring the clients’ requests, and the disks keep its log.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-project-key-value-server/img-df334f8e1ef3.jpg)

*A small machine room. A server like this chapter’s runs on one of the machines in the rack; the network cables bring the clients’ requests, and the disks keep its log.*

## 31.6 Milestone 6: the test suite, and what is left

The tests form a Cargo crate that includes the chapter’s modules by their paths, and a small program that starts the server on a port and a log given on its command line.

| test | what it checks |
| --- | --- |
| protocol | every command; eleven malformed lines covering every reason, and one too long; printing then parsing gives the command back |
| stores | both stores agree with a plain map on 3,000 random requests; 8 [threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) of 1,000 `SET`s lose none |
| [replay](#def-b2-project-key-value-server-log) | a log cut at every byte [replays](#def-b2-project-key-value-server-log) to the map after its last complete record ([Proposition 31.6](#prop-b2-project-key-value-server-replay)); a damaged byte stops the [replay](#def-b2-project-key-value-server-log) at its record |
| torn tail | `open` cuts it and appends after the last good record |
| compaction | the compacted [log replays](#def-b2-project-key-value-server-log) to the same map, is shorter, and takes appends ([Proposition 31.7](#prop-b2-project-key-value-server-compaction)) |
| `MSET` | [atomic](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-atomic) under 4 writers and 4 readers ([Exercise 31.10](#exo-b2-project-key-value-server-10)) |
| end to end | a session on port 44311, a request in two writes, a restart that keeps the data |
| kill | the server killed while a client writes: every acknowledged `SET` is replayed |

The kill test crashes the server on purpose: it starts the server program, lets a client send `SET`s as fast as the syncs allow, and kills the server after 300 milliseconds with a signal that no program can catch. It then [replays](#def-b2-project-key-value-server-log) the log and checks that it holds exactly the acknowledged `SET`s, plus at most the one in flight, which was written but whose `OK` never left.

What the server does not do: it runs on one machine, so a dead disk or a dead machine loses the data or the service; it has no authentication, which is acceptable only because it listens on the [loopback address](https://one-course.com/books/computer-science/4/en/chapter/16-sockets#def-b2-sockets-loopback); it does not expire keys ([Exercise 31.7](#exo-b2-project-key-value-server-7)) or take snapshots ([Exercise 31.9](#exo-b2-project-key-value-server-9)); and a `COUNT` is not a snapshot of the map. Replicating the log to other machines, and agreeing on its order when one of them fails, is the project of the Year 3 volume.

## 31.7 Exercises

**Exercise 31.1 ★.**

Predict the server’s reply to each line of the session in `exo_session.rs`: `SET a 1`, `SET b 2`, `SET a 3`, `GET a`, `DEL b`, `DEL b`, `GET b`, `COUNT`, `SET c 4 5`, `SET c 4` written with two spaces before and after the key, `GET c`, `DEL`, `COUNT`. Then run it.

**Solution of Exercise 31.1.**

```
$ rustc --edition 2021 -O -o exo_session exo_session.rs && ./exo_session
> SET a 1      < OK
> SET b 2      < OK
> SET a 3      < OK
> GET a        < VALUE 3
> DEL b        < OK
> DEL b        < NOTFOUND
> GET b        < NOTFOUND
> COUNT        < COUNT 1
> SET c 4 5    < ERR SET takes a key and a value
> SET  c  4    < OK
> GET c        < VALUE 4
> DEL          < ERR DEL takes one key
> COUNT        < COUNT 2
```

***Output 31.4.** The session’s replies.*

The second `DEL b` finds nothing. `SET c 4 5` has three arguments and is refused. The line with doubled spaces is accepted: the parser drops the empty words between spaces, so it reads as `SET c 4`. A stricter protocol would refuse it; this one is lenient on purpose, and the tests fix the behaviour so that it cannot change by accident. `DEL` without a key is refused, and the last `COUNT` sees `a` and `c`.

**Exercise 31.2 ★.**

The server of `exo_one_read.rs` treats the bytes returned by one `read` as one request. Run it; explain each line it prints, and what [Listing 31.2](#lst-b2-project-key-value-server-handle) does instead.

**Solution of Exercise 31.2.**

```
$ rustc --edition 2021 -O -o exo_one_read exo_one_read.rs && ./exo_one_read
the server got one request: "SET a 1\nGET a\n"
the server got one request: "GE"
the server got one request: "T a\n"
```

***Output 31.5.** Three reads: two requests in the first, half a request in each of the others.*

TCP delivers a stream of bytes, not the client’s writes. The first `read` returns both requests of the first write, which the buggy server would parse as one line, with a newline inside. The last request was written in two pieces, 100 milliseconds apart, and arrives in two reads, neither of them a request. [Listing 31.2](#lst-b2-project-key-value-server-handle) reads through a buffer up to each newline: it would see `SET a 1`, `GET a` and `GET a`, whatever the reads return.

**Exercise 31.3 ★.**

A visit counter is incremented by `GET` and then `SET` of the value plus one. Explain the result of the first part of `exo_incr.rs`, then write an `INCR k` that is [atomic](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-atomic), and check it with eight clients.

**Solution of Exercise 31.3.**

```
$ rustc --edition 2021 -O -o exo_incr exo_incr.rs && ./exo_incr
GET then SET, two clients: visits = 1
INCR, 8 clients x 10000: visits = 80000
```

***Output 31.6.** Two increments make 1; eight clients of INCR lose none.*

Both clients read 0 before either writes, then both write 1: a [lost update](https://one-course.com/books/computer-science/4/en/chapter/30-database-design-dependencies-normal-forms-and-transactions#def-b2-database-design-anomalies), staged here by a [barrier](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-barrier) between the read and the write. Each step is locked, but the [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) is released between them. `INCR` reads, adds one and writes under one acquisition of the [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock), so no other client can come between: $8 \times 10\,000 = 80\,000$. In the server, it is one more `Command` handled like `SET` under the shard’s write [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock), and logged as the `SET` of the new value, so that a [replay](#def-b2-project-key-value-server-log) does not depend on the order of increments being repeated exactly.

**Exercise 31.4 ★.**

Keys have 4 characters and values 6. Give the size of the log after $n$ `SET`s spread evenly over $k$ keys, before and after compaction, as formulas in $n$ and $k$; check them with `exo_log_size.rs`.

**Solution of Exercise 31.4.**

A record is $8 + 3 + 1 + 4 + 1 + 6 = 23$ bytes. Before compaction the log holds $23n$ bytes; after it, one record per key present, $23\min(n, k)$ bytes, here $23k$ since $n \ge k$.

```
$ rustc --edition 2021 -O -o exo_log_size exo_log_size.rs && ./exo_log_size
       n      k   log (bytes)   compacted (bytes)
    1000     10         23000                 230
    1000   1000         23000               23000
  100000     10       2300000                 230
  100000   1000       2300000               23000
```

***Output 31.7.** The four cases.*

When $n = k$ compaction gains nothing; with $n = 100\,000$ and $k = 10$ it shrinks the log ten thousand times.

**Exercise 31.5 ★★.**

Two clients run without any [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock): each reads $x$ and then writes the value it read plus one, starting from $x = 0$. List the [interleavings](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-interleaving) of the four steps, give the final $x$ for each, and check with `exo_interleave.rs`. Which outcome is the [lost update](https://one-course.com/books/computer-science/4/en/chapter/30-database-design-dependencies-normal-forms-and-transactions#def-b2-database-design-anomalies) of the previous chapter?

**Solution of Exercise 31.5.**

Each client’s two steps keep their order, so an [interleaving](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-interleaving) is a choice of the 2 positions of $a$’s steps among 4: $\binom{4}{2} = 6$.

```
$ rustc --edition 2021 -O -o exo_interleave exo_interleave.rs && ./exo_interleave
GETa SETa GETb SETb          x = 2
GETa GETb SETa SETb          x = 1
GETa GETb SETb SETa          x = 1
GETb GETa SETa SETb          x = 1
GETb GETa SETb SETa          x = 1
GETb SETb GETa SETa          x = 2
```

***Output 31.8.** The six [interleavings](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-interleaving).*

Only the two serial orders give 2. In the four others both clients read 0 before either writes, and both write 1: one increment is lost. That is the [lost update](https://one-course.com/books/computer-science/4/en/chapter/30-database-design-dependencies-normal-forms-and-transactions#def-b2-database-design-anomalies) of the previous chapter, here with no database to refuse it.

**Exercise 31.6 ★★.**

An `MSET a x b y` must change two keys in different [shards](#def-b2-project-key-value-server-shard) together. A first version [locks](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) the shard of its first key, then the shard of its second. Run `exo_mset_deadlock.rs`, explain the first two lines with a wait-for graph, and fix the order.

**Solution of Exercise 31.6.**

```
$ rustc --edition 2021 -O -o exo_mset_deadlock exo_mset_deadlock.rs && ./exo_mset_deadlock
locks in the order of the keys:
  MSET a b: holds shard 0, waits for shard 1: stuck
  MSET b a: holds shard 1, waits for shard 0: stuck
locks in increasing order of shard:
  MSET a b: took shard 0, then shard 1: done
  MSET b a: took shard 0, then shard 1: done
```

***Output 31.9.** Opposite orders deadlock; one order does not.*

The wait-for graph has an edge from `MSET a b` to `MSET b a` (the first waits for shard 1, held by the second) and an edge back (the second waits for shard 0, held by the first): a cycle, so a deadlock; the program sees it only because it gives up after 200 milliseconds. Fix: sort the shard numbers of the keys and [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) in increasing order, as in [Proposition 31.4](#prop-b2-project-key-value-server-lock-order); both now take shard 0 first, so one of them waits before holding anything, and the cycle cannot close. Two keys in the same shard need one [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock), not two: the numbers must be deduplicated, or a [thread](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) would wait for a [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) it already holds.

**Exercise 31.7 ★★.**

Add `SETEX k s v`, which sets a key that disappears $s$ seconds later. Run `exo_setex.rs`, which expires a key when it is read and sweeps the others. What must the log record so that a restart does not bring an expired key back?

**Solution of Exercise 31.7.**

```
$ rustc --edition 2021 -O -o exo_setex exo_setex.rs && ./exo_setex
t =    0 s: GET session:ada -> Some("token-1")
t =   29 s: GET session:ada -> Some("token-1")
t =   30 s: GET session:ada -> None
t = 3600 s: keys before the sweep 3
            the sweep removes 2, 1 left
```

***Output 31.10.** Lazy expiry on read, then a sweep.*

The key set at $t = 0$ for 30 seconds is still there at 29 and gone at 30. Two keys were never read after expiring: only the sweep removes them, and a real server runs it from time to time. The log must record the instant of expiry, not the duration: a `SETEX k 30 v` replayed an hour later would give the key thirty new seconds. Record `SETAT k` *deadline* `v`, and let [replay](#def-b2-project-key-value-server-log) skip, or delete, the keys whose deadline has passed.

**Exercise 31.8 ★★.**

Prove [Proposition 31.6](#prop-b2-project-key-value-server-replay).

**Solution of Exercise 31.8.**

Write $M_0$ for the empty map and $M_i$ for the map after applying $r_1, \dots, r_i$. *Claim*: after $i$ iterations of the loop of [Listing 31.9](#lst-b2-project-key-value-server-replay), the map is $M_i$ and `at` is the offset where $r_{i+1}$ begins. True for $i = 0$. If true for $i < n$, `next_record` reads $r_{i+1}$: its eight header bytes are present, its length is right, its CRC matches, since the record was written whole by `record`, and its payload parses as a `SET` or `DEL`; applying it gives $M_{i+1}$, and `at` advances by its size. At $i = n$, the bytes that remain do not begin with a complete, undamaged record by hypothesis, so `next_record` returns `None` and the loop ends with $M_n$. Finally, the server appended each change before applying it, in the order of the changes to each key (the shard [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) is held across both), and changes to different keys commute; so $M_n$ is the map the server held after its $n$-th logged change. The hypothesis on the tail is the delicate one: a torn record is short and fails the length test, and a tail of zeros fails the parse; random bytes pass the CRC test with probability $2^{-32}$.

**Exercise 31.9 ★★.**

Instead of compacting, the server can write a *snapshot*, the whole map as a file, and start a new, empty log. Run `exo_snapshot.rs`. In which order must the snapshot and the new log be made durable, and what does recovery do if the server crashes while writing the snapshot?

**Solution of Exercise 31.9.**

```
$ rustc --edition 2021 -O -o exo_snapshot exo_snapshot.rs && ./exo_snapshot
snapshot: 190 bytes; tail: 34 bytes
k3 = Some("after"), k4 = None, 9 keys
```

***Output 31.11.** Snapshot and tail replayed as one log.*

The snapshot is itself a log of one `SET` per key, so recovery [replays](#def-b2-project-key-value-server-log) the snapshot and then the tail as one sequence; a `DEL` in the tail removes a key of the snapshot, as `k4` shows. Order: write the snapshot to a temporary file, sync it, rename it over the old snapshot, sync the directory, and only then empty the log. A crash while the snapshot is written leaves the temporary file, which recovery ignores, and the old snapshot and full log, which are still correct. Emptying the log before the snapshot is durable would lose every change since the previous snapshot. The program does not sync, since it demonstrates the formats only; a server must.

**Exercise 31.10 ★★★.**

Write an [atomic](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-atomic) `MSET` and `MGET` for the sharded store, taking the shard [locks](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) in increasing order, and test them under load: four writers set two keys to the same value, half of them naming the keys in the other order, and four readers check that they never see two different values. Use `exo_mset.rs` and its module `mset.rs`.

**Solution of Exercise 31.10.**

```
$ rustc --edition 2021 -O -o exo_mset exo_mset.rs && ./exo_mset
shards of the keys: 1 and 4
4 writers x 20000 MSET, 4 readers x 20000 MGET: 0 reads saw two values
```

***Output 31.12.** The two keys in different [shards](#def-b2-project-key-value-server-shard), and no torn read.*

The module `mset.rs` sorts and deduplicates the shard numbers, takes the write [locks](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) in that order, and changes every key while it holds them all; `mget` takes the read [locks](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) in the same order. An `MGET` therefore sees the state either before or after each `MSET`, never between, and no deadlock is possible ([Proposition 31.4](#prop-b2-project-key-value-server-lock-order)), although half the writers name the keys the other way round. The crate’s test runs the same check with three keys. In the server, an `MSET` must also be one log record, or a crash between its records would [replay](#def-b2-project-key-value-server-log) half of it.

**Exercise 31.11 ★★★.**

Model the server as follows: a request costs $s$ microseconds in all, of which a time $h$ is spent holding the [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) of its shard; the store has $N$ [shards](#def-b2-project-key-value-server-shard) and receives requests from $c$ clients that each wait for the reply before sending the next. Give the throughput when the [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) is not the bottleneck, and the throughput that one [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) caps, and compare with [Output 31.3](#out-b2-project-key-value-server-load).

**Solution of Exercise 31.11.**

Each client sends a request every $s$ microseconds, so $c$ clients offer $c / s$ requests per microsecond. One [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) is held $h$ microseconds per request, so it lets through at most $1 / h$ requests per microsecond, whatever $c$; $N$ [shards](#def-b2-project-key-value-server-shard), with keys spread evenly, at most about $N / h$. The throughput is about $\min(c / s,\ N / h)$. In process, one [thread](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) does about 4.5 million operations per second, so $s \approx 0.2$ µs, and the [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) is held for most of it: one [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) caps near 5 million per second. The measured throughput *drops* below that with more [threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread), to 1 million: the model leaves out the cost of contention itself, the [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock)’s memory moving between cores and the [threads](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-thread) put to sleep and woken. Over TCP, $s \approx 150$ µs, so 8 clients offer about 53 thousand requests per second, far below either cap, and the [lock](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#def-b2-threads-and-synchronisation-lock) does not matter, as measured. The measured rate at 8 clients is higher than the model, about 100 thousand, because the latency per request fell as the machine got busier; a model with one fixed $s$ cannot show that.

**Exercise 31.12 ★★★.**

Pipelining: a client sends a batch of $b$ requests in one write, then reads the $b$ replies. Measure the throughput for $b = 1, 10, 100, 1000$ with `exo_pipeline.rs`, and explain the result. Why did [Listing 31.2](#lst-b2-project-key-value-server-handle) need nothing new to support it?

**Solution of Exercise 31.12.**

```
$ rustc --edition 2021 -O -o exo_pipeline exo_pipeline.rs && ./exo_pipeline
batch   requests   k req/s   us per request
    1     100000       6.7           148.60
   10     100000      61.3            16.31
  100     100000     444.0             2.25
 1000     100000    1546.3             0.65
```

***Output 31.13.** One client, batches of 1 to 1000 requests, on the author’s laptop.*

With $b = 1$ each request pays a whole round trip, about 150 microseconds of [system calls](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-syscall), scheduling and loopback. A batch pays one round trip for $b$ requests, so the time per request falls almost as $1/b$ until the server’s own work per request, under a microsecond, dominates: about 230 times the throughput at $b = 1000$. [Listing 31.2](#lst-b2-project-key-value-server-handle) reads requests from its buffer one line at a time whatever the batch, and [flushes](https://one-course.com/books/computer-science/4/en/chapter/14-files-pipes-and-signals#def-b2-files-pipes-signals-buffering) the replies only when the buffer is empty: one write of $b$ replies for a batch of $b$ requests. Nothing in the protocol had to change, because each reply is one line in the order of the requests.
