◉ Pulse
LORDLYAMIGO avatar
#52 today

LORDLYAMIGO/HeatedShards

C++ AI #cpp #sharding

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.

Created Jul 21, 2026
Stars
6
Today
+6
Forks
0
Quality
90/100
Momentum
19

README

Fetched from GitHub on Nov 7, 2026, 11:33 PM UTC · README.md

View original on GitHub

Third-party content — Open Source Pulse is not the owner of this repository.

This README belongs to LORDLYAMIGO/HeatedShards and its contributors. We fetch it directly from the project’s public GitHub repository and display it for reference only. All text, code, images and trademarks remain the property of their respective authors. See the repository for its license terms. Copyright / takedown policy.

Heated Shards Logo

Probabilistic Shard Manager — C++20 Proof of Concept

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.

Quick Start

Requirements

  • CMake 3.25+
  • GCC 12+ or Clang 15+ (C++20 support)
  • Windows/Linux/macOS (POSIX compatible or Windows)

Build

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)

Run Simulation

# 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.2

Run Tests

cd build && ctest --output-on-failure
# or directly:
./build/tests/sharding_tests.exe

Architecture Overview

System Components

┌─────────────────────────────────────────────────┐
│           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)   │
      └─────────────┘             └──────────────┘

Key Features

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

Design Principles

SOLID Compliance

  • 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

Modern C++ Idioms

  • RAII everywhere — no raw new/delete. std::unique_ptr / std::shared_ptr manage lifetimes.
  • Value semantics for small types — Shard, EMA avoid heap allocation on hot paths.
  • std::optional<T> — for nullable values (threshold, disk assignment, frozen timestamp).
  • std::chrono — all time handling. No raw double seconds.
  • std::atomic<double> — thread-safe EMA updates without locks.
  • const correctness — immutability enforced at compile time.
  • [[nodiscard]] — error-prone return values must be checked.
  • Concepts (C++20) — Hashable concept constrains template parameters.
  • std::span — zero-copy views over contiguous data.

Project Structure

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

Core Components

Shard (Value Type)

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)

Probabilistic Data Structures

CountMinSketch

Frequency estimation with error bounds: P(error > ε×N) < δ

  • Default: ε ≈ 0.0026, δ ≈ 0.0067
  • Never underestimates; bounded overestimation
  • Used for hot-key detection

ExponentialMovingAverage

Thread-safe lock-free rate smoothing:

rate = α × instantRate + (1 - α) × prevRate
  • α = 0.1: balanced responsiveness
  • Half-life tunable per instance

HyperLogLog

Cardinality estimation (±0.81% error at ~16KB memory)

  • Used for auxiliary metrics
  • Not on critical path

Placement Strategy

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

Rebalancing

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

Freezing Logic

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

Testing

All tests use Google Test (gtest). Run with:

cd build && ctest --output-on-failure

Test 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

Configuration

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 accesses
  • basic: threshold = 100 accesses
  • pro: threshold = 1000 accesses
  • unlimited: no threshold

Workload Generation

Zipf Distribution (Realistic Web Traffic)

ZipfWorkloadGenerator(alpha, seed)
  • alpha = 1.5: standard web access pattern
  • Generates skewed shard access frequencies
  • Popular shards see exponentially more traffic

Burst Injection

BurstInjector(baseGenerator, shardIdx, startEvent, duration, multiplier)
  • Wraps any generator
  • Injects spikes on specific shard
  • Useful for testing freeze/demotion logic

Compilation Warnings Treated as Errors

Build with /WX (MSVC) or -Werror (GCC/Clang) to catch issues early:

cmake -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-Werror"

Performance Characteristics

  • 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

Design Decisions & Tradeoffs

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

Future Enhancements

  • 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)

References

  • 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)

License

MIT License — see LICENSE file


Rendered by GitHub from the repository’s README. Scroll to read the full file.
First trending

Jul 21, 2026

first spotted on the list

Best rank

#52

highest position reached

Appearances

1

times on the trending list

Quality score

90

out of 100

Momentum

19

trend strength indicator

Star velocity

0.06

stars per day since creation

Activity — last 60 days

daily counts, collected every 6 hours
  • Stars
  • Forks
  • Merged PRs
  • Issues
  • Closed issues

Collecting activity data since launch — check back in a few days.

Star history

total stars per snapshot

Not enough snapshots yet — check back soon.

Rank history

position on trending · lower is better

Not enough snapshots yet — check back soon.

3D card for your website

Live HTML card with a glass surface and pointer tilt. Paste the iframe on any website.

<iframe src="https://www.notionpulse.cc/embed/LORDLYAMIGO/HeatedShards" width="420" height="240" style="border:0;max-width:100%;background:transparent" loading="lazy" title="LORDLYAMIGO/HeatedShards — trending on Open Source Pulse"></iframe>

Stars badge

Show current stars in your README or profile. Auto-updates every 6 hours.

LORDLYAMIGO/HeatedShards stars badge
Markdown
[![LORDLYAMIGO/HeatedShards](https://www.notionpulse.cc/api/badge/LORDLYAMIGO/HeatedShards.svg)](https://www.notionpulse.cc/repo/LORDLYAMIGO/HeatedShards)
HTML
<a href="https://www.notionpulse.cc/repo/LORDLYAMIGO/HeatedShards"><img src="https://www.notionpulse.cc/api/badge/LORDLYAMIGO/HeatedShards.svg" alt="LORDLYAMIGO/HeatedShards stars badge" /></a>

Repository of the Day

#52 Repository of the Day

Repository of the Week

#52 Repository of the Week

Repository of the Month

#52 Repository of the Month