# RoundRobin

**RoundRobin** distributes tasks evenly across agents or chains to maximize efficiency—ideal for high-frequency DeFi trades, payroll processing, or cross-chain operations. It minimizes latency and avoids chain congestion by cycling through available resources, ensuring scalable Web3 automation with enterprise-grade reliability.

***

#### **Core Components**

**1. Task Distributor**

* Cyclically assigns tasks to agents/chains (e.g., Ethereum → Polygon → Solana).
* Prioritizes based on real-time metrics (gas fees, latency, liquidity).

**2. Agent Pool**

| Agent Type          | Function                                  |
| ------------------- | ----------------------------------------- |
| **Execution Agent** | Processes transactions on assigned chain. |
| **Chain Optimizer** | Selects optimal chain for next task.      |
| **Load Monitor**    | Tracks agent health and throughput.       |

**3. Fallback Protocol**

* Auto-skips overloaded agents/chains.
* Retries failed tasks 3x before escalating.

***

#### **Workflow**

```mermaid
sequenceDiagram  
    User->>AgentGPT: "Process 50K Transactions"  
    AgentGPT->>RoundRobinEngine: Assign Tasks  
    RoundRobinEngine->>ExecutionAgent1: Task 1 (Ethereum)  
    RoundRobinEngine->>ExecutionAgent2: Task 2 (Polygon)  
    RoundRobinEngine->>ExecutionAgent3: Task 3 (Solana)  
    ExecutionAgent1-->>User: Confirmed (0.9s)  
    ExecutionAgent2-->>User: Confirmed (0.7s)  
    ExecutionAgent3-->>User: Failed → Retry on Arbitrum  
```

***

#### **Logic Code Example**

```python
from agentgpt.architectures import RoundRobinAgent  
from agentgpt.web3 import ERC7645, ChainOptimizer  
from typing import List, Dict  

class HighFrequencyTrader(RoundRobinAgent):  
    def __init__(self, agents: List[str]):  
        super().__init__(agents=agents, retries=3)  
        self.chain_optimizer = ChainOptimizer()  
        self.executor = ERC7645()  

    def distribute_tasks(self, tasks: List[Dict]) -> List[str]:  
        # Assign tasks cyclically to agents/chains  
        assignments = []  
        for i, task in enumerate(tasks):  
            agent = self.agents[i % len(self.agents)]  
            chain = self.chain_optimizer.recommend_chain()  
            assignments.append({"agent": agent, "chain": chain})  
        return assignments  

    def execute(self, tasks: List[Dict]):  
        assignments = self.distribute_tasks(tasks)  
        for assignment in assignments:  
            try:  
                tx_hash = self.executor.execute(  
                    assignment["agent"],  
                    assignment["chain"],  
                    task["amount"],  
                    gas_limit=200000  
                )  
                self.zk_audit.log_task(assignment, tx_hash)  
            except Exception as e:  
                self.retry_or_fallback(task, e)  

    def retry_or_fallback(self, task: Dict, error: Exception):  
        for _ in range(self.retries):  
            new_chain = self.chain_optimizer.fallback_chain()  
            try:  
                tx_hash = self.executor.execute(  
                    self.agents[self.current_agent_index],  
                    new_chain,  
                    task["amount"]  
                )  
                return tx_hash  
            except:  
                continue  
        self.alert_human_operator(task, error)  

# Usage  
agents = ["ExecutionAgent1", "ExecutionAgent2", "ExecutionAgent3"]  
trader = HighFrequencyTrader(agents)  
tasks = [{"amount": 1000}, {"amount": 2500}, {"amount": 5000}]  # USDC amounts  
trader.execute(tasks)  
```

***

#### **Key Features**

**1. Dynamic Agent Weighting**

Adjust agent priority based on performance:

```python
trader.set_agent_priority("ExecutionAgent1", weight=2.0)  # Higher load capacity  
```

**2. Chain-Aware Scheduling**

Route tasks to chains with lowest gas:

```python
chain = self.chain_optimizer.select_chain(min_gwei=30, min_liquidity=1e6)  
```

**3. Auto-Scaling**

Add/remove agents dynamically during peak loads:

```python
trader.add_agent("ExecutionAgent4")  
trader.remove_agent("ExecutionAgent2")  
```

***

#### **Enterprise Use Cases**

**1. DeFi Arbitrage**

* Distributes 1,200+ swaps/hour across Uniswap, PancakeSwap, and Curve.
* Achieves 94% success rate with MEV protection.

**2. Enterprise Payroll Processing**

* Processes 250,000+ salaries/hour across Ethereum, Polygon, and Base.
* Reduces costs by 72% vs single-chain execution.

***

#### **Performance Metrics**

| **Metric**          | **Result**    |
| ------------------- | ------------- |
| Transactions/Minute | 890           |
| Success Rate        | 97.5%         |
| Load Distribution   | ±3% fairness  |
| Cost Savings        | 65% vs static |

***

#### **Implementation Guide**

**1. CLI Quickstart**

Deploy a RoundRobin workflow for payroll:

```bash
agentgpt-cli create-roundrobin \  
  --name "EnterprisePayroll" \  
  --agents Agent1,Agent2,Agent3 \  
  --chains ethereum,polygon,arbitrum  
```

**2. Best Practices**

* Pre-warm agents during off-peak hours.
* Set gas limits 15% higher than average to avoid retries.

***

#### **Limitations**

* **Latency**: Adds \~0.4s/transaction vs direct execution.
* **Infrastructure Cost**: Requires 3x agent redundancy.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://agent-gpt.gitbook.io/agent-gpt/agentgpt-architectures/architectures-available/roundrobin.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
