本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 2 · 本科二年级
31Project: 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, and it is measured under a 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, borrowing and lifetimes (Chapter 6); Result and the ? operator (Chapter 7); traits and trait objects (Chapter 8). Threads, mutexes, reader–writer locks, and the lock-order rule that prevents deadlock (Proposition 15.18). A TCP connection carries a stream of bytes with no message boundaries, so a protocol must frame its messages (Section 16.3, Section 19.3). The CRC-32 detects every burst of errors up to 32 bits long (Theorem 17.9). 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.
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.
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}")),
}
}
Command, or the reason in an Err code/bachelor-2/31-project-key-value-server/listings/protocol.rsThe 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.
/// 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
}
}
}
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:
/// 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(())
}
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 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 of its own process, runs a scripted session against it, and reads the log back:
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));
$ 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")]
Two SETs, 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 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 of its own:
/// 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(())
}
The compiler checks the sharing: the closure moves an Arc<Shared> into the thread, and Shared holds a Box<dyn Store> whose trait requires Send + Sync, so a store that could not be shared safely between threads would not compile. A thread per connection costs a stack and a creation per client, and nothing bounds the number of threads: ten thousand clients make ten thousand threads.
Definition 31.2 (Thread pool)
A thread pool is a fixed set of threads, 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 is created per task.
/// 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(())
}
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 is released before the connection is handled, not after. Here a task is a whole connection, so a pool of workers serves 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 -th client. An event loop (Definition 16.12) serves any number of idle clients with one 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.
/// 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"),
}
}
Definition 31.3 (Sharding, lock striping)
Sharding splits a map into parts, the shards, and puts each key in the shard numbered by a hash of the key modulo . With one lock per shard, lock striping, two requests on keys of different shards proceed in parallel.
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,
}
}
GET, a write lock for SET and DEL code/bachelor-2/31-project-key-value-server/listings/store.rsEach shard is behind a reader–writer lock, so that many GETs on one shard also proceed together. COUNT takes the shards’ read locks 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 looks at what an unlocked client sees). Compaction, in the next milestone, holds every shard and then the log: several locks at once.
Proposition 31.4 (Lock order)
Number the locks: shard is lock for , and the log is lock . If every operation that holds several of them acquired them in increasing order, as SET, DEL, compaction and the MSET of Exercise 31.10 do, the server cannot deadlock.
Proof. A SET or DEL takes one shard lock, then the log: increasing. COUNT holds one lock at a time. Compaction takes the shards in the order , then the log. By Proposition 15.18, a set of threads waiting for each other would form a circle, in which each thread holds a 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 shows the deadlock that two MSETs produce when each takes the locks in the order of its own keys.
31.4 Milestone 4: persistence
A map in memory disappears with the 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:
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./// 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
}
}
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.
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(())
}
Cutting the tail off matters: without it, the next record would be appended after the torn bytes, and the following replay 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.
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(())
}
$ 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")]
Proposition 31.6 (Replay)
Let a log hold the records followed by any bytes that do not begin with a complete, undamaged record. Its replay is the map obtained by applying in order to the empty map, which is the map the server held after its -th change.
Proof. Exercise 31.8, by induction on . ∎
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, also stops the replay, 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 may leave that last record short, and so may the machine stopping between the operating system’s memory and the disk; the replay 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 SETs of one key leave a thousand records for one value. Compaction rewrites it:
/// 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)
}
Proposition 31.7 (Compaction)
If no change happens during the rewrite, the compacted log replays to the same map as the log it replaces.
Proof. The compacted log holds one SET k v for each pair of the map , 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 . By Proposition 31.6, the old log replays to the map held after its last change, which is , since no change happens during the rewrite: the store’s compact holds every shard’s 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 -th latency percentile is the latency below which a fraction of the requests fall: is the median, 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 GETs for one SET over a thousand keys. It is run twice, once against the store directly from threads of the same process, to measure the locks alone, and once through TCP:
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))
}
$ 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
Three things stand out. In process, one lock gets slower as threads are added, from about 4.5 million operations per second with one thread to about 1 million with eight, while the sharded store reaches about 7 million; with a single thread the shards cost something, a hash and a reader–writer 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 and loopback, and a 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 SETs 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).
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 of 1,000 SETs lose none |
| replay | a log cut at every byte replays to the map after its last complete record (Proposition 31.6); a damaged byte stops the replay at its record |
| torn tail | open cuts it and appends after the last good record |
| compaction | the compacted log replays to the same map, is shorter, and takes appends (Proposition 31.7) |
MSET | atomic under 4 writers and 4 readers (Exercise 31.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 SETs as fast as the syncs allow, and kills the server after 300 milliseconds with a signal that no program can catch. It then replays the log and checks that it holds exactly the acknowledged SETs, 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; it does not expire keys (Exercise 31.7) or take snapshots (Exercise 31.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
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
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 does instead.
Solution
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"
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 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, and check it with eight clients.
Solution
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
Both clients read 0 before either writes, then both write 1: a lost update, staged here by a barrier between the read and the write. Each step is locked, but the lock is released between them. INCR reads, adds one and writes under one acquisition of the lock, so no other client can come between: . In the server, it is one more Command handled like SET under the shard’s write lock, and logged as the SET of the new value, so that a replay 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 SETs spread evenly over keys, before and after compaction, as formulas in and ; check them with exo_log_size.rs.
Solution
Solution of Exercise 31.4.
A record is bytes. Before compaction the log holds bytes; after it, one record per key present, bytes, here since .
$ 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
When compaction gains nothing; with and it shrinks the log ten thousand times.
Exercise 31.5 ★★
Two clients run without any lock: each reads and then writes the value it read plus one, starting from . List the interleavings of the four steps, give the final for each, and check with exo_interleave.rs. Which outcome is the lost update of the previous chapter?
Solution
Solution of Exercise 31.5.
Each client’s two steps keep their order, so an interleaving is a choice of the 2 positions of ’s steps among 4: .
$ 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
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 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 together. A first version locks 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
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
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 in increasing order, as in Proposition 31.4; 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, not two: the numbers must be deduplicated, or a thread would wait for a lock it already holds.
Exercise 31.7 ★★
Add SETEX k s v, which sets a key that disappears 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
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
The key set at 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 skip, or delete, the keys whose deadline has passed.
Exercise 31.8 ★★
Prove Proposition 31.6.
Solution
Solution of Exercise 31.8.
Write for the empty map and for the map after applying . Claim: after iterations of the loop of Listing 31.9, the map is and at is the offset where begins. True for . If true for , next_record reads : 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 , and at advances by its size. At , the bytes that remain do not begin with a complete, undamaged record by hypothesis, so next_record returns None and the loop ends with . Finally, the server appended each change before applying it, in the order of the changes to each key (the shard lock is held across both), and changes to different keys commute; so is the map the server held after its -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 .
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
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
The snapshot is itself a log of one SET per key, so recovery replays 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 MSET and MGET for the sharded store, taking the shard locks 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
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
The module mset.rs sorts and deduplicates the shard numbers, takes the write locks in that order, and changes every key while it holds them all; mget takes the read locks 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), 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 half of it.
Exercise 31.11 ★★★
Model the server as follows: a request costs microseconds in all, of which a time is spent holding the lock of its shard; the store has shards and receives requests from clients that each wait for the reply before sending the next. Give the throughput when the lock is not the bottleneck, and the throughput that one lock caps, and compare with Output 31.3.
Solution
Solution of Exercise 31.11.
Each client sends a request every microseconds, so clients offer requests per microsecond. One lock is held microseconds per request, so it lets through at most requests per microsecond, whatever ; shards, with keys spread evenly, at most about . The throughput is about . In process, one thread does about 4.5 million operations per second, so µs, and the lock is held for most of it: one lock caps near 5 million per second. The measured throughput drops below that with more threads, to 1 million: the model leaves out the cost of contention itself, the lock’s memory moving between cores and the threads put to sleep and woken. Over TCP, µs, so 8 clients offer about 53 thousand requests per second, far below either cap, and the 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 cannot show that.
Exercise 31.12 ★★★
Pipelining: a client sends a batch of requests in one write, then reads the replies. Measure the throughput for with exo_pipeline.rs, and explain the result. Why did Listing 31.2 need nothing new to support it?
Solution
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
With each request pays a whole round trip, about 150 microseconds of system calls, scheduling and loopback. A batch pays one round trip for requests, so the time per request falls almost as until the server’s own work per request, under a microsecond, dominates: about 230 times the throughput at . Listing 31.2 reads requests from its buffer one line at a time whatever the batch, and flushes the replies only when the buffer is empty: one write of replies for a batch of requests. Nothing in the protocol had to change, because each reply is one line in the order of the requests.