---
title: "Preventing Infinite Delegation Loops: Setting max_turns and Hop Limits"
date: "2026-11-29T08:55:20+07:00"
description: "Protect your Google ADK agent swarms from runaway token costs and conversational deadlocks by implementing max_turns, hop counters, and circuit breakers."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-preventing-infinite-delegation-loops-max-turns.jpg"
alt: "Preventing Infinite Delegation Loops and Hop Limits in Google ADK"
tags: ['google-adk', 'multi-agent', 'guardrails', 'security', 'python']
---

In multi-agent systems where agents dynamically transfer control to one another, an insidious failure mode is the **Delegation Ping-Pong** (or infinite delegation loop). 

Consider two agents: a `SupportAgent` and a `BillingAgent`. If a user submits an ambiguous query ("Why was my service suspended due to an unpaid bill?"), `SupportAgent` decides it is a billing issue and transfers to `BillingAgent`. `BillingAgent` notices service configuration aspects and transfers back to `SupportAgent`. Without safety guardrails, this ping-pong loop can repeat dozens of times within seconds, draining thousands of dollars in API quotas and degrading system responsiveness.

In this tutorial, we will explore why delegation loops occur, how to enforce hard execution limits using `max_turns`, and how to build a custom `HopLimitMiddleware` circuit breaker in Google Agent Development Kit (ADK).

---

## 1. The Mechanics of Delegation Loops

In Google ADK, an agent turn occurs whenever an agent or sub-agent processes input and yields events. A multi-agent delegation is a sequence of turns without human intervention:

```
[User Message]
      │
      ▼
┌──────────────┐   Turn 1: "I need Billing help"    ┌──────────────┐
│ SupportAgent │ ──────────────────────────────────►│ BillingAgent │
└──────────────┘                                    └──────────────┘
       ▲                                                   │
       │           Turn 2: "Actually, it's IT support"     │
       └───────────────────────────────────────────────────┘
       │                                                   ▲
       │           Turn 3: "No, check payment terms"       │
       └───────────────────────────────────────────────────┘
                           (INFINITE LOOP!)
```

Without a hop ceiling, the runner continues executing until the hosting environment times out (e.g., Cloud Run 60-minute deadline), incurring massive model inference bills.

---

## 2. Setting `max_turns` in ADK Runners

Google ADK provides native turn control at the `Runner` level. Setting `max_turns` guarantees that the execution loop terminates deterministically regardless of how many transfers sub-agents attempt:

```python
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService

runner = Runner(
    agent=root_coordinator,
    session_service=InMemorySessionService(),
    # Hard cutoff on total agent turns per user interaction
    max_turns=6,
)
```

If the fleet exceeds 6 turns without returning a final response to the user, the `Runner` immediately breaks the execution loop and yields a graceful termination event.

---

## 3. Implementing a Granular Hop-Counter Callback

While a global `max_turns` limit prevents complete server lockups, you often want more granular control—such as detecting when two specific agents have ping-ponged more than twice, or logging an alert before the ceiling is hit.

ADK's `before_agent_callback` allows you to inspect the agent lifecycle on every single handoff:

```python
from typing import Dict, Any
from google.adk.agents import Agent
from google.adk.agents.invocation_context import InvocationContext

class HopLimitEnforcer:
    """Tracks agent transfers and halts execution if hop limits are exceeded."""

    def __init__(self, max_hops: int = 5):
        self.max_hops = max_hops

    def before_agent_hook(
        self, agent: Agent, ctx: InvocationContext
    ) -> None:
        # Retrieve or initialize hop counter for the current user interaction
        current_hops = ctx.session.state.get("_agent_transfer_hops", 0)
        history = ctx.session.state.get("_agent_transfer_history", [])

        current_hops += 1
        history.append(agent.name)

        ctx.session.state["_agent_transfer_hops"] = current_hops
        ctx.session.state["_agent_transfer_history"] = history

        print(f"[HOP {current_hops}/{self.max_hops}] Routing into: {agent.name}")

        # Check for ping-pong between the same two agents
        if len(history) >= 4:
            if history[-1] == history[-3] and history[-2] == history[-4]:
                raise RuntimeError(
                    f"Delegation Ping-Pong Detected! Alternating between '{history[-1]}' and '{history[-2]}'."
                )

        # Check for overall hop ceiling
        if current_hops > self.max_hops:
            raise RuntimeError(
                f"Delegation Hop Limit Exceeded! Fleet reached {current_hops} hops without resolution."
            )

hop_enforcer = HopLimitEnforcer(max_hops=4)
```

