<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Raft Streaming Consensus Simulator</title>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background: #f0f0f0; }
#controls { background: white; padding: 15px; border-radius: 8px; margin-bottom: 20px; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
button { padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; background: #007bff; color: white; }
button:hover { background: #0056b3; }
button:disabled { background: #ccc; }
input[type=range] { width: 100px; }
label { font-weight: bold; }
#canvas { border: 2px solid #333; background: white; display: block; margin: 0 auto 20px; border-radius: 8px; }
#status { background: white; padding: 15px; border-radius: 8px; }
#events { height: 200px; overflow-y: auto; background: #f8f8f8; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px; }
.partition-btn { background: #dc3545; }
.crash-btn { background: #6c757d; }
#speed { width: 150px; }
.info { color: #666; font-size: 14px; }
</style>
</head>
<body>
<h1>Raft Streaming Consensus Simulator</h1>
<p class="info">Educational tool for simulating Raft consensus with streaming client requests. Nodes form a cluster agreeing on a replicated log. Inject failures to see resilience.</p>
<div id="controls">
<button id="startPause">Start</button>
<button id="reset">Reset</button>
<label>Speed: <input type="range" id="speed" min="0.1" max="10" step="0.1" value="1"></label>
<span id="speedVal">1x</span>
<label>Client Traffic: <input type="checkbox" id="clientTraffic"></label>
<button id="injectCrash">Crash Random Node</button>
<button id="healAll">Heal All</button>
<button id="partition">Partition (50/50)</button>
<div>
<label>Node: <select id="nodeSelect"><option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></label>
<button id="crashNode" class="crash-btn">Crash</button>
<button id="reviveNode" class="crash-btn">Revive</button>
</div>
<div class="info">Legend: 🔵 Follower | 🟡 Candidate | 🟢 Leader | ⚫ Crashed | Messages: delayed/dropped on failure</div>
</div>
<canvas id="canvas" width="1000" height="600"></canvas>
<div id="status">
<div>Sim Time: <span id="simTime">0</span>ms | Events: <span id="eventCount">0</span> | Committed: <span id="committed">0</span> | Status: <span id="verifyStatus">Ready</span></div>
<div id="events"></div>
</div>
<script>
// Core Simulator Classes
class LogEntry {
constructor(term, value) {
this.term = term;
this.value = value;
}
}
class Message {
constructor(from, to, type, payload, sendTime) {
this.from = from;
this.to = to;
this.type = type;
this.payload = payload;
this.sendTime = sendTime;
this.delay = Math.random() * 50 + 10; // 10-60ms network delay
this.receiveTime = sendTime + this.delay;
this.delivered = false;
}
}
class Node {
constructor(id, sim) {
this.id = id;
this.sim = sim;
this.reset();
}
reset() {
this.state = 'follower'; // follower, candidate, leader
this.term = 0;
this.log = [];
this.commitIndex = -1;
this.lastApplied = -1;
this.votedFor = null;
this.leaderId = null;
this.electionTimeout = 0;
this.heartbeatTimeout = 0;
this.votes = 0;
this.matchIndex = new Array(this.sim.numNodes).fill(0);
this.nextIndex = new Array(this.sim.numNodes).fill(0).map((_, i) => i === this.id ? 0 : 1);
this.crashed = false;
this.resetTimeouts();
}
resetTimeouts() {
this.electionTimeout = Math.random() * 150 + 150; // 150-300ms
this.heartbeatTimeout = 100;
}
updateTimeouts(delta) {
if (this.crashed) return;
this.electionTimeout -= delta;
this.heartbeatTimeout -= delta;
}
step(delta) {
if (this.crashed) return;
this.updateTimeouts(delta);
if (this.state === 'leader') {
if (this.heartbeatTimeout <= 0) {
this.sendHeartbeats();
this.heartbeatTimeout = 100;
}
} else if (this.electionTimeout <= 0) {
this.startElection();
}
}
startElection() {
this.state = 'candidate';
this.term++;
this.votedFor = this.id;
this.votes = 1;
this.resetTimeouts();
this.sim.logEvent(`Node ${this.id}: Starts election in term ${this.term}`);
// Request votes
for (let i = 0; i < this.sim.numNodes; i++) {
if (i !== this.id) {
const lastLogIndex = this.log.length - 1;
const lastLogTerm = this.log.length ? this.log[lastLogIndex].term : 0;
this.sim.sendMessage(this.id, i, 'RequestVote', {
term: this.term,
candidateId: this.id,
lastLogIndex,
lastLogTerm
});
}
}
}
sendHeartbeats() {
for (let i = 0; i < this.sim.numNodes; i++) {
if (i !== this.id) {
this.sendAppendEntries(i);
}
}
}
sendAppendEntries(to) {
const prevLogIndex = this.nextIndex[to] - 1;
const prevLogTerm = prevLogIndex >= 0 ? this.log[prevLogIndex].term : 0;
const entries = this.log.slice(this.nextIndex[to]);
const sim = this.sim;
sim.sendMessage(this.id, to, 'AppendEntries', {
term: this.term,
leaderId: this.id,
prevLogIndex,
prevLogTerm,
entries: entries.map(e => ({term: e.term, value: e.value})),
leaderCommit: this.commitIndex
});
}
handleMessage(msg) {
if (this.crashed || msg.payload.term < this.term) return;
if (msg.payload.term > this.term) {
this.term = msg.payload.term;
this.resetToFollower();
}
switch (msg.type) {
case 'RequestVote':
this.handleRequestVote(msg.payload);
break;
case 'RequestVoteResponse':
this.handleRequestVoteResponse(msg.payload);
break;
case 'AppendEntries':
this.handleAppendEntries(msg.payload);
break;
case 'AppendEntriesResponse':
this.handleAppendEntriesResponse(msg.payload);
break;
}
}
handleRequestVote(payload) {
let grant = false;
if (payload.term > this.term ||
(payload.term === this.term && (this.votedFor === null || payload.candidateId === this.votedFor))) {
const lastLogIndex = this.log.length - 1;
const lastLogTerm = this.log.length ? this.log[lastLogIndex].term : 0;
if (payload.lastLogTerm > lastLogTerm ||
(payload.lastLogTerm === lastLogTerm && payload.lastLogIndex >= lastLogIndex)) {
grant = true;
}
}
if (grant) {
this.votedFor = payload.candidateId;
}
this.sim.sendMessage(this.id, payload.candidateId, 'RequestVoteResponse', {
term: this.term,
voteGranted: grant
});
this.resetTimeouts();
}
handleRequestVoteResponse(payload) {
if (payload.term === this.term && payload.voteGranted) {
this.votes++;
if (this.votes > this.sim.numNodes / 2) {
this.becomeLeader();
}
}
}
handleAppendEntries(payload) {
if (payload.term < this.term) {
this.sim.sendMessage(this.id, payload.leaderId, 'AppendEntriesResponse', {term: this.term, success: false});
return;
}
this.leaderId = payload.leaderId;
this.resetTimeouts();
const prevLogIndex = payload.prevLogIndex;
if (prevLogIndex >= this.log.length ||
(prevLogIndex >= 0 && this.log[prevLogIndex].term !== payload.prevLogTerm)) {
this.sim.sendMessage(this.id, payload.leaderId, 'AppendEntriesResponse', {term: this.term, success: false});
return;
}
// Append new entries
for (let i = 0; i < payload.entries.length; i++) {
const newIndex = prevLogIndex + 1 + i;
const newEntry = payload.entries[i];
if (newIndex >= this.log.length) {
this.log.push(new LogEntry(newEntry.term, newEntry.value));
} else if (this.log[newIndex].term !== newEntry.term) {
this.log[newIndex] = new LogEntry(newEntry.term, newEntry.value);
}
}
if (payload.leaderCommit > this.commitIndex) {
this.commitIndex = Math.min(payload.leaderCommit, this.log.length - 1);
}
this.sim.sendMessage(this.id, payload.leaderId, 'AppendEntriesResponse', {term: this.term, success: true});
}
handleAppendEntriesResponse(payload) {
if (payload.term !== this.term) return;
if (payload.success) {
this.matchIndex[payload.from] = this.nextIndex[payload.from];
this.nextIndex[payload.from]++;
} else {
this.nextIndex[payload.from]--;
}
// Update commitIndex
let newCommit = this.commitIndex;
for (let i = this.commitIndex + 1; i < this.log.length; i++) {
let count = 0;
for (let j = 0; j < this.sim.numNodes; j++) {
if (this.matchIndex[j] >= i) count++;
}
if (count > this.sim.numNodes / 2 && this.log[i].term === this.term) {
newCommit = i;
} else {
break;
}
}
this.commitIndex = newCommit;
// Advance lastApplied (simplified)
this.lastApplied = this.commitIndex;
}
becomeLeader() {
this.state = 'leader';
this.leaderId = this.id;
this.resetTimeouts();
this.nextIndex.fill(0);
this.matchIndex.fill(0);
this.sim.logEvent(`Node ${this.id}: Becomes leader in term ${this.term}`);
}
resetToFollower() {
this.state = 'follower';
this.votedFor = null;
this.votes = 0;
this.leaderId = null;
this.resetTimeouts();
}
}
class Simulator {
constructor(numNodes = 5) {
this.numNodes = numNodes;
this.nodes = [];
this.messages = [];
this.time = 0;
this.running = false;
this.speed = 1;
this.eventLog = [];
this.partitions = new Set(); // pairs (min,max) for partitioned links
this.nextClientId = 0;
for (let i = 0; i < numNodes; i++) {
this.nodes.push(new Node(i, this));
}
this.canvas = document.getElementById('canvas');
this.ctx = this.canvas.getContext('2d');
this.initUI();
this.reset();
}
initUI() {
document.getElementById('startPause').onclick = () => this.toggle();
document.getElementById('reset').onclick = () => this.reset();
document.getElementById('speed').oninput = (e) => {
this.speed = +e.target.value;
document.getElementById('speedVal').textContent = this.speed + 'x';
};
document.getElementById('clientTraffic').onchange = (e) => this.clientTraffic = e.target.checked;
document.getElementById('injectCrash').onclick = () => this.crashRandom();
document.getElementById('healAll').onclick = () => this.healAll();
document.getElementById('partition').onclick = () => this.randomPartition();
document.getElementById('crashNode').onclick = () => this.crashNode(+document.getElementById('nodeSelect').value);
document.getElementById('reviveNode').onclick = () => this.reviveNode(+document.getElementById('nodeSelect').value);
}
reset() {
this.nodes.forEach(n => n.reset());
this.messages = [];
this.time = 0;
this.eventLog = [];
this.partitions.clear();
this.nextClientId = 0;
this.clientTraffic = false;
this.updateUI();
this.logEvent('Simulator reset. 5 nodes ready.');
}
toggle() {
this.running = !this.running;
document.getElementById('startPause').textContent = this.running ? 'Pause' : 'Start';
}
update(delta) {
if (!this.running) return;
const simDelta = delta * this.speed * 10; // Accelerate sim time
this.time += simDelta;
// Update nodes
this.nodes.forEach(node => {
node.step(simDelta);
});
// Deliver messages
this.messages = this.messages.filter(msg => {
if (this.time >= msg.receiveTime && !msg.delivered) {
const toNode = this.nodes[msg.to];
if (!toNode.crashed) {
toNode.handleMessage(msg);
msg.delivered = true;
this.logEvent(`Msg ${msg.type} ${msg.from}->${msg.to} delivered at ${this.time.toFixed(0)}`);
}
}
return !msg.delivered || this.time < msg.receiveTime + 1000; // Cleanup old
});
// Client traffic
if (this.clientTraffic && Math.random() < 0.02 * this.speed) { // Rate control
this.sendClientRequest();
}
// Verification
this.verify();
this.draw();
this.updateUI();
}
sendMessage(from, to, type, payload) {
// Check partition/crash
if (this.nodes[from].crashed || this.nodes[to].crashed) return;
const a = Math.min(from, to);
const b = Math.max(from, to);
if (this.partitions.has(`${a}-${b}`)) return; // Partitioned
const msg = new Message(from, to, type, payload, this.time);
this.messages.push(msg);
this.logEvent(`Msg ${type} ${from}->${to} sent at ${this.time.toFixed(0)}`);
}
sendClientRequest() {
const target = Math.floor(Math.random() * this.numNodes);
const value = `client-${this.nextClientId++}`;
// Simulate client append: leader appends, else forward (simplified: random node pretends to be client)
const leader = this.nodes.find(n => n.state === 'leader' && !n.crashed);
const nodeId = leader ? leader.id : target;
this.nodes[nodeId].log.push(new LogEntry(this.nodes[nodeId].term || 0, value));
this.logEvent(`Client append ${value} to node ${nodeId}`);
}
crashRandom() {
const alive = this.nodes.filter(n => !n.crashed);
if (alive.length) {
const idx = Math.floor(Math.random() * alive.length);
this.crashNode(alive[idx].id);
}
}
crashNode(id) {
this.nodes[id].crashed = true;
this.logEvent(`Node ${id} crashed`);
}
reviveNode(id) {
this.nodes[id].crashed = false;
this.nodes[id].resetTimeouts();
this.logEvent(`Node ${id} revived`);
}
healAll() {
this.nodes.forEach(n => { n.crashed = false; n.resetTimeouts(); });
this.partitions.clear();
this.logEvent('All nodes healed');
}
randomPartition() {
this.partitions.clear();
const mid = Math.floor(this.numNodes / 2);
for (let i = 0; i < mid; i++) {
for (let j = mid; j < this.numNodes; j++) {
this.partitions.add(`${i}-${j}`);
}
}
this.logEvent('Random 50/50 partition injected');
}
verify() {
const commits = this.nodes.map(n => n.commitIndex).filter(i => i >= 0);
const minCommit = Math.min(...commits);
let safe = true;
let issues = [];
// Check log consistency up to minCommit
for (let i = 0; i <= minCommit; i++) {
const entries = this.nodes.map(n => n.log[i] ? `${n.log[i].term}:${n.log[i].value}` : 'MISSING');
const unique = new Set(entries);
if (unique.size > 1) {
safe = false;
issues.push(`Log mismatch at index ${i}: ${Array.from(unique).join(', ')}`);
break;
}
}
// Unique leader per term
const leaders = {};
this.nodes.forEach(n => {
if (n.leaderId) leaders[n.leaderId] = (leaders[n.leaderId] || 0) + 1;
});
if (Object.values(leaders).some(c => c > 1)) {
safe = false;
issues.push('Multiple leaders detected');
}
document.getElementById('committed').textContent = minCommit + 1;
document.getElementById('verifyStatus').textContent = safe ? '✅ SAFE' : '❌ VIOLATED';
document.getElementById('verifyStatus').style.color = safe ? 'green' : 'red';
}
logEvent(msg) {
this.eventLog.push(`${this.time.toFixed(0)}: ${msg}`);
document.getElementById('eventCount').textContent = this.eventLog.length;
const events = document.getElementById('events');
events.innerHTML += `<div>${msg}</div>`;
events.scrollTop = events.scrollHeight;
}
draw() {
const ctx = this.ctx;
ctx.clearRect(0, 0, 1000, 600);
const centerX = 500;
const centerY = 300;
const radius = 200;
const nodeRadius = 30;
// Draw nodes
this.nodes.forEach((node, i) => {
const angle = (i / this.numNodes) * Math.PI * 2;
const x = centerX + Math.cos(angle) * radius;
const y = centerY + Math.sin(angle) * radius;
// Node circle
ctx.save();
if (node.crashed) {
ctx.fillStyle = '#333';
} else {
const colors = { follower: '#1e90ff', candidate: '#ffd700', leader: '#32cd32' };
ctx.fillStyle = colors[node.state] || '#ccc';
}
ctx.beginPath();
ctx.arc(x, y, nodeRadius, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#000';
ctx.lineWidth = 2;
ctx.stroke();
// State label
ctx.fillStyle = 'white';
ctx.font = 'bold 14px Arial';
ctx.textAlign = 'center';
ctx.fillText(node.id, x, y + 5);
ctx.fillStyle = 'black';
ctx.font = '12px Arial';
const stateLabel = node.crashed ? 'CRASHED' : node.state.toUpperCase();
ctx.fillText(stateLabel, x, y + 20);
// Log bar
const logWidth = Math.min(node.log.length * 5, 100);
ctx.fillStyle = node.crashed ? '#666' : '#ff69b4';
ctx.fillRect(x - logWidth/2, y + 35, logWidth, 8);
ctx.fillStyle = 'black';
ctx.font = '10px Arial';
ctx.fillText(`log:${node.log.length} c:${node.commitIndex + 1}`, x, y + 55);
ctx.restore();
});
// Draw messages
this.messages.forEach(msg => {
const fromNode = this.nodes[msg.from];
const toNode = this.nodes[msg.to];
if (fromNode.crashed || toNode.crashed) return;
const fromAngle = (msg.from / this.numNodes) * Math.PI * 2;
const toAngle = (msg.to / this.numNodes) * Math.PI * 2;
const fromX = centerX + Math.cos(fromAngle) * radius;
const fromY = centerY + Math.sin(fromAngle) * radius;
const toX = centerX + Math.cos(toAngle) * radius;
const toY = centerY + Math.sin(toAngle) * radius;
const progress = Math.min((this.time - msg.sendTime) / msg.delay, 1);
const curX = fromX + (toX - fromX) * progress;
const curY = fromY + (toY - fromY) * progress;
ctx.strokeStyle = msg.delivered ? '#00ff00' : `rgba(255,0,0,${1 - progress})`;
ctx.lineWidth = 2;
ctx.setLineDash(msg.delivered ? [] : [5, 5]);
ctx.beginPath();
ctx.moveTo(fromX, fromY);
ctx.lineTo(curX, curY);
ctx.stroke();
ctx.setLineDash([]);
// Label
ctx.fillStyle = 'black';
ctx.font = '10px Arial';
ctx.textAlign = 'center';
ctx.fillText(msg.type[0], curX, curY - 10);
});
// Leader arrow
const leader = this.nodes.find(n => n.state === 'leader');
if (leader) {
const angle = (leader.id / this.numNodes) * Math.PI * 2;
const lx = centerX + Math.cos(angle) * (radius + 50);
const ly = centerY + Math.sin(angle) * (radius + 50);
ctx.fillStyle = '#ffd700';
ctx.beginPath();
ctx.moveTo(lx, ly - 15);
ctx.lineTo(lx + 15, ly + 7);
ctx.lineTo(lx - 15, ly + 7);
ctx.closePath();
ctx.fill();
ctx.fillStyle = 'black';
ctx.fillText('LEADER', lx, ly + 25);
}
}
updateUI() {
document.getElementById('simTime').textContent = this.time.toFixed(0);
}
}
// Run simulator
const sim = new Simulator(5);
let lastTime = 0;
function loop(currentTime) {
const delta = (currentTime - lastTime) / 1000;
lastTime = currentTime;
sim.update(delta);
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
</script>
</body>
</html>
Usage Instructions (Educational Guide)
Overview
This is a fully self-contained HTML/JS Raft consensus protocol simulator optimized for education. Open the file in any modern browser. It simulates:
- Message Scheduling: Messages have realistic network delays (10-60ms), queued by receive time, visualized as animated arrows.
- Failure Injection: Crash/revive nodes, network partitions (dropped messages), random failures.
- Visualization: Real-time canvas showing node states (colors), logs (pink bars), messages (red/dashed in-flight, green delivered), leader crown.
- Verification: Automatic safety checks (log consistency, unique leader). Alerts violations in red.
- Streaming: Toggle "Client Traffic" for continuous append requests (sequential values). Watch consensus replicate under failures.
Key Raft Mechanics Demonstrated
- Leader Election: Timeouts trigger candidates; majority votes win.
- Log Replication: Leader appends client values, heartbeats enforce consistency.
- Commit Safety: Majority matchIndex advances commits.
- Fault Tolerance: Survives 1-2 crashes/partitions (quorum).
Educational Experiments
- Start & Observe: Click Start. Watch election → leader → idle heartbeats.
- Streaming Consensus: Enable Client Traffic. See log grow identically.
- Inject Failure:
- Crash a follower: Leader continues, promotes another.
- Crash leader: New election auto-recovers.
- Partition: Cluster splits; heals on "Heal All".
- Break It: Crash 3+ nodes → consensus stalls (verification fails).
- Tune: Speed up to 10x, pause to inspect.
Simulator Internals (For Deeper Learning)
- Event-Driven: Fixed-step sim loop processes timeouts/messages in timestamp order.
- Simplified Raft: Core phases (election/replication), no snapshots/conf changes.
- Verification Properties:
- Safety: All committed logs identical (no forks).
- Leader Uniqueness: At most one leader/term.
- Extensible: Add Byzantine faults by modifying
handleMessage.
Copy-paste into raft-sim.html and share! Perfect for classes/Docs. Questions? Ask Sherlock. 🕵️