Redis Part 3: How to Add Persistence to a Redis Clone in Rust
The Final Stretch
We have a TCP server accepting concurrent connections and executing commands against a shared in-memory store with key expiry running in the background. The one thing missing is that when the server restarts, all data is gone. We also have no proper client, just raw netcat sessions.
Part 3 finishes the build. Disk persistence, the CLI client, and the test suite. After this the project is complete.
Disk Persistence
Redis calls its persistence mechanism RDB snapshots. Every few seconds it serializes the entire dataset to disk. On startup it reads the snapshot back. Ours works the same way.
The challenge is that Instant is not serializable. It represents a point in time relative to some system clock that may not survive a restart. To persist expiry times we convert them to Unix timestamps (seconds since the epoch) when saving and convert back on load.
Replace the placeholder src/persistence.rs:
<button data-code="use crate::storage::{Entry, Store};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::time;
#[derive(Serialize, Deserialize)]
struct PersistedEntry {
value: String,
expires_at_unix: Option,
}
#[derive(Serialize, Deserialize)]
struct Snapshot {
entries: HashMap,
}
pub async fn load_from_disk(path: &str, store: &Store) {
if !Path::new(path).exists() {
println!("No snapshot found at {}. Starting fresh.", path);
return;
}
match tokio::fs::read_to_string(path).await {
Err(e) => eprintln!("Could not read snapshot: {}", e),
Ok(content) => match serde_json::from_str::(&content) {
Err(e) => eprintln!("Could not parse snapshot: {}", e),
Ok(snapshot) => {
let now_unix = unix_now();
let mut store = store.lock().unwrap();
for (key, pe) in snapshot.entries {
let expires_at = pe.expires_at_unix.and_then(|exp_unix| {
if exp_unix > now_unix {
let remaining = exp_unix – now_unix;
Some(Instant::now() + Duration::from_secs(remaining))
} else {
None // already expired, skip
}
});
if pe.expires_at_unix.map_or(true, |_| expires_at.is_some()) {
store.insert(key, Entry { value: pe.value, expires_at });
}
}
println!("Loaded {} keys from {}", store.len(), path);
}
},
}
}
pub fn start_persistence(store: Store, path: &str) {
let path = path.to_string();
tokio::spawn(async move {
let mut interval = time::interval(Duration::from_secs(30));
loop {
interval.tick().await;
save_snapshot(&store, &path).await;
}
});
}
async fn save_snapshot(store: &Store, path: &str) {
let snapshot = {
let store = store.lock().unwrap();
let now = Instant::now();
let now_unix = unix_now();
let entries = store
.iter()
.filter(|(_, e)| e.expires_at.map_or(true, |exp| now eprintln!("Serialization failed: {}", e),
Ok(json) => match tokio::fs::write(path, json).await {
Err(e) => eprintln!("Could not write snapshot: {}", e),
Ok(_) => println!("[snapshot] Saved {} keys to {}", snapshot.entries.len(), path),
},
}
}
fn unix_now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use crate::storage::{Entry, Store};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::time;
#[derive(Serialize, Deserialize)]
struct PersistedEntry {
value: String,
expires_at_unix: Option<u64>,
}
#[derive(Serialize, Deserialize)]
struct Snapshot {
entries: HashMap<String, PersistedEntry>,
}
pub async fn load_from_disk(path: &str, store: &Store) {
if !Path::new(path).exists() {
println!("No snapshot found at {}. Starting fresh.", path);
return;
}
match tokio::fs::read_to_string(path).await {
Err(e) => eprintln!("Could not read snapshot: {}", e),
Ok(content) => match serde_json::from_str::<Snapshot>(&content) {
Err(e) => eprintln!("Could not parse snapshot: {}", e),
Ok(snapshot) => {
let now_unix = unix_now();
let mut store = store.lock().unwrap();
for (key, pe) in snapshot.entries {
let expires_at = pe.expires_at_unix.and_then(|exp_unix| {
if exp_unix > now_unix {
let remaining = exp_unix - now_unix;
Some(Instant::now() + Duration::from_secs(remaining))
} else {
None // already expired, skip
}
});
if pe.expires_at_unix.map_or(true, |_| expires_at.is_some()) {
store.insert(key, Entry { value: pe.value, expires_at });
}
}
println!("Loaded {} keys from {}", store.len(), path);
}
},
}
}
pub fn start_persistence(store: Store, path: &str) {
let path = path.to_string();
tokio::spawn(async move {
let mut interval = time::interval(Duration::from_secs(30));
loop {
interval.tick().await;
save_snapshot(&store, &path).await;
}
});
}
async fn save_snapshot(store: &Store, path: &str) {
let snapshot = {
let store = store.lock().unwrap();
let now = Instant::now();
let now_unix = unix_now();
let entries = store
.iter()
.filter(|(_, e)| e.expires_at.map_or(true, |exp| now < exp))
.map(|(k, e)| {
let expires_at_unix = e.expires_at.map(|exp| {
let remaining = (exp - now).as_secs();
now_unix + remaining
});
(k.clone(), PersistedEntry {
value: e.value.clone(),
expires_at_unix,
})
})
.collect();
Snapshot { entries }
};
match serde_json::to_string_pretty(&snapshot) {
Err(e) => eprintln!("Serialization failed: {}", e),
Ok(json) => match tokio::fs::write(path, json).await {
Err(e) => eprintln!("Could not write snapshot: {}", e),
Ok(_) => println!("[snapshot] Saved {} keys to {}", snapshot.entries.len(), path),
},
}
}
fn unix_now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
use crate::storage::{Entry, Store};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::time;
#[derive(Serialize, Deserialize)]
struct PersistedEntry {
value: String,
expires_at_unix: Option<u64>,
}
#[derive(Serialize, Deserialize)]
struct Snapshot {
entries: HashMap<String, PersistedEntry>,
}
pub async fn load_from_disk(path: &str, store: &Store) {
if !Path::new(path).exists() {
println!("No snapshot found at {}. Starting fresh.", path);
return;
}
match tokio::fs::read_to_string(path).await {
Err(e) => eprintln!("Could not read snapshot: {}", e),
Ok(content) => match serde_json::from_str::<Snapshot>(&content) {
Err(e) => eprintln!("Could not parse snapshot: {}", e),
Ok(snapshot) => {
let now_unix = unix_now();
let mut store = store.lock().unwrap();
for (key, pe) in snapshot.entries {
let expires_at = pe.expires_at_unix.and_then(|exp_unix| {
if exp_unix > now_unix {
let remaining = exp_unix - now_unix;
Some(Instant::now() + Duration::from_secs(remaining))
} else {
None // already expired, skip
}
});
if pe.expires_at_unix.map_or(true, |_| expires_at.is_some()) {
store.insert(key, Entry { value: pe.value, expires_at });
}
}
println!("Loaded {} keys from {}", store.len(), path);
}
},
}
}
pub fn start_persistence(store: Store, path: &str) {
let path = path.to_string();
tokio::spawn(async move {
let mut interval = time::interval(Duration::from_secs(30));
loop {
interval.tick().await;
save_snapshot(&store, &path).await;
}
});
}
async fn save_snapshot(store: &Store, path: &str) {
let snapshot = {
let store = store.lock().unwrap();
let now = Instant::now();
let now_unix = unix_now();
let entries = store
.iter()
.filter(|(_, e)| e.expires_at.map_or(true, |exp| now < exp))
.map(|(k, e)| {
let expires_at_unix = e.expires_at.map(|exp| {
let remaining = (exp - now).as_secs();
now_unix + remaining
});
(k.clone(), PersistedEntry {
value: e.value.clone(),
expires_at_unix,
})
})
.collect();
Snapshot { entries }
};
match serde_json::to_string_pretty(&snapshot) {
Err(e) => eprintln!("Serialization failed: {}", e),
Ok(json) => match tokio::fs::write(path, json).await {
Err(e) => eprintln!("Could not write snapshot: {}", e),
Ok(_) => println!("[snapshot] Saved {} keys to {}", snapshot.entries.len(), path),
},
}
}
fn unix_now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
The #[derive(Serialize, Deserialize)] on PersistedEntry and Snapshot is the serde derive macro from article 012. It generates all the JSON serialization code automatically. Without it you would write hundreds of lines of manual serialization logic.
load_from_disk reads the JSON file, parses it, and reconstructs the store. Expired keys are skipped during load. Keys with no expiry are restored as-is. Keys with a future expiry have their Instant reconstructed from the remaining seconds.
save_snapshot takes a snapshot of the store while holding the lock for the minimum amount of time. Notice how the lock is released before the async tokio::fs::write call. Holding a lock across an async operation is a common mistake. Here we build the snapshot synchronously, drop the lock, then write to disk asynchronously.
The CLI Client
Connecting with nc works but is not a great experience. Let us write a proper client with a prompt.
Create src/bin/client.rs:
Result<(), Box> {
let addr = std::env::args()
.nth(1)
.unwrap_or_else(|| "127.0.0.1:6379".to_string());
let stream = TcpStream::connect(&addr).await?;
println!("Connected to Tiny Redis at {}", addr);
println!("Commands: PING SET key value [EX secs] GET key");
println!(" DEL key EXISTS key EXPIRE key secs");
println!(" TTL key DBSIZE QUIT");
println!();
let (reader, mut writer) = stream.into_split();
let mut server_reader = BufReader::new(reader);
let mut welcome = String::new();
server_reader.read_line(&mut welcome).await?;
println!("Server: {}", welcome.trim());
let stdin = io::stdin();
loop {
print!("> ");
io::stdout().flush()?;
let mut input = String::new();
match stdin.lock().read_line(&mut input) {
Ok(0) => break, // EOF
Err(e) => { eprintln!("Input error: {}", e); break; }
Ok(_) => {}
}
let trimmed = input.trim();
if trimmed.is_empty() {
continue;
}
writer.write_all(format!("{}n", trimmed).as_bytes()).await?;
let mut response = String::new();
server_reader.read_line(&mut response).await?;
let resp = response.trim();
if resp.starts_with('+') {
println!("{}", &resp[1..]);
} else if resp.starts_with(':') {
println!("(integer) {}", &resp[1..]);
} else if resp == "$-1" {
println!("(nil)");
} else if resp.starts_with('-') {
println!("Error: {}", &resp[1..]);
} else {
println!("{}", resp);
}
if trimmed.to_uppercase() == "QUIT" {
break;
}
}
println!("Goodbye.");
Ok(())
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::io::{self, BufRead, Write};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = std::env::args()
.nth(1)
.unwrap_or_else(|| "127.0.0.1:6379".to_string());
let stream = TcpStream::connect(&addr).await?;
println!("Connected to Tiny Redis at {}", addr);
println!("Commands: PING SET key value [EX secs] GET key");
println!(" DEL key EXISTS key EXPIRE key secs");
println!(" TTL key DBSIZE QUIT");
println!();
let (reader, mut writer) = stream.into_split();
let mut server_reader = BufReader::new(reader);
let mut welcome = String::new();
server_reader.read_line(&mut welcome).await?;
println!("Server: {}", welcome.trim());
let stdin = io::stdin();
loop {
print!("> ");
io::stdout().flush()?;
let mut input = String::new();
match stdin.lock().read_line(&mut input) {
Ok(0) => break, // EOF
Err(e) => { eprintln!("Input error: {}", e); break; }
Ok(_) => {}
}
let trimmed = input.trim();
if trimmed.is_empty() {
continue;
}
writer.write_all(format!("{}n", trimmed).as_bytes()).await?;
let mut response = String::new();
server_reader.read_line(&mut response).await?;
let resp = response.trim();
if resp.starts_with('+') {
println!("{}", &resp[1..]);
} else if resp.starts_with(':') {
println!("(integer) {}", &resp[1..]);
} else if resp == "$-1" {
println!("(nil)");
} else if resp.starts_with('-') {
println!("Error: {}", &resp[1..]);
} else {
println!("{}", resp);
}
if trimmed.to_uppercase() == "QUIT" {
break;
}
}
println!("Goodbye.");
Ok(())
}
use std::io::{self, BufRead, Write};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = std::env::args()
.nth(1)
.unwrap_or_else(|| "127.0.0.1:6379".to_string());
let stream = TcpStream::connect(&addr).await?;
println!("Connected to Tiny Redis at {}", addr);
println!("Commands: PING SET key value [EX secs] GET key");
println!(" DEL key EXISTS key EXPIRE key secs");
println!(" TTL key DBSIZE QUIT");
println!();
let (reader, mut writer) = stream.into_split();
let mut server_reader = BufReader::new(reader);
let mut welcome = String::new();
server_reader.read_line(&mut welcome).await?;
println!("Server: {}", welcome.trim());
let stdin = io::stdin();
loop {
print!("> ");
io::stdout().flush()?;
let mut input = String::new();
match stdin.lock().read_line(&mut input) {
Ok(0) => break, // EOF
Err(e) => { eprintln!("Input error: {}", e); break; }
Ok(_) => {}
}
let trimmed = input.trim();
if trimmed.is_empty() {
continue;
}
writer.write_all(format!("{}n", trimmed).as_bytes()).await?;
let mut response = String::new();
server_reader.read_line(&mut response).await?;
let resp = response.trim();
if resp.starts_with('+') {
println!("{}", &resp[1..]);
} else if resp.starts_with(':') {
println!("(integer) {}", &resp[1..]);
} else if resp == "$-1" {
println!("(nil)");
} else if resp.starts_with('-') {
println!("Error: {}", &resp[1..]);
} else {
println!("{}", resp);
}
if trimmed.to_uppercase() == "QUIT" {
break;
}
}
println!("Goodbye.");
Ok(())
}
The client formats responses the way a real Redis client would. +OK becomes OK. :-1 becomes (integer) -1. $-1 becomes (nil). Small detail but it makes the experience feel polished.
The optional address argument (std::env::args().nth(1)) means you can connect to a remote server with cargo run --bin client -- 192.168.1.5:6379.
Tests
With all three modules built, we can write integration tests that test the full command execution path against a real store.
Create tests/integration.rs:
use std::time::Duration;
use tiny_redis::command::{execute, Command};
use tiny_redis::storage::new_store;
#[tokio::test]
async fn set_and_get() {
let store = new_store();
execute(Command::Set {
key: "name".to_string(),
value: "Alice".to_string(),
ttl: None,
}, &store).await;
let response = execute(Command::Get { key: "name".to_string() }, &store).await;
assert_eq!(response, "+Alicen");
}
#[tokio::test]
async fn get_missing_key_returns_nil() {
let store = new_store();
let response = execute(Command::Get { key: "ghost".to_string() }, &store).await;
assert_eq!(response, "$-1n");
}
#[tokio::test]
async fn del_removes_key() {
let store = new_store();
execute(Command::Set {
key: "temp".to_string(),
value: "value".to_string(),
ttl: None,
}, &store).await;
let del_response = execute(Command::Del { key: "temp".to_string() }, &store).await;
assert_eq!(del_response, ":1n");
let get_response = execute(Command::Get { key: "temp".to_string() }, &store).await;
assert_eq!(get_response, "$-1n");
}
#[tokio::test]
async fn expired_key_returns_nil() {
let store = new_store();
execute(Command::Set {
key: "short".to_string(),
value: "lived".to_string(),
ttl: Some(Duration::from_millis(1)),
}, &store).await;
tokio::time::sleep(Duration::from_millis(10)).await;
let response = execute(Command::Get { key: "short".to_string() }, &store).await;
assert_eq!(response, "$-1n");
}
#[tokio::test]
async fn dbsize_counts_active_keys() {
let store = new_store();
execute(Command::Set { key: "a".to_string(), value: "1".to_string(), ttl: None }, &store).await;
execute(Command::Set { key: "b".to_string(), value: "2".to_string(), ttl: None }, &store).await;
execute(Command::Set { key: "c".to_string(), value: "3".to_string(), ttl: None }, &store).await;
let response = execute(Command::DbSize, &store).await;
assert_eq!(response, ":3n");
}
#[tokio::test]
async fn ping_returns_pong() {
let store = new_store();
let response = execute(Command::Ping, &store).await;
assert_eq!(response, "+PONGn");
}
#[tokio::test]
async fn overwrite_existing_key() {
let store = new_store();
execute(Command::Set {
key: "count".to_string(),
value: "1".to_string(),
ttl: None,
}, &store).await;
execute(Command::Set {
key: "count".to_string(),
value: "99".to_string(),
ttl: None,
}, &store).await;
let response = execute(Command::Get { key: "count".to_string() }, &store).await;
assert_eq!(response, "+99n");
}
use std::time::Duration;
use tiny_redis::command::{execute, Command};
use tiny_redis::storage::new_store;
#[tokio::test]
async fn set_and_get() {
let store = new_store();
execute(Command::Set {
key: "name".to_string(),
value: "Alice".to_string(),
ttl: None,
}, &store).await;
let response = execute(Command::Get { key: "name".to_string() }, &store).await;
assert_eq!(response, "+Alicen");
}
#[tokio::test]
async fn get_missing_key_returns_nil() {
let store = new_store();
let response = execute(Command::Get { key: "ghost".to_string() }, &store).await;
assert_eq!(response, "$-1n");
}
#[tokio::test]
async fn del_removes_key() {
let store = new_store();
execute(Command::Set {
key: "temp".to_string(),
value: "value".to_string(),
ttl: None,
}, &store).await;
let del_response = execute(Command::Del { key: "temp".to_string() }, &store).await;
assert_eq!(del_response, ":1n");
let get_response = execute(Command::Get { key: "temp".to_string() }, &store).await;
assert_eq!(get_response, "$-1n");
}
#[tokio::test]
async fn expired_key_returns_nil() {
let store = new_store();
execute(Command::Set {
key: "short".to_string(),
value: "lived".to_string(),
ttl: Some(Duration::from_millis(1)),
}, &store).await;
tokio::time::sleep(Duration::from_millis(10)).await;
let response = execute(Command::Get { key: "short".to_string() }, &store).await;
assert_eq!(response, "$-1n");
}
#[tokio::test]
async fn dbsize_counts_active_keys() {
let store = new_store();
execute(Command::Set { key: "a".to_string(), value: "1".to_string(), ttl: None }, &store).await;
execute(Command::Set { key: "b".to_string(), value: "2".to_string(), ttl: None }, &store).await;
execute(Command::Set { key: "c".to_string(), value: "3".to_string(), ttl: None }, &store).await;
let response = execute(Command::DbSize, &store).await;
assert_eq!(response, ":3n");
}
#[tokio::test]
async fn ping_returns_pong() {
let store = new_store();
let response = execute(Command::Ping, &store).await;
assert_eq!(response, "+PONGn");
}
#[tokio::test]
async fn overwrite_existing_key() {
let store = new_store();
execute(Command::Set {
key: "count".to_string(),
value: "1".to_string(),
ttl: None,
}, &store).await;
execute(Command::Set {
key: "count".to_string(),
value: "99".to_string(),
ttl: None,
}, &store).await;
let response = execute(Command::Get { key: "count".to_string() }, &store).await;
assert_eq!(response, "+99n");
}
Run them all with cargo test. The expired_key_returns_nil test is particularly satisfying because it tests real time-based behaviour. It sets a key with a 1 millisecond TTL, sleeps 10 milliseconds, then verifies the key is gone.
Running the Complete System
Start the server in one terminal:
cargo run --bin server
cargo run --bin server
You should see:
No snapshot found at tiny_redis.snapshot. Starting fresh.
Tiny Redis listening on 127.0.0.1:6379
No snapshot found at tiny_redis.snapshot. Starting fresh.
Tiny Redis listening on 127.0.0.1:6379
Start the client in another terminal:
cargo run --bin client
cargo run --bin client
Try a session:
PING
PONG
> SET username zeeshan
OK
> GET username
zeeshan
> SET session abc123 EX 30
OK
> TTL session
(integer) 29
> DBSIZE
(integer) 2
> EXISTS username
(integer) 1
> DEL username
(integer) 1
> GET username
(nil)
> QUIT
OK
Goodbye.” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
Connected to Tiny Redis at 127.0.0.1:6379
Server: Welcome to Tiny Redis. Type QUIT to disconnect.
> PING
PONG
> SET username zeeshan
OK
> GET username
zeeshan
> SET session abc123 EX 30
OK
> TTL session
(integer) 29
> DBSIZE
(integer) 2
> EXISTS username
(integer) 1
> DEL username
(integer) 1
> GET username
(nil)
> QUIT
OK
Goodbye.
Connected to Tiny Redis at 127.0.0.1:6379
Server: Welcome to Tiny Redis. Type QUIT to disconnect.
> PING
PONG
> SET username zeeshan
OK
> GET username
zeeshan
> SET session abc123 EX 30
OK
> TTL session
(integer) 29
> DBSIZE
(integer) 2
> EXISTS username
(integer) 1
> DEL username
(integer) 1
> GET username
(nil)
> QUIT
OK
Goodbye.
Open a second client terminal and connect another session while the first is still running. Both work simultaneously. The store is shared, changes from one client visible to the other. After 30 seconds the session key expires automatically.
Stop the server and restart it. The snapshot file loads automatically and your non-expired keys come back.
What This Project Demonstrates
Go back through the article series and match each concept to the code:
Article 003 (Ownership, Borrowing) is in every function signature. &Store borrows the store. store.lock().unwrap() gives a mutable guard that releases when it goes out of scope.
Article 005 (Traits) is in Command::parse returning Result, the Serialize and Deserialize derives on the snapshot types, and AsyncBufReadExt and AsyncWriteExt enabling methods on the reader and writer.
Article 006 (Error Handling) is the entire error.rs and every ? operator in the codebase.
Article 007 (Threads and Concurrency) is Arc::clone and Mutex in the storage engine and the background tasks.
Article 008 (Async/Await) is the TCP server, connection handler, and all the background tasks.
Article 009 (Closures and Iterators) is store.retain(...) in expiry cleanup and the iterator chain with .filter().map().collect() in the snapshot serialization.
Article 010 (Smart Pointers) is Arc<Mutex<HashMap>> for the store and Box<dyn std::error::Error> in main.
Article 011 (Lifetimes) is implicit in the Entry struct holding Option<Instant> and the references passed through the command executor.
Article 012 (Macros) is #[derive(Serialize, Deserialize)] on the snapshot types and #[tokio::main] and #[tokio::test].
Article 013 (Modules) is the entire project structure with proper pub/pub(crate) boundaries.
Article 014 (Testing) is the parser unit tests and the integration tests.
Where to Take It Next
This is a working, tested, persistent key-value store. What you build from here is up to you.
If you want to go deeper on systems: add a proper RESP3 protocol parser, support for list and hash data types, replication, or an AOF (append-only file) persistence mode. Look at how real Redis handles these.
If you want to go toward web services: put an HTTP API in front of the store using Axum. Now you have a Redis-like backend with a REST interface.
If you want to go toward performance: benchmark it with wrk or a custom load test. Profile with perf or cargo flamegraph. See where the Mutex contention is. Replace it with a sharded lock or a lock-free structure.
This codebase is small enough to understand completely and large enough to extend meaningfully. That is the ideal starting point for going further.
The series started with “what is Rust and why does it exist.” It ends here, with a concurrent, persistent, tested network server that you built yourself. Everything in between was building toward this.
Happy coding and safe assembling. We made it.
Full GitHub Repo here
Part 1: Building a Redis Clone in Rust
Part 1: Building a Redis Clone in Rust
A storage engine using Arc<Mutex>, a typed command parser, custom errors, and tests before a single TCP…
Part 2: How to Build a Concurrent TCP Server in Rust With Tokio
Redis Part 2: How to Build a Concurrent TCP Server in Rust With Tokio
Where We Left Off
Follow this series and join us in mastering Rust from scratch!