---

## 4. Building the Self-Protected Multi-Agent Fleet

Let's assemble a fleet equipped with hop limits:

```python
import asyncio
from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService

# Sub-Agent A
agent_a = Agent(
    name="triage_agent",
    model="gemini-3.8-flash",
    description="Analyzes incoming requests and classifies them.",
    instruction="""
    If the question involves payments, delegate to billing_agent.
    """,
    before_agent_callback=hop_enforcer.before_agent_hook,
)

# Sub-Agent B
agent_b = Agent(
    name="billing_agent",
    model="gemini-3.8-flash",
    description="Handles accounts and billing disputes.",
    instruction="""
    If the question mentions general terms or policy, delegate to triage_agent.
    """,
    before_agent_callback=hop_enforcer.before_agent_hook,
)

# Connect cross-delegations (potential loop hazard)
agent_a.sub_agents = [agent_b]
agent_b.sub_agents = [agent_a]
```

---

## 5. Simulating an Ambiguous Query and Circuit Breaker

Now, let's execute a prompt specifically designed to induce circular delegation and observe how the circuit breaker intercepts the condition:

```python
async def main():
    session_service = InMemorySessionService()
    runner = Runner(agent=agent_a, session_service=session_service, max_turns=6)
    session = await session_service.get_or_create("loop_test_session")

    ambiguous_prompt = (
        "Is my account payment status governed by standard general support policy?"
    )

    print("Executing ambiguous prompt...\n")
    try:
        async for event in runner.run_async(session=session, message=ambiguous_prompt):
            if event.content and event.content.parts:
                print(f"[{event.author}]: {event.content.parts[0].text}")

    except RuntimeError as exc:
        print(f"\n🛑 CIRCUIT BREAKER TRIGGERED: {str(exc)}")
        print("Transfer History:", session.state.get("_agent_transfer_history"))

        # Deliver a safe, graceful fallback to the end user
        fallback_msg = (
            "I apologize, but our automated assistants were unable to resolve your inquiry. "
            "Your ticket has been flagged for human support review."
        )
        print(f"\nUser Display: {fallback_msg}")

if __name__ == "__main__":
    asyncio.run(main())
```

---

## 6. Production Safety Architecture

| Layer | Guardrail Mechanism | Purpose |
| :--- | :--- | :--- |
| **Layer 1: Runner** | `max_turns=N` | Global safety net; kills execution if model turns exceed $N$. |
| **Layer 2: Callback** | `HopLimitEnforcer` | Detects rapid $A \leftrightarrow B$ ping-pong cycles and raises fast alerts. |
| **Layer 3: Topologies** | `disallow_transfer_to_peers` | Eliminates lateral transfers structurally so loops are physically impossible. |
| **Layer 4: Fallback** | User-facing catch block | Converts technical loop errors into clean human escalation notices. |

**Takeaway:** Never deploy open multi-agent delegation fleets without strict `max_turns` bounds and hop-limit circuit breakers. Protecting your application against delegation loops preserves your budget and guarantees predictable response times.

## Sources
- Google ADK Documentation: https://adk.dev/
- Google GenAI SDK: https://github.com/googleapis/python-genai
- Google Cloud Run Best Practices: https://cloud.google.com/run/docs/best-practices
