Skip to content

feat(network): Raft-coordinated load balancer with all 5 routing strategies (v1.8.0, Issue #78) - #4245

Merged
makr-code merged 4 commits into
developfrom
copilot/load-balancing-with-raft-coordination
Mar 15, 2026
Merged

makr-code merged 4 commits into
developfrom
copilot/load-balancing-with-raft-coordination

Conversation

Copilot AI commented Mar 15, 2026 •

Copy link
Copy Markdown
Contributor

Implements RaftLoadBalancer — a Raft-consensus-based load balancer for distributed query routing with health monitoring, dynamic rebalancing, and cross-datacenter affinity.

Description

Core implementation

  • include/network/raft_load_balancer.h — RaftLoadBalancer with nested Config, Backend, Stats; LoadBalancingStrategy and RaftRole enums; full thread-safe API
  • src/network/raft_load_balancer.cpp — Production implementation:
    • Background Raft election loop: randomised timeouts, FOLLOWER → CANDIDATE → LEADER; single-node self-elects
    • Background health-check loop: per-backend consecutive_failures/consecutive_successes counters, configurable unhealthy_threshold/recovery_threshold, automatic failover + re-admission
    • 5 routing strategies: Round Robin, Least Connections, Nginx smooth Weighted Round Robin (persistent wrr_effective_weights_), Health-Based, FNV-1a Consistent Hash
    • Dynamic weight rebalancing: damped 10% adjustment toward inverse-load target when imbalance exceeds rebalance_threshold
    • Cross-DC routing: prefer_local_datacenter with fallback to all healthy backends
    • Idempotent start()/stop() via started_ atomic flag
RaftLoadBalancer::Config cfg;
cfg.strategy                 = LoadBalancingStrategy::LEAST_CONNECTIONS;
cfg.health_check_interval_ms = 5000;
cfg.rebalance_threshold      = 0.2;
cfg.datacenter               = "dc-west";
cfg.prefer_local_datacenter  = true;

RaftLoadBalancer lb(cfg);
lb.addBackend("node1:8766", 1.0, "dc-west");
lb.addBackend("node2:8766", 2.0, "dc-west");  // double capacity
lb.addBackend("node3:8766", 1.0, "dc-east");
lb.start();

auto addr   = lb.selectBackend();             // least-connections, local-DC preferred
auto sticky = lb.selectBackend(session_id);   // consistent hash for sticky routing
lb.onRequestComplete(addr, /*ok=*/true);

Build integration (audit fix)

  • cmake/ModularBuild.cmake — Added raft_load_balancer.cpp to THEMIS_NETWORK_SOURCES so the class is compiled into themis_core, not only in the test binary
  • tests/CMakeLists.txt — Replaced custom test block with add_network_focused_test macro (links against themis_core, no duplicate source compilation — consistent with all other focused network tests); fixed 3 pre-existing interleaved CMake if/endif blocks

Tests & CI

  • tests/test_raft_load_balancer.cpp — 26 tests covering all 14 acceptance criteria (AC1–AC14): leader election, failover, recovery, per-strategy routing, WRR distribution, consistent-hash determinism, cross-DC fallback, stats tracking
  • .github/workflows/load-balancing-raft-coordination-ci.yml — Matrix CI on gcc-12, clang-15, gcc-13

Type of Change

  • Bug fix
  • New feature
  • Refactoring
  • Documentation
  • Other:

Testing

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed

📚 Research & Knowledge (wenn applicable)

  • Diese PR basiert auf wissenschaftlichen Paper(s) oder Best Practices?
    • Falls JA: Research-Dateien in /docs/research/ angelegt?
    • Falls JA: Im Modul-README unter "Wissenschaftliche Grundlagen" verlinkt?
    • Falls JA: In /docs/research/implementation_influence/ eingetragen?

Relevante Quellen:

  • Paper:
  • Best Practice:
  • Architecture Decision:

Checklist

  • Code follows project style guidelines
  • Self-review completed
  • Documentation updated (if needed)
  • No new warnings introduced
Original prompt

This section details on the original issue you should resolve

<issue_title>Load Balancing with Raft Coordination</issue_title>
<issue_description>### Context

This issue implements the roadmap item 'Load Balancing with Raft Coordination' for the network domain. It is sourced from the consolidated roadmap under 🟠 High Priority — Near-term (v1.5.0 – v1.8.0) and targets milestone v1.8.0.

Primary detail section: Load Balancing with Raft Coordination

Goal

Deliver the scoped changes for Load Balancing with Raft Coordination in src/network/ and complete the linked detail section in a release-ready state for v1.8.0.

Detailed Scope

Load Balancing with Raft Coordination

Priority: High
Target Version: v1.8.0

Add Raft-based load balancing for distributed query routing.

Features:

  • Raft consensus for load balancer state
  • Automatic failover on node failures
  • Health-based routing decisions
  • Dynamic weight adjustment based on load
  • Cross-datacenter routing

Architecture:

┌─────────────────────────────────────────────────────┐
│          Raft Load Balancer Cluster                  │
│  ┌─────────┐  ┌─────────┐  ┌─────────┐             │
│  │Leader   │  │Follower │  │Follower │             │
│  │(active) │  │(standby)│  │(standby)│             │
│  └─────────┘  └─────────┘  └─────────┘             │
│       │              │             │                 │
│       │   (consensus on routing decisions)          │
│       │              │             │                 │
│       └──────────────┴─────────────┘                │
│                      │                               │
└──────────────────────┼───────────────────────────────┘
                       │
         ┌─────────────┼─────────────┐
         │             │             │
    ┌────▼────┐  ┌────▼────┐  ┌────▼────┐
    │ Shard 1 │  │ Shard 2 │  │ Shard 3 │
    │ (node1) │  │ (node2) │  │ (node3) │
    └─────────┘  └─────────┘  └─────────┘

API:

RaftLoadBalancer::Config config;
config.raft_port = 8774;
config.health_check_interval_ms = 5000;
config.rebalance_threshold = 0.2;  // 20% load imbalance

RaftLoadBalancer lb(config);
lb.add_backend("node1:8766", /*weight=*/1.0);
lb.add_backend("node2:8766", /*weight=*/1.0);
lb.add_backend("node3:8766", /*weight=*/1.0);
lb.start();

// Client-side
auto conn = lb.get_connection();
// Automatically routed to least loaded backend

Load Balancing Strategies:

  • Round Robin: Simple, predictable
  • Least Connections: Route to backend with fewest active connections
  • Weighted Round Robin: Distribute based on capacity weights
  • Health-Based: Exclude unhealthy backends
  • Consistent Hashing: Sticky routing for caching

Failover:

  • Raft leader monitors backend health
  • Automatic removal of failed backends
  • Automatic re-addition when backend recovers
  • Leader election on LB leader failure

Acceptance Criteria

  • Raft consensus for load balancer state
  • Automatic failover on node failures
  • Health-based routing decisions
  • Dynamic weight adjustment based on load
  • Cross-datacenter routing
  • Round Robin: Simple, predictable
  • Least Connections: Route to backend with fewest active connections
  • Weighted Round Robin: Distribute based on capacity weights
  • Health-Based: Exclude unhealthy backends
  • Consistent Hashing: Sticky routing for caching
  • Raft leader monitors backend health
  • Automatic removal of failed backends
  • Automatic re-addition when backend recovers
  • Leader election on LB leader failure

Relationships

References

  • src/ROADMAP.md
  • src/network/FUTURE_ENHANCEMENTS.md#load-balancing-with-raft-coordination
  • Source key: roadmap:78:network:v1.8.0:load-balancing-with-raft-coordination

Generated from the consolidated source roadmap. Keep the roadmap and issue in sync when scope changes.

</issue_description>

Comments on the Issue (you are @copilot in this section)


📍 Connect Copilot coding agent with Jira, Azure Boards or Linear to delegate work to Copilot in one click without leaving your project management tool.

Copilot AI and others added 2 commits March 15, 2026 09:45
…ssue #78)

- include/network/raft_load_balancer.h: Full header with Config, Backend, Stats,
  RaftRole and all 5 load-balancing strategies
- src/network/raft_load_balancer.cpp: Production implementation with health-check
  loop, Raft election loop, dynamic weight rebalancing, cross-DC routing
- tests/test_raft_load_balancer.cpp: 26 focused unit tests covering all 14 ACs
- tests/CMakeLists.txt: Add RaftLoadBalancerFocusedTests target + fix 3 pre-existing
  CMake parse errors (interleaved/unclosed blocks)
- .github/workflows/load-balancing-raft-coordination-ci.yml: CI workflow

Co-authored-by: makr-code <[email protected]>
- Remove dead code in AC2/AC3 health test cases (single lb instance)
- Fix start() double-start detection using separate started_ atomic flag
- Implement proper Nginx smooth weighted round-robin with persistent
  per-backend effective weights (wrr_effective_weights_ map)
- All 26 tests pass

Co-authored-by: makr-code <[email protected]>
Copilot AI changed the title [WIP] Add load balancing with Raft coordination for network domain feat(network): Load Balancing with Raft Coordination (v1.8.0) Mar 15, 2026
Copilot AI requested a review from makr-code March 15, 2026 09:51
…rk macro for tests

- cmake/ModularBuild.cmake: add raft_load_balancer.cpp to THEMIS_NETWORK_SOURCES
  so the class is compiled into themis_core (not only in the focused test binary)
- tests/CMakeLists.txt: replace custom test block with add_network_focused_test
  macro call — links against themis_core, removes duplicate source compilation,
  consistent with all other focused network tests

Co-authored-by: makr-code <[email protected]>
Copilot AI changed the title feat(network): Load Balancing with Raft Coordination (v1.8.0) feat(network): Raft-coordinated load balancer with all 5 routing strategies (v1.8.0, Issue #78) Mar 15, 2026
@makr-code
makr-code marked this pull request as ready for review March 15, 2026 10:31
@makr-code
makr-code merged commit 0b8106f into develop Mar 15, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Load Balancing with Raft Coordination

2 participants