---
title: "Cost-Controlled Multi-Agent Fleet"
domain: "Multi-Agent Systems"
summary: "Patterns for fanning work out to parallel agents without file collisions, runaway spend, or lost cost visibility."
url: "https://agentic-patterns.com/packs/cost-controlled-multi-agent-fleet"
markdown_url: "https://agentic-patterns.com/packs/cost-controlled-multi-agent-fleet.md"
pattern_count: 6
---

# Cost-Controlled Multi-Agent Fleet

> Patterns for fanning work out to parallel agents without file collisions, runaway spend, or lost cost visibility.

**Domain:** Multi-Agent Systems

## How to apply this stack with a coding agent

```text
Apply the "Cost-Controlled Multi-Agent Fleet" pattern pack to this repository.
Check each pattern's "Use when" and "Avoid when" conditions against our codebase,
identify gaps in order of risk, and list the files to update before making edits.
```

## Patterns in this pack

1. **Sub-Agent Spawning** — Lets the main agent spawn sub-agents with fresh context and scoped tools to work on subtasks in parallel, then merges their results ([page](https://agentic-patterns.com/patterns/sub-agent-spawning) | [.md](https://agentic-patterns.com/patterns/sub-agent-spawning.md))
2. **Design-Time File Partition as Concurrency Control** — Each task declares every path it will write; overlapping tasks get a blocking dependency so only disjoint work runs at once on a shared checkout ([page](https://agentic-patterns.com/patterns/design-time-file-partition) | [.md](https://agentic-patterns.com/patterns/design-time-file-partition.md))
3. **Lane-Based Execution Queueing** — Routes work into named lanes, each with its own queue and concurrency limit, so sessions never interleave and background jobs never block users ([page](https://agentic-patterns.com/patterns/lane-based-execution-queueing) | [.md](https://agentic-patterns.com/patterns/lane-based-execution-queueing.md))
4. **Budget-Aware Model Routing with Hard Cost Caps** — Routes each request to the cheapest model that meets its needs under hard cost caps, and escalates only when quality gates fail ([page](https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps) | [.md](https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps.md))
5. **Agent Circuit Breaker** — Prevents agents from wasting tokens and time on repeatedly failing tools by tracking failure rates and temporarily disabling broken tool endpoints ([page](https://agentic-patterns.com/patterns/agent-circuit-breaker) | [.md](https://agentic-patterns.com/patterns/agent-circuit-breaker.md))
6. **Intent-Level Cost Attribution** — Records every LLM call against the projectId/intentId/user key that caused it, at call time, so spend can be queried and enforced per work item instead of as an opaque total ([page](https://agentic-patterns.com/patterns/intent-level-cost-attribution) | [.md](https://agentic-patterns.com/patterns/intent-level-cost-attribution.md))

---

## Sub-Agent Spawning

- URL: https://agentic-patterns.com/patterns/sub-agent-spawning
- Markdown: https://agentic-patterns.com/patterns/sub-agent-spawning.md
- Category: Orchestration & Control | Status: foundational

> Lets the main agent spawn sub-agents with fresh context and scoped tools to work on subtasks in parallel, then merges their results

### Use when

- Large multi-file task overflows the main agent's context
- Subtasks are independent and can run in parallel
- Some work needs isolated tools or files for safety

### Avoid when

- Small task that fits in one context window
- Subtasks depend on each other and need tight coordination
- Token budget cannot cover several agents at once

<details>
<summary>Full pattern specification</summary>

---
title: "Sub-Agent Spawning"
summary: "Lets the main agent spawn sub-agents with fresh context and scoped tools to work on subtasks in parallel, then merges their results"
status: "foundational"
category: "Orchestration & Control"
url: "https://agentic-patterns.com/patterns/sub-agent-spawning"
source: "https://lethain.com/agents-subagents/"
authors: ["Nikola Balic (@nibzard)"]
tags: ["orchestration","context","scalability","subagents","yaml-configuration","virtual-files","subject-hygiene","parallel-delegation"]
signals: ["Large multi-file task overflows the main agent's context","Subtasks are independent and can run in parallel","Some work needs isolated tools or files for safety"]
anti_signals: ["Small task that fits in one context window","Subtasks depend on each other and need tight coordination","Token budget cannot cover several agents at once"]
updated_at: "2026-10-13"
---

# Sub-Agent Spawning

> Lets the main agent spawn sub-agents with fresh context and scoped tools to work on subtasks in parallel, then merges their results

## Use when

- Large multi-file task overflows the main agent's context
- Subtasks are independent and can run in parallel
- Some work needs isolated tools or files for safety

## Avoid when

- Small task that fits in one context window
- Subtasks depend on each other and need tight coordination
- Token budget cannot cover several agents at once

## Problem

Large multi-file tasks blow out the main agent's context window and reasoning budget. You need a way to delegate work to specialized agents with isolated contexts and tools.

## Solution

Let the main agent **spawn focused sub-agents**, each with its own fresh context, to work in parallel on shardable subtasks. Aggregate their results when done.

**Critical requirement**: each subagent invocation must have a clear, specific task subject for traceability. Empty or generic subjects make parallel work untraceable and synthesis difficult. See [Subject Hygiene](subject-hygiene.md) for details.

### 1. Declarative YAML configuration

Define subagent types in configuration files with their own system prompts, allowed tools, and context windows:

```yaml
# agents.yaml: which subagents each agent may spawn
subagents:
  planning:
    file: subagents/planning.yaml
    allowed_in: [main_agent, research_agent]
  think:
    file: subagents/think.yaml
    allowed_in: [main_agent]

# subagents/planning.yaml: the subagent's own prompt and tools
name: planning
system_prompt: "Break down complex tasks into steps..."
tools: [list_files, read_file]   # or inherit: all (from the parent agent)

# subagents/think.yaml
name: think
system_prompt: "Analyze and refine reasoning..."
tools: [read_file, search]
```

The main agent invokes a subagent through a dedicated tool, `subagent(agent_name, prompt, files)`, which gives:

- **Virtual file isolation**: the subagent sees only the files explicitly passed to it
- **Tool scoping**: subagents can inherit all parent tools or use a subset
- **Specialized system prompts**: each subagent type has predefined behavior

### 2. Dynamic spawning for parallel work

Spawn subagents on demand for parallel task execution:

```pseudo
# Main agent creates a todo list
files = glob("**/*.md")
batches = chunk(files, 9)

# Spawn subagents for each batch IN PARALLEL
for batch in batches:
    spawn_subagent(
        task="Update YAML front-matter in markdown files",  # Clear, specific subject
        files=batch,
        context=instructions
    )
# All subagents run concurrently, not sequentially
```

**Parallel delegation best practices:**

- **Launch independent tasks simultaneously**: do not explore A, then B, then C sequentially
- **Use clear task subjects**: each subagent needs a traceable identity (see [Subject Hygiene](subject-hygiene.md))
- **Plan synthesis upfront**: define how the main agent will combine the subagent findings
- **Limit to 2-4 subagents**: the observed maximum in effective sessions; more adds coordination overhead

Recent developments show that improved agent [state externalization capabilities](proactive-agent-state-externalization.md) may make subagent delegation more practical, because they help agents better identify which tasks suit delegation and how to communicate the necessary context to subagents.

### Example: YAML front-matter refactor

```mermaid
sequenceDiagram
  MainAgent->>GlobTool: "*.md"
  MainAgent->>TaskTool: spawn 4 sub-agents with 9 files each

  par Parallel subagents (launched together)
      MainAgent->>SubAgent1: "Update front-matter: batch 1"
      MainAgent->>SubAgent2: "Update front-matter: batch 2"
      MainAgent->>SubAgent3: "Update front-matter: batch 3"
      MainAgent->>SubAgent4: "Update front-matter: batch 4"
  end

  par Each works independently
      SubAgent1->>Files: update batch 1
      SubAgent2->>Files: update batch 2
      SubAgent3->>Files: update batch 3
      SubAgent4->>Files: update batch 4
  end

  MainAgent->>Git: merge branches ➜ single PR
```

**Real-world example from nibzard-web:** four parallel subagents launched simultaneously:

- `"Newsletter component exploration"` → agent-a7911db
- `"Modal pattern discovery"` → agent-adeac17
- `"Search implementation research"` → agent-a03b9c9
- `"Log page analysis"` → agent-b84c3d1

The main agent synthesized the findings and implemented a unified approach.

## How to use it

**Use cases for subagents:**

1. **Context window management**: upload large files to a subagent, extract the specific data, and return a summary to the main agent
2. **Concurrent work**: run several subagents in parallel and join on completion, which reduces clock-time for I/O-bound workflows because network API calls can happen simultaneously
3. **Code-driven LLM invocation**: a code workflow calls the subagent, the subagent makes an LLM-powered decision, and control returns to the code with the result
4. **Security isolation**: separate tools and contexts in mutually isolated subagents, so external resource retrieval stays apart from internal access and the blast radius of sensitive operations shrinks

**Virtual file passing:**

```pseudo
# Main agent
result = subagent(
    agent_name="planning",
    prompt="Analyze these files and create migration plan",
    files=["file1.ts", "file2.ts", "file3.ts"]
)
# Only these 3 files are visible to the planning subagent
```

**Recursive architecture:** some implementations treat every agent as a subagent, which enables flexible composition and consistent behavior across the system.

**Swarm migrations:** for massive parallelization (10+ subagents) and large-scale code migrations, see the [Swarm Migration Pattern](swarm-migration-pattern.md).

**Failure modes / gotchas:**

- **Generic subjects:** an empty or generic task subject makes parallel work untraceable and synthesis difficult. Give each subagent task a clear, specific subject.
- **Sequential launches:** exploring A, then B, then C removes the latency benefit. Launch independent tasks simultaneously.
- **Unplanned synthesis:** without a defined way to combine findings, the main agent must merge conflicting results ad hoc. Plan the synthesis before you spawn.
- **Too many subagents:** more than 2-4 subagents adds coordination overhead.
- **Subagents by default:** the source author reports, "frequently thought we needed subagents, then found more natural alternative". Look for the simpler design first.

## Trade-offs

**Pros:**

- **Context isolation**: each subagent has a clean context window
- **Parallelization**: concurrent execution reduces workflow latency
- **Specialization**: different subagent types for different tasks (planning, thinking, analysis)
- **Virtual files**: precise control over what each subagent can see
- **Tool scoping**: limit subagent capabilities for security and simplicity
- **Declarative config**: reusable subagent definitions through YAML

**Cons:**

- **Overhead**: spawning and coordinating subagents adds complexity
- **Cost**: running multiple agents simultaneously increases token usage
- **Coordination**: the main agent must track and aggregate subagent results
- **Not always necessary**: see the "found more natural alternative" note above
- **Latency visibility**: user-facing latency is an "invisible feature" until it becomes problematic

**When subagents matter most:** context window management (large file processing), I/O-bound workflows (network API calls), code-driven workflows that need LLM delegation, and massive parallelization (10+ concurrent agents).

## References

* Claude Code documentation, [Create custom subagents](https://code.claude.com/docs/en/subagents) - the official subagent configuration reference
* Vezhnevets, A., et al. (2017). [FeUdal Networks for Hierarchical Reinforcement Learning](https://arxiv.org/abs/1703.01161). ICML. - Manager-worker separation with goal-setting in latent space
* Raising An Agent - Episode 6: Claude 4 Sonnet edits 36 blog posts via four sub-agents.
* Boris Cherny (Anthropic) on swarm migrations for framework changes and lint rules
* [AI & I Podcast: How to Use Claude Code Like the People Who Built It](https://every.to/podcast/transcript-how-to-use-claude-code-like-the-people-who-built-it)
* [Cognition AI: Devin & Claude Sonnet 4.5](https://cognition.ai/blog/devin-sonnet-4-5-lessons-and-challenges) - discusses how improved model judgment about state externalization may make subagent delegation more practical
* [Building Companies with Claude Code](https://claude.com/blog/building-companies-with-claude-code) - Ambral's "robust research engine" uses dedicated sub-agents specialized for different data types, enabling parallel research across system areas
* [Building an internal agent: Subagent support](https://lethain.com/agents-subagents/) - Will Larson on YAML-configured subagents with virtual file isolation and code-driven LLM invocation
* [Cursor: Scaling long-running autonomous coding](https://cursor.com/blog/scaling-agents) - Hierarchical spawning with hundreds of concurrent agents validated in production

[Author's session anecdote](https://www.nibzard.com/ampcode) - the four-parallel-subagent website refactor described above

</details>

---

## Design-Time File Partition as Concurrency Control

- URL: https://agentic-patterns.com/patterns/design-time-file-partition
- Markdown: https://agentic-patterns.com/patterns/design-time-file-partition.md
- Category: Orchestration & Control | Status: proposed

> Each task declares every path it will write; overlapping tasks get a blocking dependency so only disjoint work runs at once on a shared checkout

### Use when

- Several headless agents work one repository from a shared checkout
- Per-agent worktrees or clones are too expensive in disk or build cache
- Collisions show up as clobbered files, duplicate fixes, or broken generated artifacts

### Avoid when

- One agent at a time, or agents on unrelated repositories
- Tasks cannot be scoped to a predictable set of paths before they start

<details>
<summary>Full pattern specification</summary>

---
title: "Design-Time File Partition as Concurrency Control"
summary: "Each task declares every path it will write; overlapping tasks get a blocking dependency so only disjoint work runs at once on a shared checkout"
status: "proposed"
category: "Orchestration & Control"
url: "https://agentic-patterns.com/patterns/design-time-file-partition"
source: "https://github.com/jedarden/NEEDLE/blob/main/docs/adr/015-concurrent-same-repo-worker-isolation.md"
authors: ["Jed Arden (@jedarden)"]
tags: ["multi-agent","concurrency","decomposition","task-queue","shared-checkout","headless"]
signals: ["Several headless agents work one repository from a shared checkout","Per-agent worktrees or clones are too expensive in disk or build cache","Collisions show up as clobbered files, duplicate fixes, or broken generated artifacts"]
anti_signals: ["One agent at a time, or agents on unrelated repositories","Tasks cannot be scoped to a predictable set of paths before they start"]
updated_at: "2026-09-26"
---

# Design-Time File Partition as Concurrency Control

> Each task declares every path it will write; overlapping tasks get a blocking dependency so only disjoint work runs at once on a shared checkout

## Use when

- Several headless agents work one repository from a shared checkout
- Per-agent worktrees or clones are too expensive in disk or build cache
- Collisions show up as clobbered files, duplicate fixes, or broken generated artifacts

## Avoid when

- One agent at a time, or agents on unrelated repositories
- Tasks cannot be scoped to a predictable set of paths before they start

## Problem

Several headless coding agents working the same repository collide on files. The usual fixes are a per-agent worktree (disk and build-cache duplication, merge-back debt) or a runtime coordination channel between agents (more moving parts, and agents negotiating while tokens burn). Neither addresses the actual failure: two tasks that were never safe to run concurrently were both marked ready.

## Solution

Decide concurrency when you cut the work, not when you run it. Every task declares the paths it **owns** — the complete set of files it will write, not just the files it intends to edit. Two tasks whose ownership overlaps get a blocking dependency edge so the queue never offers both at once; tasks with disjoint ownership are free to run in parallel on a single shared checkout. Depth of parallelism is therefore bounded by the partition (how many disjoint owners exist), and the agents need no inter-agent channel at all.

```pseudo
for each task in plan:
    task.owns = intended edits
             ∪ generated outputs of those edits   # lockfiles, codegen, snapshots, rendered docs
             ∪ repo-wide files the task will touch # changelog, index, tracker checkpoint
for (a, b) in pairs(tasks):
    if overlap(a.owns, b.owns): add_edge(b blocked_by a)
ready = tasks with no unresolved blockers   # only disjoint work is claimable
```

Ownership must cover incidental writes, because those are where "disjoint" tasks actually collide:

- **Generated files.** A dependency bump rewrites the lockfile; a schema change regenerates client code, an OpenAPI document, or a snapshot; a docs change regenerates an index or sitemap. The task that changes the input owns every output the build regenerates from it.
- **Repo-wide files.** Changelogs, version files, aggregate indexes, and the task tracker's own checkpoint file are written by most tasks. Either serialise every task that touches them (they become a single owner) or exclude them from task commits and regenerate them in one downstream step.
- **Tool side effects.** A formatter or linter with `--fix` writes wherever it finds something to fix. Run it only on owned paths, or treat a repo-wide format as its own task.
- **Opportunistic edits.** An agent that notices an unrelated problem must not fix it in place; it files a new task. Mediate writes against a canonical-path allowlist before they happen, including shell and tool side effects. Committing only owned paths excludes other changes from that commit; it neither rejects nor undoes an out-of-scope write already made in the shared tree.

File partitioning does not partition `.git/`. Serialize index and commit transactions under one shared lock, and prohibit workers from independently checking out branches, resetting, or cleaning the shared tree. If writes cannot be mediated or repository-wide operations cannot be serialized, use isolated worktrees or serialize the whole task. Read dependencies also matter: serialize a task that needs a stable version of files another task will change.

## Evidence

- **Evidence Grade:** `low`
- **Most Valuable Findings:**
  - One production deployment: a fleet of ~20 headless workers sharing one checkout per repository since 2026. With explicit ownership plus atomic claims, the residual failure was duplicate *claims* on one task (two workers producing byte-identical commits), not file collisions — that is, the remaining defect was in the queue, not the partition.
  - The early collisions that did occur were incidental writes (a tracker checkpoint file and a lockfile), which is why ownership was widened from "files edited" to "files written".
- **Unverified / Unclear:** Evidence is a single practitioner's fleet; no comparative measurement against per-agent worktrees or message-based coordination at the same scale.

## How to use it

- **When:** three or more agents on one repository, especially where a per-agent worktree or clone is expensive (large Rust/Go/JS build caches) or where merge-back of worktrees has already become a chore.
- **Decompose with ownership as a first-class field.** During planning, each task gets an `Owns:` line listing paths or components. If you cannot write that line, the task is not yet decomposed enough to run unattended; split it.
- **Enumerate the write set, not the edit set.** For each task ask: what does the build, formatter, codegen, or tracker rewrite when these files change? Add those paths. Two tasks that both trigger a lockfile update overlap even if their source edits do not.
- **Derive edges mechanically.** Compute the pairwise overlap and add a blocking dependency for every overlapping pair. Do not rely on workers to notice overlap at runtime.
- **Pair with an atomic claim.** The queue must hand a ready task to exactly one worker in a single transaction; the partition is only as safe as the claim.
- **Enforce before writes, then limit commits.** Mediate write operations to owned paths. Serialize Git staging and commits under a shared lock, committing only owned paths rather than `git add -A`. Commit selection is not a write sandbox; unowned writes must be prevented before they can clobber another worker’s work.
- **Size the partition to the fleet.** The number of mutually disjoint ready tasks is your ceiling on useful concurrency. If the ceiling is lower than the fleet, repartition (split a hot module) rather than adding workers.

## Trade-offs

- **Pros:** No inter-agent protocol; one shared checkout per repository; collisions are prevented before dispatch rather than detected after; the dependency graph doubles as the record of why two tasks were serialised.
- **Cons:** Requires the planner to know the code layout and build side effects well enough to write honest ownership lines; vague tasks invite two workers to fix the same obvious thing. Over-partitioning serialises work that could have run in parallel; under-partitioning reintroduces collisions.
- **Limits:** Does not itself protect against a worker writing outside its declared set — that needs write mediation, task isolation, or whole-task serialization. Does not help when tasks genuinely need the same file at the same time; those must be serialised or the file split.

## References

- [NEEDLE ADR-015](https://github.com/jedarden/NEEDLE/blob/main/docs/adr/015-concurrent-same-repo-worker-isolation.md) — contributor-maintained design record, including shared Git-state hazards and task-level serialization.
- [Git commit documentation](https://git-scm.com/docs/git-commit) — path-limited commits select content; they do not constrain earlier filesystem writes.

</details>

---

## Lane-Based Execution Queueing

- URL: https://agentic-patterns.com/patterns/lane-based-execution-queueing
- Markdown: https://agentic-patterns.com/patterns/lane-based-execution-queueing.md
- Category: Orchestration & Control | Status: emerging

> Routes work into named lanes, each with its own queue and concurrency limit, so sessions never interleave and background jobs never block users

### Use when

- Several user sessions or channels share one agent process
- Background jobs like cron or sub-agents must not block user replies
- Output from concurrent commands must not interleave

### Avoid when

- Work needs priorities, deadlines, or work stealing
- A single serial queue already gives enough throughput

<details>
<summary>Full pattern specification</summary>

---
title: "Lane-Based Execution Queueing"
summary: "Routes work into named lanes, each with its own queue and concurrency limit, so sessions never interleave and background jobs never block users"
status: "emerging"
category: "Orchestration & Control"
url: "https://agentic-patterns.com/patterns/lane-based-execution-queueing"
source: "https://github.com/openclaw/openclaw/blob/main/src/process/command-queue.ts"
authors: ["OpenClaw Contributors"]
tags: ["queueing","concurrency","lanes","isolation","parallelism","deadlock-prevention"]
signals: ["Several user sessions or channels share one agent process","Background jobs like cron or sub-agents must not block user replies","Output from concurrent commands must not interleave"]
anti_signals: ["Work needs priorities, deadlines, or work stealing","A single serial queue already gives enough throughput"]
updated_at: "2026-10-13"
---

# Lane-Based Execution Queueing

> Routes work into named lanes, each with its own queue and concurrency limit, so sessions never interleave and background jobs never block users

## Use when

- Several user sessions or channels share one agent process
- Background jobs like cron or sub-agents must not block user replies
- Output from concurrent commands must not interleave

## Avoid when

- Work needs priorities, deadlines, or work stealing
- A single serial queue already gives enough throughput

## Problem

Traditional agent systems serialize all operations through a single execution queue, creating bottlenecks that limit throughput. Concurrent execution is desirable but risky:

- **Interleaving hazards**: Multiple commands writing to stdin/stdout simultaneously corrupt user-facing output
- **Race conditions**: Shared state access without proper synchronization causes data corruption
- **Deadlock risks**: Naive concurrent queuing can create circular dependencies between operations

Agentic systems need parallelism to remain responsive (e.g., background tasks shouldn't block user interactions), but must preserve isolation guarantees.

## Solution

Isolated execution lanes with independent queues and configurable concurrency per lane. Each lane is a named queue with its own concurrency limit, drained independently without interference.

**Core concepts:**

- **Session lanes**: Per-conversation queues prevent message interleaving. Each user session gets an isolated lane (e.g., `session:telegram:user123`).
- **Global lanes**: Background tasks (cron jobs, health checks) execute in dedicated lanes (e.g., `cron`, `subagent`) without blocking session lanes.
- **Hierarchical composition**: Operations can nest lanes (session → global) via queue chaining. The outer lane waits for the inner lane, preventing deadlocks through structured queuing.
- **Configurable concurrency**: Each lane supports a `maxConcurrent` cap. Unconfigured lanes default to 1 (serial); the `main` lane defaults to `max(8, available CPU parallelism × 4)` and is bounded by `agents.defaults.maxConcurrent`.
- **Wait-time warnings**: Tasks that sit queued too long trigger warnings and callbacks, surfacing performance issues.

**Implementation sketch:**

```typescript
type LaneState = {
  queue: QueueEntry[];
  active: number;           // Currently running tasks
  maxConcurrent: number;    // Concurrency limit
  draining: boolean;
};

const lanes = new Map<string, LaneState>();

function drainLane(lane: string) {
  const state = getLaneState(lane);
  // Pump tasks until concurrency limit reached
  while (state.active < state.maxConcurrent && state.queue.length > 0) {
    const entry = state.queue.shift();
    state.active += 1;
    entry.task().finally(() => {
      state.active -= 1;
      pump();  // Drain next entry
    });
  }
}

function enqueueCommandInLane<T>(
  lane: string,
  task: () => Promise<T>,
): Promise<T> {
  return new Promise((resolve, reject) => {
    getLaneState(lane).queue.push({ task, resolve, reject });
    drainLane(lane);
  });
}
```

**Deadlock prevention via hierarchical composition:**

```typescript
// Session lane queues a task that itself queues to global lane
await enqueueCommandInLane(sessionLane, () =>
  enqueueCommandInLane(globalLane, () =>
    doBackgroundWork()
  )
);
// Outer promise resolves when inner completes; no circular wait
```

**Lane examples from OpenClaw:**

- `main`: Inbound interactive turns; concurrency defaults to `max(8, available CPU parallelism × 4)`
- `system-agent` and `system-agent-inference`: Internal agent work, isolated from user traffic
- `cron` and `cron-nested`: Scheduled turns; an isolated cron turn holds a `cron` slot while its inner agent execution uses `cron-nested`
- `hook-dispatch`: External hook agent-run dispatch, in its own lane rather than the cron budget
- `background`, `active-memory`, `nested`: Housekeeping work that must not block user lanes
- `subagent:<session>`: Per-session spawned-agent queues (default 8 per spawning session); `subagent:swarm:<group>` collectors default to 32
- `session:<key>`: Per-session serial queues shared by CLI, embedded, and CLI-backend runs

## How to use it

1. **Identify isolation boundaries**: Group operations that must not interleave (e.g., per-user, per-channel).
2. **Define lane names**: Use a hierarchy (e.g., `session:telegram:user123`) for scoping.
3. **Set concurrency limits**: Serial lanes use `maxConcurrent=1`; parallel lanes use higher values.
4. **Queue tasks**: Call `enqueueCommandInLane(lane, task)` to schedule work.
5. **Compose hierarchically**: When a queued task must spawn work in another lane, await the inner enqueue from the outer task.

**Observability**: Track per-lane metrics (queue depth, active count, wait times) to detect backpressure and starvation. Key signals include `queue_size_per_lane`, `active_tasks_per_lane`, and `wait_time_p95`.

**Pitfalls to avoid:**

- **Over-parallelization**: Too many concurrent workers can exhaust resources (file handles, memory). Monitor `active` count.
- **Starvation**: Low-priority lanes may wait indefinitely if high-priority lanes are always full. Use wait-time warnings to detect.
- **Missing hierarchy**: Direct cross-lane dependencies without nested queuing risk deadlocks. Always compose via `enqueueCommandInLane(() => enqueueCommandInLane(...))`.
- **Dynamic lane proliferation**: Creating lanes with unstable identifiers (e.g., timestamps) causes unbounded memory growth. Use stable names and implement lane garbage collection for session-scoped lanes.

## Trade-offs

**Pros:**

- **Isolation guarantees**: No interleaving between lanes; each lane preserves ordering.
- **Flexible parallelism**: Concurrency per lane allows mixed workloads (serial UI, parallel background).
- **Simple mental model**: Hierarchical composition maps to structured programming patterns.
- **Observability**: Lane-level metrics (queue depth, active count, wait times) aid debugging.

**Cons/Considerations:**

- **Memory overhead**: Each lane maintains a queue; thousands of idle lanes may waste memory.
- **Tuning required**: Concurrency limits need calibration based on workload characteristics.
- **Not a general scheduler**: No priority queues, deadlines, or work stealing. Use a proper scheduler for complex needs.

## References

- [OpenClaw command-queue.ts](https://github.com/openclaw/openclaw/blob/main/src/process/command-queue.ts) - Core queue implementation
- [OpenClaw lanes.ts](https://github.com/openclaw/openclaw/blob/main/src/process/lanes.ts) - Lane enum: main, system-agent, cron, cron-nested, hook-dispatch, background, subagent, active-memory, nested
- [OpenClaw queue documentation](https://docs.openclaw.ai/concepts/queue) - Lane concurrency defaults and session lanes
- Related: [Parallel Tool Execution](/patterns/parallel-tool-execution) for tool-level parallelism
- Academic foundations: Actor Model (IJCAI '73), Work-Stealing (SOSP '95), CALM Theorem (PODS '11)
- Industry analogs: Sidekiq queues, BullMQ isolation, Airflow pools

</details>

---

## Budget-Aware Model Routing with Hard Cost Caps

- URL: https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps
- Markdown: https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps.md
- Category: Orchestration & Control | Status: emerging

> Routes each request to the cheapest model that meets its needs under hard cost caps, and escalates only when quality gates fail

### Use when

- Model bills grow faster than product value
- Every request goes to the strongest model by default
- High-volume workflows with measurable quality targets

### Avoid when

- Task complexity cannot be classified reliably
- Team cannot maintain an extra routing control plane

<details>
<summary>Full pattern specification</summary>

---
title: "Budget-Aware Model Routing with Hard Cost Caps"
summary: "Routes each request to the cheapest model that meets its needs under hard cost caps, and escalates only when quality gates fail"
status: "emerging"
category: "Orchestration & Control"
url: "https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps"
source: "https://arxiv.org/abs/2305.05176"
authors: ["Codex (@openai)"]
tags: ["routing","cost-control","multi-model","orchestration","reliability"]
signals: ["Model bills grow faster than product value","Every request goes to the strongest model by default","High-volume workflows with measurable quality targets"]
anti_signals: ["Task complexity cannot be classified reliably","Team cannot maintain an extra routing control plane"]
updated_at: "2026-10-13"
---

# Budget-Aware Model Routing with Hard Cost Caps

> Routes each request to the cheapest model that meets its needs under hard cost caps, and escalates only when quality gates fail

## Use when

- Model bills grow faster than product value
- Every request goes to the strongest model by default
- High-volume workflows with measurable quality targets

## Avoid when

- Task complexity cannot be classified reliably
- Team cannot maintain an extra routing control plane

## Problem

Agent systems often route every request to the strongest model by default, which quietly inflates cost and reduces throughput under load. Soft budget guidance in prompts is not enough because model selection happens in control code, not language outputs. Teams need deterministic guardrails that preserve quality for hard tasks while preventing runaway token spend for routine work.

## Solution

Introduce a routing layer with explicit budget contracts and hard caps per request, user, and workflow lane.

Key elements:
- A tiered model catalog (`small`, `medium`, `frontier`) with capability metadata.
- A policy engine that computes a maximum allowable spend before each call.
- Deterministic fallback rules when the selected model would exceed budget.
- Quality override paths for safety-critical or high-value workflows.

Typical flow:
1. Classify task complexity and risk.
2. Assign an expected token envelope and max dollar budget.
3. Select the cheapest model that satisfies required capabilities.
4. Enforce a hard cap before each model/tool step.
5. Escalate only when objective signals justify the extra cost.

**Cascade routing**: Try the cheapest adequate model first; if quality gates fail, escalate to stronger models. Learned routing policies trained on human preference data can improve selection accuracy while respecting budget constraints.

```pseudo
budget = policy.max_cost(task_type, user_tier)
candidate = router.pick_model(task_features, budget)

if estimate_cost(candidate, context) > budget:
    candidate = router.next_cheaper(candidate)

result = call_model(candidate, context)
if quality_gate.failed(result) and policy.can_escalate(task_type):
    result = call_model(router.next_stronger(candidate), context)
```

## How to use it

- Use it when model bills are growing faster than product value.
- Start with high-volume workflows where quality targets are measurable.
- Add routing telemetry: selected model, estimated cost, actual cost, escalation reason.
- Define hard-fail behavior for cap breaches (defer, partial answer, or human handoff).
- Check provider-native caps before building your own: for example Claude Code's `--max-budget-usd` flag stops a run once estimated API spend reaches a set amount.

## Trade-offs

* **Pros:** Predictable spending, better capacity planning, and clear escalation policy.
* **Cons:** More control-plane complexity and risk of under-powering hard requests if classification is weak.

## References

- https://arxiv.org/abs/2305.05176 - FrugalGPT (Stanford, 2023): learned query cascades; the hard-cap layer on top is this pattern's addition, not the paper's
- https://arxiv.org/abs/2406.18665 - RouteLLM (ICLR 2024)
- https://arxiv.org/html/2510.08439v1 - xRouter (2025)
- https://arxiv.org/abs/2601.07206 - LLMRouterBench (2026): benchmark covering both performance-oriented and performance-cost routing
- https://arxiv.org/abs/2609.37902 - Market-Aware Routing for Open-Weight LLM Inference (Sep 2026): routing must also pick the serving provider, not just the model
- https://code.claude.com/docs/en/cli-reference - Claude Code CLI reference: `--max-budget-usd` as an example of a provider-native hard spend cap
- https://developers.openai.com/api/docs/guides/rate-limits - OpenAI rate and spend limits: requests that exceed a project or organization budget cap fail hard with 429

</details>

---

## Agent Circuit Breaker

- URL: https://agentic-patterns.com/patterns/agent-circuit-breaker
- Markdown: https://agentic-patterns.com/patterns/agent-circuit-breaker.md
- Category: Reliability & Eval | Status: emerging

> Prevents agents from wasting tokens and time on repeatedly failing tools by tracking failure rates and temporarily disabling broken tool endpoints

### Use when

- Agent calls external APIs or tools that can fail
- Retries burn tokens without progress
- Multiple tool providers available for fallback

### Avoid when

- All tools are local and deterministic
- Single-shot agent with no retry logic

<details>
<summary>Full pattern specification</summary>

---
title: "Agent Circuit Breaker"
summary: "Prevents agents from wasting tokens and time on repeatedly failing tools by tracking failure rates and temporarily disabling broken tool endpoints"
status: "emerging"
category: "Reliability & Eval"
url: "https://agentic-patterns.com/patterns/agent-circuit-breaker"
source: "https://martinfowler.com/bliki/CircuitBreaker.html"
authors: ["Jeel Thummar (@jeelthummar)"]
tags: ["circuit-breaker","fault-tolerance","tool-reliability","graceful-degradation","resilience"]
signals: ["Agent calls external APIs or tools that can fail","Retries burn tokens without progress","Multiple tool providers available for fallback"]
anti_signals: ["All tools are local and deterministic","Single-shot agent with no retry logic"]
updated_at: "2026-10-13"
---

# Agent Circuit Breaker

> Prevents agents from wasting tokens and time on repeatedly failing tools by tracking failure rates and temporarily disabling broken tool endpoints

## Use when

- Agent calls external APIs or tools that can fail
- Retries burn tokens without progress
- Multiple tool providers available for fallback

## Avoid when

- All tools are local and deterministic
- Single-shot agent with no retry logic

## Problem

Agents that use external tools — APIs, databases, web scrapers, code executors — face a common failure mode: a tool endpoint becomes degraded or unavailable, and the agent **keeps calling it**, burning tokens on retries that will never succeed.

This creates three cascading problems:

- **Token waste**: Each failed tool call costs input/output tokens, and the agent often generates lengthy retry reasoning
- **Latency amplification**: Sequential retries on a dead endpoint add seconds or minutes with no progress
- **Cascading failure**: If one tool is down (e.g., a search API), the agent may stall entirely instead of using alternative approaches

Unlike model-level failover (switching between GPT-4 and Claude when one provider is down), tool-level failures require a different strategy — the agent needs to learn, mid-session, that a specific tool is broken and **stop using it**.

## Solution

Apply the classic Circuit Breaker pattern from distributed systems to agent tool invocations. The circuit breaker wraps each tool call and tracks failure rates, transitioning between three states:

```mermaid
stateDiagram-v2
    [*] --> Closed
    Closed --> Open: failure_count >= threshold
    Open --> HalfOpen: cooldown_elapsed
    HalfOpen --> Closed: probe_succeeds
    HalfOpen --> Open: probe_fails
```

**States:**

| State | Behavior |
|-------|----------|
| **Closed** | Tool calls pass through normally. Failures are counted. |
| **Open** | Tool calls are **blocked immediately** — returns a cached error or fallback. No actual call is made. |
| **Half-Open** | One probe call is allowed through. If it succeeds, reset to Closed. If it fails, return to Open. |

**Core mechanism:**

```python
class AgentCircuitBreaker:
    def __init__(self, failure_threshold=3, cooldown_seconds=60):
        self.state = "closed"
        self.failure_count = 0
        self.threshold = failure_threshold
        self.cooldown = cooldown_seconds
        self.opened_at = None

    def call(self, tool_fn, *args, **kwargs):
        if self.state == "open":
            if time.time() - self.opened_at >= self.cooldown:
                self.state = "half_open"  # Allow one probe
            else:
                raise CircuitOpenError(f"Circuit open — tool disabled for {self.cooldown}s")

        try:
            result = tool_fn(*args, **kwargs)
            if self.state == "half_open":
                self.state = "closed"
                self.failure_count = 0
            return result
        except Exception as e:
            self.failure_count += 1
            if self.failure_count >= self.threshold:
                self.state = "open"
                self.opened_at = time.time()
            raise
```

**Agent-specific adaptations beyond traditional circuit breakers:**

- **Token-aware thresholds**: Open the circuit after N tokens wasted, not just N failures
- **Fallback routing**: When a circuit opens, inform the agent's system prompt so it chooses alternative tools
- **Per-tool granularity**: Each tool (search API, code executor, database) gets its own circuit breaker
- **Session-scoped state**: Circuit state resets between agent sessions (unlike persistent microservice breakers)

## Evidence

- **Evidence Grade:** `medium`
- **Most Valuable Findings:**
  - Circuit breakers are proven in production in microservice architectures (Netflix Hystrix, Resilience4j, Polly) and the pattern translates directly to agent tool calls
  - Agent-specific 2025-26 practitioner coverage (Maxim's production guide, ToolRoute's reliability-patterns write-up) recommends circuit breakers for LLM application and agent tool failures
- **Unverified / Unclear:** Optimal threshold and cooldown values for agent workloads vary significantly by tool type and latency profile. No published measurements of token savings from circuit breakers in agent systems were found; the token-waste benefit is currently qualitative

## How to use it

**When to apply:**

- Agent uses 3+ external tools that can independently fail
- Tools have variable reliability (APIs with rate limits, web scrapers, third-party services)
- Agent sessions are long enough that a tool may recover mid-session

**Implementation steps:**

1. **Wrap each tool** in its own circuit breaker instance
2. **Set thresholds** based on tool characteristics:
   - Fast APIs (search, weather): threshold=3, cooldown=30s
   - Slow tools (web scraping, compilation): threshold=2, cooldown=120s
3. **Define fallback behavior** when circuits open:
   - Return cached/stale results if available
   - Route to an alternative tool (e.g., switch search providers)
   - Inform the agent that the tool is unavailable so it can adjust its plan
4. **Log circuit state changes** for observability

**Integration with agent loops:**

```python
# In your agent's tool execution layer
breakers = {
    "web_search": AgentCircuitBreaker(failure_threshold=3, cooldown_seconds=60),
    "code_exec": AgentCircuitBreaker(failure_threshold=2, cooldown_seconds=120),
    "database":  AgentCircuitBreaker(failure_threshold=3, cooldown_seconds=30),
}

def execute_tool(tool_name, *args):
    breaker = breakers.get(tool_name)
    if breaker:
        return breaker.call(tools[tool_name], *args)
    return tools[tool_name](*args)
```

## Trade-offs

**Pros:**

- Prevents token waste from futile retries on broken tools
- Enables graceful degradation — agent continues working with available tools
- Self-healing: half-open probes restore tools automatically when they recover
- Simple to implement (~50 lines of core logic)
- Session-scoped state avoids the state management complexity of persistent breakers

**Cons:**

- Adds a layer of indirection around tool calls
- Threshold tuning requires understanding each tool's failure characteristics
- May mask intermittent errors that would naturally resolve with a single retry
- Agent must be prompted to handle `CircuitOpenError` gracefully (fallback awareness)
- Not useful for agents with only 1-2 highly reliable tools

## References

- [Martin Fowler: CircuitBreaker](https://martinfowler.com/bliki/CircuitBreaker.html) — canonical pattern description
- [Release It! (Michael Nygard, 2007)](https://pragprog.com/titles/mnee2/release-it-second-edition/) — original production pattern
- [Netflix Hystrix](https://github.com/Netflix/Hystrix) — production implementation at scale
- [Resilience4j](https://resilience4j.readme.io/) — lightweight Java implementation
- [Retries, Fallbacks, and Circuit Breakers in LLM Apps: A Production Guide (Maxim)](https://www.getmaxim.ai/articles/retries-fallbacks-and-circuit-breakers-in-llm-apps-a-production-guide) — agent-era practitioner coverage
- [How AI Agents Handle Tool Failures: Reliability Patterns for Production (ToolRoute)](https://www.toolroute.ai/blog/how-ai-agents-handle-tool-failures) — circuit breakers for agent tool calls (2026)
- Related: [Failover-Aware Model Fallback](failover-aware-model-fallback.md) — handles model-provider failures (complementary)
- Related: [Action Caching & Replay](action-caching-replay.md) — cached results can serve as circuit-open fallbacks

</details>

---

## Intent-Level Cost Attribution

- URL: https://agentic-patterns.com/patterns/intent-level-cost-attribution
- Markdown: https://agentic-patterns.com/patterns/intent-level-cost-attribution.md
- Category: Reliability & Eval | Status: proposed

> Records every LLM call against the projectId/intentId/user key that caused it, at call time, so spend can be queried and enforced per work item instead of as an opaque total

### Use when

- Multiple agents, users, or intents share one model budget and someone must answer for the spend
- A budget cap exists or is planned, and it should bind the specific work that is expensive rather than throttling everything uniformly
- Cost regressions after a prompt, model, or workflow change need to be localized to the intent that caused them

### Avoid when

- A single agent with a single user and no budget enforcement - a daily total is enough
- Call sites cannot name their intent or project, and threading attribution keys through the orchestration layer is not feasible

<details>
<summary>Full pattern specification</summary>

---
title: "Intent-Level Cost Attribution"
summary: "Records every LLM call against the projectId/intentId/user key that caused it, at call time, so spend can be queried and enforced per work item instead of as an opaque total"
status: "proposed"
category: "Reliability & Eval"
url: "https://agentic-patterns.com/patterns/intent-level-cost-attribution"
source: "https://github.com/Retsumdk/agent-cost-attribution-api"
authors: ["Retsumdk (@Retsumdk)"]
tags: ["cost-control","observability","budgeting","multi-agent","token-spend"]
signals: ["Multiple agents, users, or intents share one model budget and someone must answer for the spend","A budget cap exists or is planned, and it should bind the specific work that is expensive rather than throttling everything uniformly","Cost regressions after a prompt, model, or workflow change need to be localized to the intent that caused them"]
anti_signals: ["A single agent with a single user and no budget enforcement - a daily total is enough","Call sites cannot name their intent or project, and threading attribution keys through the orchestration layer is not feasible"]
updated_at: "2026-10-20"
---

# Intent-Level Cost Attribution

> Records every LLM call against the projectId/intentId/user key that caused it, at call time, so spend can be queried and enforced per work item instead of as an opaque total

## Use when

- Multiple agents, users, or intents share one model budget and someone must answer for the spend
- A budget cap exists or is planned, and it should bind the specific work that is expensive rather than throttling everything uniformly
- Cost regressions after a prompt, model, or workflow change need to be localized to the intent that caused them

## Avoid when

- A single agent with a single user and no budget enforcement - a daily total is enough
- Call sites cannot name their intent or project, and threading attribution keys through the orchestration layer is not feasible

## Problem

Agent fleets spend LLM budget continuously and opaquely. When a bill spikes or a budget cap trips, the operator can usually answer *how much* was spent but not *which work caused it*: a single daily total hides whether the spend came from a misbehaving retry loop, one user's abnormal usage, a specific intent that quietly grew, or steady baseline load across the fleet. Without attribution at the level of the work item that triggered the calls, cost control degenerates into guesswork — you can cut a budget, but you cannot cut the right thing, and you cannot tell whether a change actually reduced waste or just moved it somewhere else.

## Solution

Attribute every model call to the intent that caused it at the moment the call is made. Each usage record carries a three-part attribution key — `projectId`, `intentId`, and `userId` — plus the model, token counts, and optional free-form metadata. Cost is computed at record time from per-model pricing, so the ledger is a first-class artifact rather than something reconstructed later from provider invoices.

The mechanism has four parts:

- **Tracker** — the core engine that turns a usage event (model, input/output tokens, attribution keys) into a priced cost record.
- **Storage** — a persistence layer with atomic writes so concurrent agents recording usage cannot corrupt the ledger.
- **Reporting API** — roll-ups by project, by intent, and by user, plus filtered record retrieval, so the same ledger answers both "what did this intent cost?" and "who is driving the bill?"
- **CLI** — server startup and report generation from the command line for operators working outside the API.

```pseudo
on_model_call(agent, model, input_tokens, output_tokens, intent, project, user):
    cost = price(model, input_tokens, output_tokens)
    ledger.append({
      model, tokens, cost,
      projectId: project, intentId: intent, userId: user,
      metadata, timestamp
    })   # atomic write

when budget_question_arises:
    report(by="intent")   # find the top spenders by work item
    report(by="user")     # separate fleet load from individual demand
```

The control points are the record schema (the attribution keys are mandatory, so unattributed spend cannot hide) and the report endpoints (the same data serves alerting, post-hoc analysis, and per-intent budget enforcement).

## Evidence

- **Evidence Grade:** `low`
- **Most Valuable Findings:** Production cost-governance systems (finops practice, LLM gateway products) consistently attribute spend along workload dimensions rather than only reporting totals; recording attribution at call time avoids the reconstruction problem that makes post-hoc invoice analysis lossy. The reference implementation demonstrates the pattern end-to-end with per-model pricing and atomic ledger writes.
- **Unverified / Unclear:** Quantified savings from intent-level attribution in published agent deployments are not documented; the pattern's value in fleets with very high intent cardinality (attribution overhead vs. insight) needs field measurement.

## How to use it

Use this pattern when:

- Multiple agents, users, or intents share one model budget and someone must answer for it.
- A budget cap exists (or should): attribution is the prerequisite for caps that bind the *right* work instead of throttling everything uniformly.
- Cost regressions need diagnosis: after a prompt, model, or workflow change, per-intent deltas localize the regression instead of forcing a fleet-wide bisect.

Prerequisites: every model call site must be able to name its intent and project — attribution keys must be threaded through the orchestration layer at call time, which is a real (and one-time) instrumentation cost. Implementation considerations: price tables must stay current with model pricing changes; atomic writes or an append-only log matter once more than one agent writes concurrently.

## Trade-offs

**Pros:**

- Turns an opaque total into a queryable ledger; cost questions become lookups, not investigations.
- Makes targeted cost control possible: cap, throttle, or refactor the specific intent that is expensive.
- Attribution recorded at call time preserves intent that post-hoc reconstruction cannot recover.

**Cons:**

- Instrumentation tax: every call site must supply the attribution keys, and a mis-keyed call silently pollutes reports.
- Attribution cardinality can explode in fleets with many short-lived intents; roll-ups need designing (per project, per user) to stay useful.
- The ledger itself is state that must be persisted and retained — at scale this becomes its own storage problem.

## References

- Reference implementation: [Retsumdk/agent-cost-attribution-api](https://github.com/Retsumdk/agent-cost-attribution-api) — REST + CLI cost ledger with `projectId`/`intentId`/`userId` attribution, per-model pricing, and atomic JSON persistence (MIT).
- Related patterns in this catalog: [Budget-aware model routing with hard cost caps](budget-aware-model-routing-with-hard-cost-caps.md) — routing-level cost control that benefits from attribution data.

</details>
