Counter SMR Example
This example demonstrates how to build a simple distributed counter using State Machine Replication (SMR) with the Rabia consensus protocol.
What This Example Shows
The Counter SMR demonstrates the fundamental SMR concepts:
- Deterministic State Machine: All operations on the counter produce predictable, reproducible results
- Operation Ordering: Rabia ensures all replicas apply increment/decrement operations in the same order
- Fault Tolerance: The counter remains available as long as a majority of replicas are healthy
- Strong Consistency: All replicas maintain identical counter values
State Machine Implementation
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 zero
All operations include overflow/underflow protection and operation counting.
Key SMR Features Demonstrated
Deterministic Operations
match command
State Serialization for Snapshots
Error Handling
The counter demonstrates proper error handling for edge cases like integer overflow/underflow, ensuring the state machine never panics or produces undefined behavior.
Running the Example
# Run the counter SMR example
# Run tests to see SMR behavior
# Run with multiple replicas (if implemented)
Use Cases
This pattern is useful for:
- Distributed Counters: Website hit counters, API rate limiting
- Resource Allocation: Database connection pools, queue sizes
- Metrics Collection: Aggregating statistics across services
- Game Scores: Leaderboards, player statistics
Extending This Example
You can extend the counter SMR to demonstrate more advanced SMR concepts:
- Batch Operations: Apply multiple increments/decrements atomically
- Conditional Operations: Increment only if value is below threshold
- Named Counters: Maintain multiple named counters in one state machine
- Time-based Operations: Add timestamps to track operation history
Implementation Notes
Why This Works Well for SMR
- Small State: The counter state is minimal (just an integer), making snapshots efficient
- Fast Operations: Arithmetic operations are fast and deterministic
- No External Dependencies: Operations don't depend on external systems or current time
- Easy to Test: Simple operations make it easy to verify correctness
Performance Characteristics
- Memory Usage: Minimal (single integer + operation counter)
- Operation Latency: Very low (simple arithmetic)
- Throughput: High (operations can be batched efficiently)
- Snapshot Size: Tiny (serialized integer)
This makes the counter an ideal first example for learning SMR concepts with Rabia.
Next Steps
After understanding the counter example, explore:
- Key-Value Store SMR - More complex state with multiple operations
- Banking SMR - Business logic with validation and transactions
- Custom State Machine - Template for your own SMR applications