Redis Part 2: How to Build a Concurrent TCP Server in Rust With Tokio
Where We Left Off
In Part 1 we built the foundation: the error types, the storage engine, and the command parser. Everything is tested and clean. Now we build the part that makes it real: the TCP server that accepts connections, the background thread that expires keys, and the command executor that ties it all together.
This is where all the async knowledge from article 008 and the concurrency knowledge from article 007 earn their place.
Key Expiry in the Background
Before the server, let us build the expiry cleanup. This is a background task that runs every second and removes keys whose expiry time has passed.
Create src/expiry.rs:
<button data-code="use crate::storage::Store;
use std::time::{Duration, Instant};
use tokio::time;
pub fn start_cleanup(store: Store) {
tokio::spawn(async move {
let mut interval = time::interval(Duration::from_secs(1));
loop {
interval.tick().await;
let mut store = store.lock().unwrap();
let now = Instant::now();
store.retain(|_, entry| {
entry.expires_at.map_or(true, |exp| now
use crate::storage::Store;
use std::time::{Duration, Instant};
use tokio::time;
pub fn start_cleanup(store: Store) {
tokio::spawn(async move {
let mut interval = time::interval(Duration::from_secs(1));
loop {
interval.tick().await;
let mut store = store.lock().unwrap();
let now = Instant::now();
store.retain(|_, entry| {
entry.expires_at.map_or(true, |exp| now < exp)
});
}
});
}
use crate::storage::Store;
use std::time::{Duration, Instant};
use tokio::time;
pub fn start_cleanup(store: Store) {
tokio::spawn(async move {
let mut interval = time::interval(Duration::from_secs(1));
loop {
interval.tick().await;
let mut store = store.lock().unwrap();
let now = Instant::now();
store.retain(|_, entry| {
entry.expires_at.map_or(true, |exp| now < exp)
});
}
});
}
tokio::spawn creates a background async task. It runs independently of the main server loop. Every second it wakes up, locks the store, and calls retain on the HashMap.
retain is an iterator method on HashMap that keeps only the entries for which the closure returns true. We return true when there is no expiry (keep it forever) or when the expiry is in the future (not yet expired). Everything else is dropped. One line to clean up all expired keys.
This approach is called lazy expiry with periodic cleanup, which is exactly how Redis does it. When a client requests a key, we check if it has expired at that moment. The background task handles the cleanup of keys no one will ever ask for again.
In Python you would use threading.Timer or asyncio.create_task. In Java you would use ScheduledExecutorService. In Rust with Tokio it is tokio::spawn with time::interval. The difference is Rust can share the store across the background task and all connection handlers through Arc<Mutex<T>> and the compiler verifies that sharing is safe.
Executing Commands
Now we write the function that takes a parsed Command and produces a response string.
This goes in src/command.rs, add it below the Command enum:
String {
match cmd {
Command::Ping => "+PONGn".to_string(),
Command::Set { key, value, ttl } => {
let entry = match ttl {
Some(duration) => crate::storage::Entry::with_expiry(value, duration),
None => crate::storage::Entry::new(value),
};
store.lock().unwrap().insert(key, entry);
"+OKn".to_string()
}
Command::Get { key } => {
let mut store = store.lock().unwrap();
match store.get(&key) {
Some(entry) if entry.is_expired() => {
store.remove(&key);
"$-1n".to_string()
}
Some(entry) => format!("+{}n", entry.value),
None => "$-1n".to_string(),
}
}
Command::Del { key } => {
let removed = store.lock().unwrap().remove(&key).is_some();
if removed { ":1n".to_string() } else { ":0n".to_string() }
}
Command::Exists { key } => {
let store = store.lock().unwrap();
let exists = store
.get(&key)
.map_or(false, |e| !e.is_expired());
if exists { ":1n".to_string() } else { ":0n".to_string() }
}
Command::Expire { key, seconds } => {
let mut store = store.lock().unwrap();
if let Some(entry) = store.get_mut(&key) {
entry.expires_at = Some(
Instant::now() + Duration::from_secs(seconds)
);
":1n".to_string()
} else {
":0n".to_string()
}
}
Command::Ttl { key } => {
let store = store.lock().unwrap();
match store.get(&key) {
None => ":-2n".to_string(),
Some(entry) => match entry.expires_at {
None => ":-1n".to_string(),
Some(exp) => {
let now = Instant::now();
if now > exp {
":-2n".to_string()
} else {
format!(":{}n", (exp – now).as_secs())
}
}
},
}
}
Command::DbSize => {
let count = store.lock().unwrap().len();
format!(":{}n", count)
}
Command::Quit => "+OKn".to_string(),
}
}” 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::Store;
pub async fn execute(cmd: Command, store: &Store) -> String {
match cmd {
Command::Ping => "+PONGn".to_string(),
Command::Set { key, value, ttl } => {
let entry = match ttl {
Some(duration) => crate::storage::Entry::with_expiry(value, duration),
None => crate::storage::Entry::new(value),
};
store.lock().unwrap().insert(key, entry);
"+OKn".to_string()
}
Command::Get { key } => {
let mut store = store.lock().unwrap();
match store.get(&key) {
Some(entry) if entry.is_expired() => {
store.remove(&key);
"$-1n".to_string()
}
Some(entry) => format!("+{}n", entry.value),
None => "$-1n".to_string(),
}
}
Command::Del { key } => {
let removed = store.lock().unwrap().remove(&key).is_some();
if removed { ":1n".to_string() } else { ":0n".to_string() }
}
Command::Exists { key } => {
let store = store.lock().unwrap();
let exists = store
.get(&key)
.map_or(false, |e| !e.is_expired());
if exists { ":1n".to_string() } else { ":0n".to_string() }
}
Command::Expire { key, seconds } => {
let mut store = store.lock().unwrap();
if let Some(entry) = store.get_mut(&key) {
entry.expires_at = Some(
Instant::now() + Duration::from_secs(seconds)
);
":1n".to_string()
} else {
":0n".to_string()
}
}
Command::Ttl { key } => {
let store = store.lock().unwrap();
match store.get(&key) {
None => ":-2n".to_string(),
Some(entry) => match entry.expires_at {
None => ":-1n".to_string(),
Some(exp) => {
let now = Instant::now();
if now > exp {
":-2n".to_string()
} else {
format!(":{}n", (exp - now).as_secs())
}
}
},
}
}
Command::DbSize => {
let count = store.lock().unwrap().len();
format!(":{}n", count)
}
Command::Quit => "+OKn".to_string(),
}
}
use crate::storage::Store;
pub async fn execute(cmd: Command, store: &Store) -> String {
match cmd {
Command::Ping => "+PONGn".to_string(),
Command::Set { key, value, ttl } => {
let entry = match ttl {
Some(duration) => crate::storage::Entry::with_expiry(value, duration),
None => crate::storage::Entry::new(value),
};
store.lock().unwrap().insert(key, entry);
"+OKn".to_string()
}
Command::Get { key } => {
let mut store = store.lock().unwrap();
match store.get(&key) {
Some(entry) if entry.is_expired() => {
store.remove(&key);
"$-1n".to_string()
}
Some(entry) => format!("+{}n", entry.value),
None => "$-1n".to_string(),
}
}
Command::Del { key } => {
let removed = store.lock().unwrap().remove(&key).is_some();
if removed { ":1n".to_string() } else { ":0n".to_string() }
}
Command::Exists { key } => {
let store = store.lock().unwrap();
let exists = store
.get(&key)
.map_or(false, |e| !e.is_expired());
if exists { ":1n".to_string() } else { ":0n".to_string() }
}
Command::Expire { key, seconds } => {
let mut store = store.lock().unwrap();
if let Some(entry) = store.get_mut(&key) {
entry.expires_at = Some(
Instant::now() + Duration::from_secs(seconds)
);
":1n".to_string()
} else {
":0n".to_string()
}
}
Command::Ttl { key } => {
let store = store.lock().unwrap();
match store.get(&key) {
None => ":-2n".to_string(),
Some(entry) => match entry.expires_at {
None => ":-1n".to_string(),
Some(exp) => {
let now = Instant::now();
if now > exp {
":-2n".to_string()
} else {
format!(":{}n", (exp - now).as_secs())
}
}
},
}
}
Command::DbSize => {
let count = store.lock().unwrap().len();
format!(":{}n", count)
}
Command::Quit => "+OKn".to_string(),
}
}
Add the missing imports at the top of command.rs:
use std::time::{Duration, Instant};
use std::time::{Duration, Instant};
The response format follows Redis’s own protocol loosely:
+OKand+PONGfor simple string responses+valuefor string values$-1for nil (key does not exist or expired):1and:0for integer responses (exists/not exists, count):-1for TTL when there is no expiry:-2for TTL when the key does not exist or has already expired
This is not the full RESP protocol but it is close enough to be recognizable and it works fine for our client.
Notice the Get arm. It checks for expiry inline:
{
store.remove(&key);
"$-1n".to_string()
}” 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″>
Some(entry) if entry.is_expired() => {
store.remove(&key);
"$-1n".to_string()
}
Some(entry) if entry.is_expired() => {
store.remove(&key);
"$-1n".to_string()
}
This is lazy expiry. Even if the background task has not run yet, a GET on an expired key will remove it immediately and return nil. The guard pattern in match (if entry.is_expired()) is something you only get in Rust. No other mainstream language has this built into its pattern matching.
The TCP Server
Now the main event. Create src/main.rs:
Result<(), Box> {
let store = storage::new_store();
let snapshot_path = "tiny_redis.snapshot";
persistence::load_from_disk(snapshot_path, &store).await;
expiry::start_cleanup(Arc::clone(&store));
persistence::start_persistence(Arc::clone(&store), snapshot_path);
let listener = TcpListener::bind("127.0.0.1:6379").await?;
println!("Tiny Redis listening on 127.0.0.1:6379");
println!("Use the client: cargo run –bin client");
loop {
let (socket, addr) = listener.accept().await?;
println!("[+] Connection from {}", addr);
let store = Arc::clone(&store);
tokio::spawn(async move {
if let Err(e) = handle_connection(socket, store).await {
eprintln!("[-] Connection error from {}: {}", addr, e);
}
println!("[-] Disconnected: {}", addr);
});
}
}
async fn handle_connection(
socket: tokio::net::TcpStream,
store: storage::Store,
) -> Result<(), Box> {
let (reader, mut writer) = socket.into_split();
let mut reader = BufReader::new(reader);
let mut line = String::new();
writer
.write_all(b"+Welcome to Tiny Redis. Type QUIT to disconnect.n")
.await?;
loop {
line.clear();
let bytes_read = reader.read_line(&mut line).await?;
if bytes_read == 0 {
break;
}
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let response = match command::Command::parse(trimmed) {
Ok(cmd) => {
let should_quit = cmd == command::Command::Quit;
let resp = command::execute(cmd, &store).await;
if should_quit {
writer.write_all(resp.as_bytes()).await?;
break;
}
resp
}
Err(e) => format!("-Error: {}n", e),
};
writer.write_all(response.as_bytes()).await?;
}
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::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
use tiny_redis::{command, expiry, persistence, storage};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let store = storage::new_store();
let snapshot_path = "tiny_redis.snapshot";
persistence::load_from_disk(snapshot_path, &store).await;
expiry::start_cleanup(Arc::clone(&store));
persistence::start_persistence(Arc::clone(&store), snapshot_path);
let listener = TcpListener::bind("127.0.0.1:6379").await?;
println!("Tiny Redis listening on 127.0.0.1:6379");
println!("Use the client: cargo run --bin client");
loop {
let (socket, addr) = listener.accept().await?;
println!("[+] Connection from {}", addr);
let store = Arc::clone(&store);
tokio::spawn(async move {
if let Err(e) = handle_connection(socket, store).await {
eprintln!("[-] Connection error from {}: {}", addr, e);
}
println!("[-] Disconnected: {}", addr);
});
}
}
async fn handle_connection(
socket: tokio::net::TcpStream,
store: storage::Store,
) -> Result<(), Box<dyn std::error::Error>> {
let (reader, mut writer) = socket.into_split();
let mut reader = BufReader::new(reader);
let mut line = String::new();
writer
.write_all(b"+Welcome to Tiny Redis. Type QUIT to disconnect.n")
.await?;
loop {
line.clear();
let bytes_read = reader.read_line(&mut line).await?;
if bytes_read == 0 {
break;
}
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let response = match command::Command::parse(trimmed) {
Ok(cmd) => {
let should_quit = cmd == command::Command::Quit;
let resp = command::execute(cmd, &store).await;
if should_quit {
writer.write_all(resp.as_bytes()).await?;
break;
}
resp
}
Err(e) => format!("-Error: {}n", e),
};
writer.write_all(response.as_bytes()).await?;
}
Ok(())
}
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
use tiny_redis::{command, expiry, persistence, storage};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let store = storage::new_store();
let snapshot_path = "tiny_redis.snapshot";
persistence::load_from_disk(snapshot_path, &store).await;
expiry::start_cleanup(Arc::clone(&store));
persistence::start_persistence(Arc::clone(&store), snapshot_path);
let listener = TcpListener::bind("127.0.0.1:6379").await?;
println!("Tiny Redis listening on 127.0.0.1:6379");
println!("Use the client: cargo run --bin client");
loop {
let (socket, addr) = listener.accept().await?;
println!("[+] Connection from {}", addr);
let store = Arc::clone(&store);
tokio::spawn(async move {
if let Err(e) = handle_connection(socket, store).await {
eprintln!("[-] Connection error from {}: {}", addr, e);
}
println!("[-] Disconnected: {}", addr);
});
}
}
async fn handle_connection(
socket: tokio::net::TcpStream,
store: storage::Store,
) -> Result<(), Box<dyn std::error::Error>> {
let (reader, mut writer) = socket.into_split();
let mut reader = BufReader::new(reader);
let mut line = String::new();
writer
.write_all(b"+Welcome to Tiny Redis. Type QUIT to disconnect.n")
.await?;
loop {
line.clear();
let bytes_read = reader.read_line(&mut line).await?;
if bytes_read == 0 {
break;
}
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let response = match command::Command::parse(trimmed) {
Ok(cmd) => {
let should_quit = cmd == command::Command::Quit;
let resp = command::execute(cmd, &store).await;
if should_quit {
writer.write_all(resp.as_bytes()).await?;
break;
}
resp
}
Err(e) => format!("-Error: {}n", e),
};
writer.write_all(response.as_bytes()).await?;
}
Ok(())
}
Let us walk through the important parts.
TcpListener::bind("127.0.0.1:6379").await? opens a TCP socket on port 6379, the same port Redis uses by default. The .await? runs it asynchronously and propagates any error.
listener.accept().await? waits for the next incoming connection. When a client connects, it returns a TcpStream and the client’s address.
Arc::clone(&store) creates a new pointer to the shared store for this connection. Each spawned task gets its own pointer, all pointing at the same data. This is article 007 in action.
tokio::spawn(async move { ... }) creates a new async task for this connection. The move keyword moves the cloned Arc and the socket into the task. The main loop is free immediately to accept the next connection. This is how we handle multiple clients simultaneously without blocking.
Inside handle_connection, socket.into_split() splits the TCP stream into a reader and a writer. We wrap the reader in BufReader so we can use read_line. This is the same pattern as reading from stdin but over a network socket.
The connection loop reads one line at a time, parses it as a command, executes it, and writes back the response. When the client sends QUIT or closes the connection (bytes_read == 0), the loop exits and the connection is cleaned up.
This is genuinely concurrent. While one client is waiting for a slow operation, other clients continue being served. No threads blocked waiting. The Tokio runtime multiplexes all of this across a thread pool automatically.
What Happens With Multiple Clients
To understand why this works, trace through what happens when two clients connect:
Client A connects. accept() returns, a task is spawned for A, and the loop immediately goes back to accept().
Client B connects. Another task is spawned for B.
Client A sends SET counter 0. The task for A locks the store, inserts the entry, releases the lock, and sends +OK.
Client B sends GET counter at the same time. The task for B tries to lock the store. If A’s task holds it, B waits. If A has released it, B gets it immediately.
The Mutex ensures that only one client is modifying the store at any moment. The Arc ensures both clients are looking at the same store. The Tokio runtime ensures neither task blocks a thread while waiting for I/O.
In Python with threading, this would require careful locking and you would worry about the GIL limiting true parallelism. In Java you would reach for ConcurrentHashMap and still need to think carefully about atomic operations across multiple map mutations. In Rust, the type system forces you to be explicit and the compiler verifies correctness.
Running It
Add a placeholder persistence.rs for now so the project compiles:
// src/persistence.rs
use crate::storage::Store;
pub async fn load_from_disk(_path: &str, _store: &Store) {
// implemented in Part 3
}
pub fn start_persistence(_store: Store, _path: &str) {
// implemented in Part 3
}
// src/persistence.rs
use crate::storage::Store;
pub async fn load_from_disk(_path: &str, _store: &Store) {
// implemented in Part 3
}
pub fn start_persistence(_store: Store, _path: &str) {
// implemented in Part 3
}
Also update src/lib.rs:
pub mod command;
pub mod error;
pub mod expiry;
pub mod persistence;
pub mod storage;
pub mod command;
pub mod error;
pub mod expiry;
pub mod persistence;
pub mod storage;
Now run the server:
cargo run --bin server
cargo run --bin server
In another terminal, connect with telnet or netcat:
nc 127.0.0.1 6379
nc 127.0.0.1 6379
Type commands:
PING
SET name Zeeshan
GET name
SET session token123 EX 10
TTL session
DBSIZE
QUIT
PING
SET name Zeeshan
GET name
SET session token123 EX 10
TTL session
DBSIZE
QUIT
You should see responses. Open a third terminal, connect another nc session, and try the same commands simultaneously. Both clients work at the same time, sharing the same store. That is the whole point.
What We Have Now
A working TCP server that:
- Accepts any number of simultaneous clients
- Parses and executes SET, GET, DEL, EXISTS, EXPIRE, TTL, DBSIZE, PING
- Expires keys lazily on GET and periodically in the background
- Handles errors cleanly and sends them back to the client
In Part 3 we add disk persistence so data survives server restarts, write the proper CLI client, add more tests, and do a final review of everything we built.
Happy coding and safe assembling!
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 3: How to Add Persistence to a Redis Clone in Rust
Redis Part 3: How to Add Persistence to a Redis Clone in Rust
Snapshot saves every 30 seconds. Nine passing tests including a real expiry timing test. A CLI client that connects and…
Follow this series and join us in mastering Rust from scratch!


