Skip to content
CanReaderPublic

About

A distributed key-value store built from scratch in Rust

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

raft-kv

A distributed key-value store built from scratch in Rust, powered by the Raft consensus algorithm.

Implements leader election, log replication, snapshotting, and fault tolerance across a 3-node cluster using gRPC for inter-node communication and RocksDB for persistent storage.


Architecture

                         ┌──────────────┐
                         │  Client CLI  │
                         └──────┬───────┘
                                │ gRPC
              ┌─────────────────┼─────────────────┐
              │                 │                 │
        ┌─────▼─────┐    ┌─────▼─────┐    ┌─────▼─────┐
        │  Node 1    │    │  Node 2    │    │  Node 3    │
        │  (Leader)  │◄──►│ (Follower) │◄──►│ (Follower) │
        └─────┬──────┘    └─────┬──────┘    └─────┬──────┘
              │                 │                 │
        ┌─────▼─────┐    ┌─────▼─────┐    ┌─────▼─────┐
        │  RocksDB   │    │  RocksDB   │    │  RocksDB   │
        └────────────┘    └────────────┘    └────────────┘

Each node runs:

  • Raft consensus engine — pure state machine with no I/O dependencies
  • State machine — RocksDB-backed KV store that applies committed log entries
  • gRPC server — dual services: RaftService (inter-node) and ClientService (external API)
  • Tick-driven event loop — tokio-based timers for election timeouts and heartbeats

Key Features

Raft Consensus (§5–§7 of the Raft paper)

  • Leader election with randomized timeouts and pre-vote protocol
  • Log replication with fast backtracking on conflict (skips entire terms)
  • Safety guarantees — only commits entries from the current term (§5.4.2)
  • No-op entry on leader election to flush prior-term commits
  • Snapshotting & log compaction — automatic snapshot triggers with chunked transfer via InstallSnapshot RPC

Fault Tolerance

  • Cluster tolerates ⌊(N-1)/2⌋ failures (1 node in a 3-node cluster)
  • Automatic leader re-election when the leader crashes
  • Followers catch up via log replication or snapshot installation
  • Durable state persistence — survives full cluster restart

Production Design Patterns

  • Pure Raft core — zero I/O in the consensus module; processes (State, Input) → (State, Outputs) for deterministic testability
  • Workspace architecture — five crates with strict dependency direction
  • Lazy gRPC connection pool with automatic reconnection
  • Leader redirection — clients automatically retry at the current leader

Project Structure

raft-kv/
├── proto/raft_kv.proto          # Protobuf service & message definitions
├── crates/
│   ├── raft-core/               # Pure Raft algorithm (no I/O)
│   │   └── src/
│   │       ├── node.rs          # Core state machine (~450 lines)
│   │       ├── log.rs           # Log with compaction support
│   │       ├── message.rs       # Input/output message types
│   │       ├── state.rs         # Role, persistent & volatile state
│   │       ├── snapshot.rs      # Snapshot metadata & chunked transfer
│   │       ├── config.rs        # Tick-based configuration
│   │       └── error.rs         # Error types
│   ├── raft-storage/            # RocksDB storage backends
│   │   └── src/
│   │       ├── rocks_store.rs   # KV state machine (apply/snapshot/restore)
│   │       ├── log_store.rs     # Durable Raft log
│   │       └── snapshot_store.rs# File-based snapshot persistence
│   ├── raft-transport/          # gRPC transport layer
│   │   └── src/
│   │       ├── raft_service.rs  # Inter-node RPC server
│   │       ├── client_service.rs# Client-facing KV API server
│   │       ├── rpc_client.rs    # Outgoing RPC client with connection pool
│   │       └── convert.rs       # Proto ↔ internal type conversions
│   ├── raft-server/             # Server binary & event loop
│   │   └── src/
│   │       ├── server.rs        # Async event loop (wires everything)
│   │       ├── main.rs          # CLI entry point
│   │       └── config.rs        # TOML configuration
│   └── raft-client/             # Client CLI binary
│       └── src/main.rs          # get/put/delete/status/bench commands
├── config/
│   ├── node1.toml               # Node 1 configuration
│   ├── node2.toml               # Node 2 configuration
│   └── node3.toml               # Node 3 configuration
└── scripts/
    ├── start_cluster.sh         # Launch 3-node cluster
    └── stop_cluster.sh          # Stop all nodes

Tech Stack

Component Technology
Language Rust (2021 edition)
Async runtime tokio
RPC framework tonic (gRPC) + prost (protobuf)
Persistent storage RocksDB
Serialization bincode (internal), protobuf (wire)
CLI framework clap v4
Observability tracing + tracing-subscriber

Quick Start

Prerequisites

  • Rust 1.75+ (rustup update stable)
  • protoc (Protocol Buffers compiler)
  • C/C++ compiler (MSVC on Windows, gcc/clang on Linux/macOS)
  • LLVM/libclang (required by RocksDB's bindgen)

Build

cargo build --release

Run a 3-Node Cluster

Terminal 1:

RUST_LOG=info cargo run --release --bin raft-kv-server -- --config config/node1.toml

Terminal 2:

RUST_LOG=info cargo run --release --bin raft-kv-server -- --config config/node2.toml

Terminal 3:

RUST_LOG=info cargo run --release --bin raft-kv-server -- --config config/node3.toml

Or use the convenience script:

./scripts/start_cluster.sh

Client Usage

# Store a value
cargo run --release --bin raft-kv-client -- put mykey "hello world"

# Retrieve a value
cargo run --release --bin raft-kv-client -- get mykey

# Delete a key
cargo run --release --bin raft-kv-client -- delete mykey

# Cluster status
cargo run --release --bin raft-kv-client -- status

# Benchmark
cargo run --release --bin raft-kv-client -- bench --count 1000

Configuration

Each node is configured via a TOML file:

node_id = 1
listen_addr = "127.0.0.1:50051"
data_dir = "./data/node1"

[[peers]]
id = 2
address = "http://127.0.0.1:50052"

[[peers]]
id = 3
address = "http://127.0.0.1:50053"

[raft]
election_timeout_min_ms = 150
election_timeout_max_ms = 300
heartbeat_interval_ms = 50
snapshot_threshold = 10000

Testing

# Unit tests (Raft core algorithm)
cargo test -p raft-core

# All tests
cargo test

Design Decisions

  1. Pure state machine Raft core — The RaftNode has zero dependencies on tokio, tonic, or RocksDB. It is a pure function: (State, Input) → (State, Outputs). This makes it unit-testable without I/O mocking and is the hallmark of a professional Raft implementation.

  2. Tick-based timers — The Raft core counts abstract ticks rather than wall-clock time. The server layer maps 10ms intervals to ticks. This makes the algorithm deterministic and testable.

  3. Fast log backtracking — Instead of decrementing next_index by 1 on each failed AppendEntries (O(n) in divergence length), the response includes conflict_term and conflict_index so the leader can skip entire terms.

  4. No-op on election — A new leader appends a no-op entry for the current term, ensuring entries from prior terms get committed indirectly (Raft safety property, §5.4.2).

  5. Workspace separation — Five crates with clear dependency direction: raft-core → raft-storage → raft-transport → raft-server/raft-client.

References

License

MIT

About

A distributed key-value store built from scratch in Rust

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages