A standalone, storage-agnostic probabilistic shard manager written in modern C++20 following SOLID principles and modern C++ idioms. The system manages the full lifecycle of shards across a tiered disk hierarchy using probabilistic data structures for efficiency.
- CMake 3.25+
- GCC 12+ or Clang 15+ (C++20 support)
- Windows/Linux/macOS (POSIX compatible or Windows)
git clone https://github.com/yourname/poc-sharding-cpp
cd poc-sharding-cpp
cmake -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build --parallel $(nproc)# Default: Zipf workload, 50 shards, 4 disks, 100k events
./build/sharding_poc
# With verbose output
./build/sharding_poc --verbose
# Custom parameters
./build/sharding_poc --shards 100 --events 500000 --alpha 1.2cd build && ctest --output-on-failure
# or directly:
./build/tests/sharding_tests.exe┌─────────────────────────────────────────────────┐
│ ShardManager (Façade) │
├─────────────────────────────────────────────────┤
│ • ILoadTracker (ShardTracker) │
│ - Count-Min Sketch (hot-key detection) │
│ - Exponential Moving Average (rate smoothing) │
│ │
│ • IFreezer (ThresholdFreezer) │
│ - Access threshold gates │
│ - Cooldown tracking │
│ │
│ • IPlacementStrategy (PowerOfTwoPlacement) │
│ - Power-of-Two Choices algorithm │
│ - Balanced load distribution │
│ │
│ • IRebalancer (HysteresisRebalancer) │
│ - Hysteresis band oscillation prevention │
│ - Migration decision logic │
└─────────────────────────────────────────────────┘
│
├──────────────────────────────┐
▼ ▼
┌─────────────┐ ┌──────────────┐
│ Disk (NVMe) │ │ Disk (SSD) │
└─────────────┘ └──────────────┘
| Capability | Technique | C++ Mechanism |
|---|---|---|
| Hot-key detection | Count-Min Sketch | Template class, fixed-size array |
| Load tracking | Exponential Moving Average | std::atomic<double>, lock-free reads |
| Balanced placement | Power-of-Two Choices | Strategy pattern, std::mt19937_64 |
| Cardinality estimation | HyperLogLog | Bit manipulation, hash functions |
| Lifecycle management | State machine | enum class, explicit transitions |
| Freeze prediction | ETA from EMA rate | std::chrono for precise timing |
| Oscillation prevention | Hysteresis band | Policy-based thresholds |
| Event system | Observer pattern | std::function, notification bus |
- SRP: Each class has exactly one reason to change
- OCP: All behavior is behind pure virtual interfaces; extend without modifying
- LSP: All implementations honor identical pre/post conditions
- ISP: Read-only projections prevent accidental coupling
- DIP: All subsystems depend on abstractions, never concrete types
- RAII everywhere — no raw
new/delete.std::unique_ptr/std::shared_ptrmanage lifetimes. - Value semantics for small types —
Shard,EMAavoid heap allocation on hot paths. std::optional<T>— for nullable values (threshold, disk assignment, frozen timestamp).std::chrono— all time handling. No rawdoubleseconds.std::atomic<double>— thread-safe EMA updates without locks.constcorrectness — immutability enforced at compile time.[[nodiscard]]— error-prone return values must be checked.- Concepts (C++20) —
Hashableconcept constrains template parameters. std::span— zero-copy views over contiguous data.
poc-sharding/
├── include/ # Public headers
│ ├── core/
│ │ ├── Types.hpp # ShardId, DiskId, type aliases
│ │ ├── ShardState.hpp # enum class ShardState
│ │ ├── DiskTier.hpp # enum class DiskTier
│ │ ├── Shard.hpp # Shard value type
│ │ └── Disk.hpp # Disk class
│ │
│ ├── interfaces/
│ │ ├── IStorageBackend.hpp
│ │ ├── IPlacementStrategy.hpp
│ │ ├── ILoadTracker.hpp
│ │ ├── IRebalancer.hpp
│ │ ├── IFreezer.hpp
│ │ ├── IWorkloadGenerator.hpp
│ │ └── IAccessObserver.hpp
│ │
│ ├── probabilistic/
│ │ ├── CountMinSketch.hpp # Header-only template
│ │ ├── ExponentialMovingAverage.hpp
│ │ └── HyperLogLog.hpp # Header-only template
│ │
│ ├── impl/
│ │ ├── ShardTracker.hpp
│ │ ├── PowerOfTwoPlacement.hpp
│ │ ├── HysteresisRebalancer.hpp
│ │ ├── ThresholdFreezer.hpp
│ │ ├── InMemoryBackend.hpp
│ │ └── LocalFilesystemBackend.hpp
│ │
│ ├── ShardManager.hpp # Façade
│ ├── ShardFactory.hpp
│ ├── DiskFactory.hpp
│ ├── NotificationBus.hpp
│ ├── SimulationRunner.hpp
│ └── WorkloadGenerator.hpp
│
├── src/
│ ├── core/ # (Minimal implementations; mostly headers)
│ ├── impl/ # All subsystem implementations
│ ├── main.cpp # Entry point
│ └── ShardManager.cpp # Façade implementation
│
├── simulation/
│ ├── WorkloadGenerator.cpp # Zipf + Burst generators
│ └── (other simulation utilities)
│
├── benchmark/
│ └── Reporter.cpp # Metrics collection
│
├── tests/
│ ├── CMakeLists.txt
│ ├── test_count_min_sketch.cpp
│ ├── test_shard_lifecycle.cpp
│ ├── test_placement.cpp
│ ├── test_disk.cpp
│ ├── test_tracker.cpp
│ └── (more tests...)
│
├── CMakeLists.txt
└── config/
└── default.json
struct Shard {
ShardId id;
std::optional<uint64_t> threshold; // nullopt = unlimited
std::atomic<uint64_t> accessCount;
ShardState state;
std::optional<DiskId> diskId;
std::atomic<double> emaAccessRate;
TimePoint lastAccessTime;
// ... derived properties: exhaustion(), etaToFreeze(), effectiveTemperature()
};- Non-copyable (atomics) but movable
- Thread-safe read access via atomics
- Lazy evaluation of derived properties (effective temperature, ETA)
Frequency estimation with error bounds: P(error > ε×N) < δ
- Default:
ε ≈ 0.0026,δ ≈ 0.0067 - Never underestimates; bounded overestimation
- Used for hot-key detection
Thread-safe lock-free rate smoothing:
rate = α × instantRate + (1 - α) × prevRateα = 0.1: balanced responsiveness- Half-life tunable per instance
Cardinality estimation (±0.81% error at ~16KB memory)
- Used for auxiliary metrics
- Not on critical path
PowerOfTwoPlacement: Load balancing via random candidate sampling
- Selects the less-loaded of two random disks
- Reduces max load from O(log N/log log N) to O(log log N)
- Stateless; trivially thread-safe
HysteresisRebalancer: Oscillation prevention
- Hysteresis band:
load > avg × hot_multiplier(1.3) → overloaded - Hysteresis band:
load < avg × cold_multiplier(0.7) → underloaded - Dead-zone prevents thrashing
- Victim selection: high-rate, non-recently-migrated shards
ThresholdFreezer: Access rate gating
- Cooldown scales logarithmically with threshold:
cooldown = base × log(1 + threshold) - Proactive demotion when ETA < proactive window
- State machine: Warm → Freezing → Frozen → Archived
All tests use Google Test (gtest). Run with:
cd build && ctest --output-on-failureTest coverage includes:
- Count-Min Sketch correctness & error bounds
- Shard lifecycle & state transitions
- Placement algorithm balancing
- Disk management & utilization
- Tracker frequency estimation
- RebalancerDecision logic
- Integration tests via SimulationRunner
Default simulation parameters (src/main.cpp):
SimulationRunner::Config simCfg{
.numShards = 50,
.numEvents = 100'000,
.rebalanceEvery = 500,
.verbose = true
};Disk tier setup (via DiskFactory::defaultTieredSet()):
- NVMe: 20 shard capacity
- SSD: 50 shard capacity
- HDD: 100 shard capacity
- Cold: 500 shard capacity
Shard tier distribution (in main() loop):
free: threshold = 10 accessesbasic: threshold = 100 accessespro: threshold = 1000 accessesunlimited: no threshold
ZipfWorkloadGenerator(alpha, seed)alpha = 1.5: standard web access pattern- Generates skewed shard access frequencies
- Popular shards see exponentially more traffic
BurstInjector(baseGenerator, shardIdx, startEvent, duration, multiplier)- Wraps any generator
- Injects spikes on specific shard
- Useful for testing freeze/demotion logic
Build with /WX (MSVC) or -Werror (GCC/Clang) to catch issues early:
cmake -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-Werror"- Hot-path operations: Lock-free reads on EMA via
std::atomic<double> - Placement: O(1) random candidates; no scan of all disks
- Freezing: O(1) per shard per tick (no iteration)
- Rebalancing: O(disk_count × victim_scan); runs every N ticks
- Memory: Shards are non-copyable move-only; no inadvertent heap allocations
| Decision | Chosen | Alternative | Rationale |
|---|---|---|---|
| Shard atomics | std::atomic<double> on EMA |
Mutex around struct | Lock-free reads on hot path |
| Shard non-copyable | Deleted copy ctor | Copyable value | Atomics non-copyable; enforces single-owner semantics |
| Disk mutex | std::mutex on shard set |
Concurrent hashmap | Set ops infrequent; simpler correctness |
| Placement RNG | std::mt19937_64 |
rand() |
Reproducible, high quality |
| Sketch params | Compile-time Width/Depth |
Runtime config | Zero-overhead; size known at design |
| Observer ownership | Non-owning IAccessObserver* |
shared_ptr |
Observers outlive bus; avoids cycles |
| Storage interface | std::span<const std::byte> |
std::string |
Type-safe, zero-copy binary data |
- Distributed rebalancing across multiple managers
- Adaptive parameters (α for EMA, thresholds) based on metrics
- Ring migration strategy (consistent hashing variant)
- Persistence layer (RocksDB backend)
- Metrics collection to time-series DB (InfluxDB, Prometheus)
- gRPC service layer for multi-node coordination
- Workload prediction (time-series forecasting)
- Cormode, G., & Muthukrishnan, S. (2005). "An improved data stream summary: the count-min sketch and its applications"
- Graham, R. L. (1966). "Bounds on multiprocessing timing anomalies"
- Flajolet, P., Fusy, É., & Gandouet, O. (2007). "HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm"
- Mitzenmacher, M., & Upfal, E. (2005). "Probability and Computing" (Power of Two Choices chapter)
MIT License — see LICENSE file
