| Crates.io | rabia-counter-example |
| lib.rs | rabia-counter-example |
| version | 0.4.1 |
| created_at | 2025-08-22 14:18:11.627189+00 |
| updated_at | 2025-08-22 14:18:11.627189+00 |
| description | Simple counter state machine implementation example using the Rabia SMR protocol |
| homepage | https://github.com/rabia-rs/rabia |
| repository | https://github.com/rabia-rs/rabia |
| max_upload_size | |
| id | 1806403 |
| size | 34,498 |
This example demonstrates how to build a simple distributed counter using State Machine Replication (SMR) with the Rabia consensus protocol.
The Counter SMR demonstrates the fundamental SMR concepts:
The counter implements these operations:
Increment(value) - Add a value to the counterDecrement(value) - Subtract a value from the counterSet(value) - Set counter to a specific valueGet - Read the current counter valueReset - Reset counter to zeroAll operations include overflow/underflow protection and operation counting.
match command {
CounterCommand::Increment(value) => {
// Deterministic: same input always produces same output
match self.state.value.checked_add(value) {
Some(new_value) => {
self.state.value = new_value;
CounterResponse::success(self.state.value)
}
None => CounterResponse::error(
self.state.value,
"Overflow: cannot increment counter".to_string(),
),
}
}
// ... other operations
}
fn serialize_state(&self) -> Vec<u8> {
bincode::serialize(&self.state).unwrap_or_default()
}
fn deserialize_state(&mut self, data: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
self.state = bincode::deserialize(data)?;
Ok(())
}
The counter demonstrates proper error handling for edge cases like integer overflow/underflow, ensuring the state machine never panics or produces undefined behavior.
# Run the counter SMR example
cargo run --bin counter_smr_example
# Run tests to see SMR behavior
cargo test -p counter_smr
# Run with multiple replicas (if implemented)
cargo run --bin counter_smr_cluster
This pattern is useful for:
You can extend the counter SMR to demonstrate more advanced SMR concepts:
This makes the counter an ideal first example for learning SMR concepts with Rabia.
After understanding the counter example, explore: