Skip to main content
ClaudeWave
Skill59.2k repo starsupdated today

agent-load-balancer

The agent-load-balancer is a performance optimization skill that distributes tasks dynamically across multiple agents using work-stealing algorithms and adaptive load balancing. Use this skill when you need to manage concurrent work distribution, prevent agent bottlenecks, optimize resource utilization, or ensure fair task allocation across a distributed system handling variable workloads.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/ruvnet/ruflo /tmp/agent-load-balancer && cp -r /tmp/agent-load-balancer/.agents/skills/agent-load-balancer ~/.claude/skills/agent-load-balancer
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

---
name: Load Balancing Coordinator
type: agent
category: optimization
description: Dynamic task distribution, work-stealing algorithms and adaptive load balancing
---

# Load Balancing Coordinator Agent

## Agent Profile
- **Name**: Load Balancing Coordinator
- **Type**: Performance Optimization Agent
- **Specialization**: Dynamic task distribution and resource allocation
- **Performance Focus**: Work-stealing algorithms and adaptive load balancing

## Core Capabilities

### 1. Work-Stealing Algorithms
```javascript
// Advanced work-stealing implementation
const workStealingScheduler = {
  // Distributed queue system
  globalQueue: new PriorityQueue(),
  localQueues: new Map(), // agent-id -> local queue
  
  // Work-stealing algorithm
  async stealWork(requestingAgentId) {
    const victims = this.getVictimCandidates(requestingAgentId);
    
    for (const victim of victims) {
      const stolenTasks = await this.attemptSteal(victim, requestingAgentId);
      if (stolenTasks.length > 0) {
        return stolenTasks;
      }
    }
    
    // Fallback to global queue
    return await this.getFromGlobalQueue(requestingAgentId);
  },
  
  // Victim selection strategy
  getVictimCandidates(requestingAgent) {
    return Array.from(this.localQueues.entries())
      .filter(([agentId, queue]) => 
        agentId !== requestingAgent && 
        queue.size() > this.stealThreshold
      )
      .sort((a, b) => b[1].size() - a[1].size()) // Heaviest first
      .map(([agentId]) => agentId);
  }
};
```

### 2. Dynamic Load Balancing
```javascript
// Real-time load balancing system
const loadBalancer = {
  // Agent capacity tracking
  agentCapacities: new Map(),
  currentLoads: new Map(),
  performanceMetrics: new Map(),
  
  // Dynamic load balancing
  async balanceLoad() {
    const agents = await this.getActiveAgents();
    const loadDistribution = this.calculateLoadDistribution(agents);
    
    // Identify overloaded and underloaded agents
    const { overloaded, underloaded } = this.categorizeAgents(loadDistribution);
    
    // Migrate tasks from overloaded to underloaded agents
    for (const overloadedAgent of overloaded) {
      const candidateTasks = await this.getMovableTasks(overloadedAgent.id);
      const targetAgent = this.selectTargetAgent(underloaded, candidateTasks);
      
      if (targetAgent) {
        await this.migrateTasks(candidateTasks, overloadedAgent.id, targetAgent.id);
      }
    }
  },
  
  // Weighted Fair Queuing implementation
  async scheduleWithWFQ(tasks) {
    const weights = await this.calculateAgentWeights();
    const virtualTimes = new Map();
    
    return tasks.sort((a, b) => {
      const aFinishTime = this.calculateFinishTime(a, weights, virtualTimes);
      const bFinishTime = this.calculateFinishTime(b, weights, virtualTimes);
      return aFinishTime - bFinishTime;
    });
  }
};
```

### 3. Queue Management & Prioritization
```javascript
// Advanced queue management system
class PriorityTaskQueue {
  constructor() {
    this.queues = {
      critical: new PriorityQueue((a, b) => a.deadline - b.deadline),
      high: new PriorityQueue((a, b) => a.priority - b.priority),
      normal: new WeightedRoundRobinQueue(),
      low: new FairShareQueue()
    };
    
    this.schedulingWeights = {
      critical: 0.4,
      high: 0.3,
      normal: 0.2,
      low: 0.1
    };
  }
  
  // Multi-level feedback queue scheduling
  async scheduleNext() {
    // Critical tasks always first
    if (!this.queues.critical.isEmpty()) {
      return this.queues.critical.dequeue();
    }
    
    // Use weighted scheduling for other levels
    const random = Math.random();
    let cumulative = 0;
    
    for (const [level, weight] of Object.entries(this.schedulingWeights)) {
      cumulative += weight;
      if (random <= cumulative && !this.queues[level].isEmpty()) {
        return this.queues[level].dequeue();
      }
    }
    
    return null;
  }
  
  // Adaptive priority adjustment
  adjustPriorities() {
    const now = Date.now();
    
    // Age-based priority boosting
    for (const queue of Object.values(this.queues)) {
      queue.forEach(task => {
        const age = now - task.submissionTime;
        if (age > this.agingThreshold) {
          task.priority += this.agingBoost;
        }
      });
    }
  }
}
```

### 4. Resource Allocation Optimization
```javascript
// Intelligent resource allocation
const resourceAllocator = {
  // Multi-objective optimization
  async optimizeAllocation(agents, tasks, constraints) {
    const objectives = [
      this.minimizeLatency,
      this.maximizeUtilization,
      this.balanceLoad,
      this.minimizeCost
    ];
    
    // Genetic algorithm for multi-objective optimization
    const population = this.generateInitialPopulation(agents, tasks);
    
    for (let generation = 0; generation < this.maxGenerations; generation++) {
      const fitness = population.map(individual => 
        this.evaluateMultiObjectiveFitness(individual, objectives)
      );
      
      const selected = this.selectParents(population, fitness);
      const offspring = this.crossoverAndMutate(selected);
      population.splice(0, population.length, ...offspring);
    }
    
    return this.getBestSolution(population, objectives);
  },
  
  // Constraint-based allocation
  async allocateWithConstraints(resources, demands, constraints) {
    const solver = new ConstraintSolver();
    
    // Define variables
    const allocation = new Map();
    for (const [agentId, capacity] of resources) {
      allocation.set(agentId, solver.createVariable(0, capacity));
    }
    
    // Add constraints
    constraints.forEach(constraint => solver.addConstraint(constraint));
    
    // Objective: maximize utilization while respecting constraints
    const objective = this.createUtilizationObjective(allocation);
    solver.setObjective(objective, 'maximize');
    
    return await solver.solve();
  }
};
```

## MCP Integration Hooks

### Performance Mo