Understanding Sub-agent maxTurns Limits in Claude Code: Preventing Infinite Loops
The maxTurns parameter in Claude Code sub-agent front-matter caps the number of autonomous iterations an agent can execute, automatically terminating the agent when the limit is reached to prevent runaway loops and uncontrolled resource consumption.
Claude Code's sub-agent architecture enables autonomous task execution, but without boundaries, these agents can spiral into infinite loops. This guide examines the maxTurns limit mechanism implemented in the shanraisshan/claude-code-best-practice repository to help you configure safe, predictable agentic workflows.
What Are Sub-agent Turns?
A turn represents a single autonomous iteration where a sub-agent may invoke a tool, execute a skill, or spawn another sub-agent. When you configure maxTurns: 5 in an agent's front-matter, you authorize exactly five such iterations before forced termination.
This counting mechanism differs from wall-clock time; an agent could complete five turns in seconds or minutes depending on tool latency. The limit focuses on interaction depth rather than duration, making it deterministic and resource-predictable.
Why maxTurns Limits Matter
Preventing runaway execution is the primary function. Without a ceiling, a sub-agent trapped in a faulty logic loop—for example, repeatedly calling a search tool with slightly modified queries—could exhaust API quotas and hang the session indefinitely.
Resource predictability follows as a direct benefit. Each turn potentially consumes compute, memory, and API calls. Bounding the count allows precise budget enforcement and prevents cost explosions from recursive agent spawning.
Safety guards for recursive architectures become essential when agents invoke themselves directly or indirectly. The maxTurns limit acts as a circuit breaker, forcing termination after a configured depth even if recursion logic contains errors.
How the Limit Is Enforced
When a sub-agent's front-matter contains a maxTurns integer, Claude Code maintains an internal counter tracking completed turns. Upon reaching the specified value, the system automatically stops the agent and returns a "sub-agent stopped due to maxTurns" status to the surrounding command or skill.
This termination is non-negotiable; the agent cannot override its own limit. The parent context receives control and may decide to retry with adjusted parameters, fallback to alternative logic, or surface the timeout to the user.
Recommended maxTurns Values by Use Case
According to the best practices defined in best-practice/claude-subagents.md, configure limits based on task complexity:
Simple, deterministic tasks — 1 to 3 turns
Use this range for agents performing linear operations like fetching a single API value and formatting it. The agent needs only fetch, parse, and return—minimal interaction surface.
Multi-step workflows — 5 to 10 turns
Complex sequences such as fetching weather data and generating SVG visualizations require multiple phases. The repository's .claude/agents/weather-agent.md example uses maxTurns: 5 to accommodate data retrieval and rendering while capping runaway loops.
Exploratory or search-heavy agents — 10 to 20 turns
Code-base explorers performing repeated Read, Glob, or Grep calls need more iterations. Allow enough turns for iterative refinement, but maintain a ceiling to prevent endless crawling through large repositories.
Recursive agents — 3 to 5 turns
When an agent might invoke itself or similar agents, keep recursion shallow. The .claude/agents/time-agent.md example caps at maxTurns: 3 to handle simple time-display tasks without risking deep recursive chains.
Long-running background agents — omit or use external scheduling
For monitoring agents triggered by timers rather than turn counts, omit maxTurns or rely on external schedulers to manage lifecycle.
Best Practices from the Source Documentation
The best-practice/claude-subagents.md file establishes several critical guidelines:
maxTurnsis optional — If omitted, the sub-agent runs until it explicitly finishes or an external stop occurs.- Use conservative values for agents invoked repeatedly by users or other agents to prevent cumulative resource drain.
- Pair limits with clear exit messages in the agent body so callers understand why termination occurred.
- Define in front-matter — The parameter belongs in the YAML header table, not the agent logic body.
Implementation Examples
Capping Simple Tasks at 2 Turns
For deterministic fetch-and-format operations, keep the limit tight:
# .claude/agents/simple-fetch.md
---
name: simple-fetch
description: Fetch a JSON endpoint and extract a field.
tools: WebFetch, Read, Write
model: haiku
maxTurns: 2 # ← stop after two interactions
permissionMode: acceptEdits
---
# Agent body ...
Turn 1: WebFetch the URL.
Turn 2: Read the response, extract the field, Write the result.
If the endpoint is unreachable, the agent stops after the second turn rather than entering an infinite retry loop.
Limiting Exploratory Search to 12 Turns
For recursive code exploration, allow sufficient depth while preventing runaway execution:
# .claude/agents/code-explorer.md
---
name: code-explorer
description: PROACTIVELY explore the repo for a pattern.
tools: Glob, Grep, Read, Write
model: sonnet
maxTurns: 12 # Allows a few rounds of searching but caps recursion
permissionMode: acceptEdits
---
# Agent logic: repeat
# 1️⃣ Glob for files
# 2️⃣ Grep pattern
# 3️⃣ If not found, adjust query and loop
# Loop stops automatically after 12 turns.
Detecting Termination in Parent Commands
The calling context should handle maxTurns exhaustion gracefully. In reports/claude-agent-command-skill.md, patterns show how to check agent exit status:
```yaml
# .claude/commands/run-explorer.md
---
description: Run the code-explorer agent on a pattern.
allowed-tools: Agent
maxTurns: 1
---
{{#if (Agent "code-explorer" description="Search for '{{input}}'" )}}
{{else}}
⚠️ **Agent stopped** – it reached its `maxTurns` limit. Consider increasing the limit or refining the query.
{{/if}}
This pattern surfaces the termination reason to the user, enabling informed decisions about retry strategies.
## Key Files in the Repository
Understanding the `maxTurns` implementation requires familiarity with these specific files:
- **[`best-practice/claude-subagents.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/best-practice/claude-subagents.md)** — Defines the complete front-matter specification for sub-agents, including the `maxTurns` field syntax and validation rules.
- **[`.claude/agents/weather-agent.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/.claude/agents/weather-agent.md)** — Production example demonstrating `maxTurns: 5` for a multi-step weather visualization workflow.
- **[`.claude/agents/time-agent.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/.claude/agents/time-agent.md)** — Minimal example showing `maxTurns: 3` for a simple, non-recursive time-display task.
- **[`implementation/claude-subagents-implementation.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/implementation/claude-subagents-implementation.md)** — Walkthrough of agent creation covering `maxTurns` configuration trade-offs.
- **[`reports/claude-agent-command-skill.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/reports/claude-agent-command-skill.md)** — Comparative analysis of front-matter across Commands, Agents, and Skills, including a reference to `maxTurns: 10` usage patterns.
## Summary
- The `maxTurns` parameter in sub-agent front-matter defines the maximum number of autonomous turns before forced termination.
- Turns represent discrete iterations of tool invocation, skill execution, or sub-agent spawning.
- Values range from 1–3 for simple tasks up to 10–20 for exploratory agents, with recursive agents capped at 3–5 turns.
- The limit prevents infinite loops, controls resource consumption, and acts as a safety guard for recursive architectures.
- When the limit triggers, the parent command receives a termination status and should implement fallback logic or user notification.
## Frequently Asked Questions
### What happens when a sub-agent reaches its maxTurns limit?
Claude Code automatically terminates the agent and returns a "sub-agent stopped due to maxTurns" status to the calling context. The agent cannot override this limit, and any incomplete work remains unfinished unless the parent implements retry logic.
### Is maxTurns required for every sub-agent?
No. According to the documentation in [`best-practice/claude-subagents.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/best-practice/claude-subagents.md), `maxTurns` is optional. If omitted, the agent runs until it explicitly signals completion or an external process terminates it. Omit only for background agents or explicitly managed long-running processes.
### How do I choose the right maxTurns value?
Base your selection on task complexity and recursion risk. Use 1–3 turns for linear data fetching, 5–10 for multi-step workflows like the weather agent example, and 10–20 for search-heavy exploration. Always use conservative values (3–5) for agents that might spawn themselves or be called frequently by other agents.
### Can a sub-agent detect how many turns it has remaining?
No. The turn counter is internal to Claude Code's execution engine and not exposed to agent logic. Design your agents to complete primary objectives within the allocated turns, and use the parent command to handle gracefully when the limit triggers before completion.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →