A Java implementation of the Raft consensus algorithm, providing a robust distributed consensus solution.
Raftly is a complete implementation of the Raft consensus protocol, featuring:
- Leader election with randomized timeouts
- Log replication with consistency guarantees
- State machine replication
- Membership management
- Thread-safe operations
- Configurable timeouts and heartbeat intervals
- Proper error handling and recovery mechanisms
- Java 8 or higher
- Maven 3.6 or higher
- Git
- Clone the repository:
git clone https://github.com/sajalkmr/raftly.git
cd raftly
- Build the project:
mvn clean install
- Start a local cluster with 3 nodes:
mvn exec:java -Dexec.mainClass="com.raftly.RaftDemo"
- The demo will:
- Initialize a 3-node Raft cluster
- Demonstrate leader election
- Show log replication in action
- Display state machine consistency
# Core Raft settings
raft.election.timeout.base=1500
raft.election.timeout.range=750
raft.heartbeat.interval=1000
raft.commit.check.interval=500
# Cluster settings
raft.cluster.size=3
You can modify these settings by:
- Updating the constants in
RaftNode.java
- Passing custom values during node initialization
- Implements the core Raft consensus logic
- Manages node state (Follower/Candidate/Leader)
- Handles leader election and log replication
- Uses scheduled tasks for timeouts and heartbeats
- Thread-safe log entry management
- Handles log consistency and conflict resolution
- Supports atomic append operations
- Maintains log indices and terms
- Applies committed log entries
- Maintains consistent state across the cluster
- Supports state snapshots and recovery
- Uses
ReentrantLock
for state modifications - Atomic operations for critical state changes
- Read-write locks for log access
- Thread-safe scheduled operations
// Initialize components
StateMachine stateMachine = new StateMachine();
Log log = new Log();
RaftNode node = new RaftNode(0, null, stateMachine, log);
// Create and set up cluster
List<RaftNode> nodes = Arrays.asList(node);
RaftCluster cluster = new RaftCluster(nodes);
node.setCluster(cluster);
// Start the node
node.start();
// Append a command through the leader
if (node.isLeader()) {
LogEntry entry = new LogEntry(currentTerm, "SET key value");
CompletableFuture<Boolean> future = node.appendCommand(entry);
boolean success = future.get(); // Wait for replication
}
The implementation includes robust error handling for:
- Network partitions
- Node failures
- Split votes
- Log inconsistencies
- Concurrent operations
- Fork the repository
- Create a feature branch
- Commit your changes
- Push to the branch
- Create a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Based on the Raft Consensus Algorithm paper by Diego Ongaro and John Ousterhout