Banking SMR Example
This example demonstrates how to build a sophisticated financial ledger using State Machine Replication (SMR) with the Rabia consensus protocol. It showcases complex business logic, validation, and transaction management in a distributed system.
What This Example Shows
The Banking SMR demonstrates advanced SMR concepts for real-world applications:
- Complex Business Logic: Account management with validation and business rules
- Multi-Entity State: Managing accounts, transactions, and relationships
- Atomic Operations: Transfer operations that must succeed or fail completely
- Validation and Error Handling: Comprehensive input validation and business rule enforcement
- Audit Trail: Complete transaction history for compliance and debugging
- Consistent State: Financial invariants maintained across all replicas
State Machine Implementation
The banking system implements these operations:
Account Management
CreateAccount { account_id, initial_balance }- Create new account with validationGetAccount { account_id }- Get complete account informationListAccounts- Get all accounts (admin operation)
Financial Operations
Deposit { account_id, amount }- Add funds to an accountWithdraw { account_id, amount }- Remove funds with balance checkingTransfer { from_account, to_account, amount }- Atomic transfer between accountsGetBalance { account_id }- Get current account balance
Reporting and Audit
GetTransactionHistory { account_id, limit }- Get transaction history with filtering
Key SMR Features Demonstrated
Complex State Management
Business Logic Validation
async
Audit Trail and Compliance
// Every financial operation creates an immutable audit record
GetTransactionHistory =>
Financial Invariants
The banking SMR maintains critical financial invariants:
- Conservation of Money: Total balance across all accounts never changes unless money is deposited or withdrawn
- Non-negative Balances: Accounts cannot have negative balances (no overdrafts)
- Atomic Transfers: Transfers either complete fully or fail completely
- Audit Trail: Every balance change is recorded in the transaction history
Running the Example
# Run the banking SMR example
# Run with multiple replicas to see consensus
# Run comprehensive tests
# Run stress tests with concurrent operations
Use Cases
This pattern is ideal for:
- Financial Systems: Banks, payment processors, digital wallets
- Trading Platforms: Order books, settlement systems, clearing houses
- Accounting Systems: General ledgers, bookkeeping, financial reporting
- Resource Management: Credits, quotas, resource allocation
- Gaming Economies: Virtual currencies, item trading, player balances
- Supply Chain: Inventory tracking, asset transfers, ownership records
Advanced Features
Concurrent Operations with Consistency
// All replicas process these operations in the same order
let batch_operations = vec!;
// All operations applied atomically in order across all replicas
let results = banking_smr.apply_commands.await;
Financial Reporting and Analytics
// The banking state provides rich analytics
Compliance and Monitoring
// Transaction monitoring for compliance
Performance Considerations
Memory Management
- Account Storage: Efficient HashMap storage for fast account lookups
- Transaction History: Consider archiving old transactions for large systems
- State Snapshots: Compressed serialization for efficient persistence
Throughput Optimization
- Batch Processing: Group multiple operations for higher throughput
- Read Replicas: Balance queries can be served from any replica
- Operation Ordering: Independent operations can be processed concurrently
Consistency Guarantees
- Strong Consistency: All replicas see the same account balances
- Linearizable Operations: Operations appear to execute atomically
- Durable Transactions: All committed transactions survive node failures
Security Considerations
Input Validation
Audit Requirements
- Immutable History: Transaction records are never modified or deleted
- Complete Trail: Every balance change is recorded with timestamps
- Deterministic IDs: Transaction IDs are generated deterministically for consistency
Implementation Notes
Why This Works Well for SMR
- Clear State Model: Accounts and transactions have well-defined relationships
- Deterministic Operations: All operations produce predictable results
- Strong Invariants: Financial rules are enforced consistently
- Atomic Operations: Complex operations (transfers) succeed or fail completely
- Rich Audit Trail: Complete history enables debugging and compliance
SMR Considerations
- State Size: Large transaction histories require careful management
- Snapshot Strategy: Balance between recovery time and storage overhead
- Validation Logic: All business rules must be deterministic across replicas
- Error Handling: Failed operations must not corrupt the state machine
Testing Strategy
Unit Tests
- Individual operation correctness
- Edge case handling (insufficient funds, invalid accounts)
- State serialization/deserialization
Integration Tests
- Multi-operation scenarios
- Concurrent transfer testing
- State consistency verification
Stress Tests
- High-volume transaction processing
- Memory usage under load
- Performance benchmarking
Next Steps
After understanding the banking example, explore:
- SMR Developer Guide - Comprehensive SMR development guide
- Performance Benchmarks - Banking SMR performance optimization
- Custom State Machine - Template for your own SMR applications
This banking example demonstrates how SMR can provide the strong consistency and fault tolerance required for financial applications while maintaining high performance and scalability.