Build This Now
Build This Now
クロード・コードとは何か?Claude Code のインストールClaude Code ネイティブインストーラーClaude Code で最初のプロジェクトを作る
Claude Code v2.1.122 Release NotesClaude Code Dynamic Workflows: How to Orchestrate 1,000 Subagents on a Real CodebaseClaude Code ベストプラクティスClaude Opus 4.7 ベストプラクティスVPS上でのClaude CodeGit 統合Claude Code レビューClaude Code WorktreesClaude CodeリモートコントロールClaude Code ChannelsChannels, Routines, Teleport, DispatchClaude Code スケジュールタスクClaude Code権限管理Claude Code オートモードAdding Stripe Payments With Claude CodeフィードバックループTodoワークフローClaude Code タスク管理プロジェクトテンプレートClaude Code の料金とトークン使用量Claude Code Pricing: What You'll Actually PayClaude Code Ultra Review 完全ガイドBuilding a Next.js App With Claude CodeClaude Code With Supabase: Database, Auth, RLSVercel deepsec with Claude Code
speedy_devvkoen_salo
Blog/Handbook/Workflow/Claude Code Dynamic Workflows: How to Orchestrate 1,000 Subagents on a Real Codebase

Claude Code Dynamic Workflows: How to Orchestrate 1,000 Subagents on a Real Codebase

A technical breakdown of how Claude Code dynamic workflows use JavaScript orchestration scripts to coordinate up to 1,000 parallel subagents outside the model context window.

設定をやめて、構築を始めよう。

AIオーケストレーション付きSaaSビルダーテンプレート。

Published May 30, 202611 min readHandbook hubWorkflow index

Claude Code dynamic workflows are a multi-agent orchestration system where Claude writes a JavaScript script that fans work out across up to 1,000 parallel subagents, keeps all intermediate results in script variables rather than the model's context window, and delivers only the final verified answer back to your session. Released May 28, 2026 alongside Claude Opus 4.8, they require CLI v2.1.154 or later.

This post covers the architecture, the six script primitives, real-world use cases, honest cost math, and the gotchas developers are hitting in the first weeks of the research preview.

Table of Contents

  1. What Is Claude Code's Dynamic Workflow System?
  2. How Claude Code Workflows Work: Architecture
  3. Real-World Use Cases for Claude Code Workflows
  4. Claude Code Workflow Costs, Limits, and Efficiency
  5. Caveats and Gotchas Developers Hit
  6. Claude Code Workflows vs LangGraph, Temporal, and Others
  7. Best Practices for Claude Code Workflows
  8. Frequently Asked Questions

設定をやめて、構築を始めよう。

AIオーケストレーション付きSaaSビルダーテンプレート。


What Is Claude Code's Dynamic Workflow System?

Before Claude Code dynamic workflows, every subagent Claude dispatched returned its result into the main conversation context window. That meant a 50-agent run accumulated 50 chunks of intermediate text, the context filled up, and quality degraded long before the task finished. The agent count ceiling was not a hard limit so much as a soft wall where the model ran out of useful working memory.

Dynamic workflows solve this by moving the orchestration out of the conversation entirely. Claude writes a JavaScript script for the specific task you give it. That script runs in a background runtime. The orchestration logic (which agents to spawn, how many, in what order, when to verify) lives in script variables. The model's context window only receives the final synthesized result.

The six primitives available in a workflow script:

  • agent(prompt, opts?) — spawns a single subagent, returns its final text or validated JSON
  • parallel(thunks) — runs an array of tasks concurrently with a synchronization barrier
  • pipeline(items, ...stages) — streams items through stages with no barrier between them
  • workflow(nameOrRef, args?) — invokes a saved workflow as a sub-step (one nesting level max)
  • phase(title) — names a progress group in the /workflows monitoring dashboard
  • log(msg) — emits a narrator line in the workflow output

The word "dynamic" has a specific meaning here. Claude decides the task decomposition, the agent count, the phasing strategy, and the verification approach in real time for the specific task you described. No two workflow scripts are identical. This is different from Routines (which are statically scheduled prompts you define once) and different from the older ScheduleWakeup primitive used in /loop sessions.

Here is the minimal structure of a valid workflow script:

export const meta = {
  name: 'security-audit',
  description: 'Parallel security scan across auth, DB, and input layers',
  whenToUse: 'When you need a full security sweep before shipping',
  phases: [
    { title: 'Scan', detail: 'Three specialized agents run in parallel' },
    { title: 'Synthesize', detail: 'One agent compiles a prioritized report' },
  ]
}

phase('Scan')
const [auth, db, input] = await parallel([
  () => agent('Audit authentication flows for bypass vulnerabilities', { label: 'auth-scanner' }),
  () => agent('Check all database queries for injection risks', { label: 'db-scanner' }),
  () => agent('Review input validation and sanitization', { label: 'input-scanner' }),
])

phase('Synthesize')
const report = await agent(
  `Compile a prioritized security report from these three findings:\n\nAuth: ${auth}\n\nDB: ${db}\n\nInput: ${input}`,
  { label: 'synthesizer' }
)

return report

How Claude Code Workflows Work: Architecture

When you trigger a workflow, this is the sequence of events:

Step 1: Planning. Claude analyzes your request and writes a JavaScript orchestration script. The script encodes which phases exist, how many agents run in each phase, whether items flow in parallel or through a pipeline, and what verification logic runs before returning results.

Step 2: Approval. You see the planned phases from the meta.phases array. You can run it, set it as trusted for this project so it never asks again, open the raw JS script with Ctrl+G to inspect it, or cancel.

Step 3: Execution. The workflow runtime runs the script in a background process. Subagents do the actual file reading, shell commands, web fetches, and MCP tool calls. Each agent() call returns its result as a JavaScript value (a string, or validated JSON if you passed a schema). Those values accumulate in script variables, not in Claude's context.

Step 4: Verification. Most Claude-generated workflows include a verification phase where separate agents attempt to refute or challenge the findings from the main phase. The workflow iterates until results converge.

Step 5: Delivery. The script's return value, the final synthesized answer, lands in your session. That is the only thing that touches Claude's context window.

Resume and caching. The runtime journals the result of every completed agent() call. If you pause a workflow with the p key in the /workflows dashboard, completed agents return their cached results instantly on resume. This only works within the same Claude Code session: if you exit the application, the journal is discarded and the next session starts fresh.

The prompt cache and cost implications. Anthropic's prompt cache has a 5-minute TTL by default. Any agent() call that fires more than 300 seconds after the previous one misses the cache entirely, triggering a full re-write at 12.5x the cost of a cache read. For workflows with inter-phase gaps longer than five minutes, explicitly request the 1-hour TTL extension via cache_control: { type: 'ephemeral', ttl: '1h' } on initial setup. This costs 2x the cache write price but makes long workflows dramatically cheaper.

The /workflows monitoring dashboard (type /workflows to open it) shows phases, active agent counts, token totals, and elapsed time. Navigation: Up/Down to select phases or agents, p to pause or resume, x to stop an agent or the entire workflow, r to restart a selected agent, s to save the run as a reusable command.

Real-World Use Cases for Claude Code Workflows

1. Parallel code review across a large PR. Split changed files into batches, run one agent per batch to check logic, types, security, and tests, then synthesize findings into a prioritized review. One developer spawned 90 agents for a single code review on this pattern and hit monthly token limits, which is a sign that the pattern works but needs budget guardrails.

2. Large-scale migration or rewrite. The canonical example is Jarred Sumner's Bun project: approximately 750,000 lines of Zig ported to Rust in 11 days, with 99.8% of the existing test suite passing from first commit to merge. The pattern is a 600-line mapping document (every Zig type and idiom translated to its Rust equivalent) plus parallel agents processing non-overlapping file sets with worktree isolation so they can write without collisions.

3. Security audit with adversarial cross-checking. An orchestrator spawns three specialized scanners (authentication flows, database queries, input validation) in parallel, then a separate verification agent attempts to find false positives in each finding before compiling a prioritized report. The built-in adversarial verification phase is what makes this pattern reliable enough for pre-ship audits.

4. Multi-source research harness. The built-in /deep-research command is itself a workflow demonstrating the fan-out pattern: nine agents scrape different sources simultaneously, intermediate findings reduce into ranked candidates, one synthesis agent compiles the final report. The same pattern works for competitive analysis, dependency audits, or changelog summarization across a monorepo.

5. Test generation at scale. Fan out across every module in a codebase, one agent per module writing tests against the public API surface, then a convergence phase checks for coverage overlap and removes duplicates before writing final test files. The isolation: 'worktree' option in agent() keeps parallel agents from creating file conflicts.

Claude Code Workflow Costs, Limits, and Efficiency

Hard limits (enforced by the runtime, not negotiable):

ConstraintValueReason
Max concurrent agents16 (fewer on low-CPU machines)Bounds local CPU and memory use
Max total agents per run1,000Prevents runaway loops
Workflow nesting depth1 levelChild shares parent's counters

Token pricing (pay-as-you-go):

  • Claude Opus 4.8: $5 input / $25 output per million tokens
  • Claude Sonnet 4.6: $3 input / $15 output per million tokens
  • Cache reads: ~10% of input price. Cache writes: ~25% of input price (when working correctly).

Pricing math on a real workflow. A parallel security audit running three Sonnet 4.6 agents at 8,000 input tokens each and 2,000 output tokens each costs roughly: (3 × 8,000 × $3/M) + (3 × 2,000 × $15/M) = $0.072 + $0.090 = $0.162. Swap those to Opus 4.8 and the same run costs $0.42. Running 90 such agents on a large codebase review at Opus rates hits $12.60 in output tokens alone before overhead, which explains how a developer can burn through monthly limits in a single session.

When workflows are cost-efficient vs. wasteful:

Efficient:

  • Tasks where parallelism reduces wall-clock time (you need the result fast, cost is secondary)
  • Large migrations where sequential execution would take days
  • Tasks with clear subtask boundaries and no cross-agent dependencies mid-run

Wasteful:

  • Routine single-file edits (a normal conversation is faster and cheaper)
  • Tasks that require real-time steering or mid-run guidance (workflows run unattended)
  • Exploratory or ambiguous requests where the decomposition strategy is unknown

The 5-minute cache cliff. If your workflow has phases separated by more than 300 seconds, every agent in the later phase pays full cache write costs instead of cheap cache reads. On a 50-agent run with an Opus orchestrator, this can inflate costs 3x to 6x compared to a well-cached run. Pass the 1-hour TTL flag on initial context to avoid this.

Budget-aware loops. The global budget variable in workflow scripts exposes the token target set at launch. Always guard budget-sensitive loops: if (budget.total && tokensUsed > budget.total * 0.8) break. Without a guard, loops run to the 1,000-agent hard cap.

Caveats and Gotchas Developers Hit

Workflow scripts are JavaScript, not TypeScript. The runtime has no TypeScript transpilation layer. Adding type annotations to a workflow script causes a parse error. If you want typed orchestration, write a TypeScript wrapper that calls the workflow at runtime; do not put types in the script itself.

Three non-deterministic built-ins throw inside workflow scripts. Date.now(), Math.random(), and new Date() without arguments are banned. The reason is that the resume cache journals every agent() call by its deterministic key. Non-deterministic values would generate different keys on re-run, breaking resume. Workarounds: pass timestamps through args at launch time, vary prompts by loop index rather than by random value.

No direct filesystem or shell access in the script. The orchestration layer cannot read files or run commands. All I/O goes through subagents. The script is a pure coordination layer.

parallel() vs pipeline() confusion. parallel() is a synchronization barrier: it waits for every thunk before returning. pipeline() has no barrier: item A can be in stage 3 while item B is still in stage 1. Default to pipeline() for independent item processing. Use parallel() only when a downstream stage needs the complete set of all prior results at once (deduplication, cross-ranking, adversarial review of the full set). A failed thunk inside parallel() resolves to null rather than rejecting, so always .filter(Boolean) the results array.

acceptEdits mode auto-applies file changes. Subagents running inside a workflow operate in acceptEdits mode by default. File edits apply without individual review prompts. On a 50-agent run touching hundreds of files, this means unreviewed changes land at scale. Review the generated workflow script (Ctrl+G in the approval prompt) before running on production branches.

When not to use dynamic workflows:

  • Any task where you need to steer or adjust mid-run
  • Exploratory debugging where the next step depends on what you just saw
  • Tasks requiring a single focused response under 10 minutes
  • Cost-sensitive environments with no per-run budget guardrails in place

The .github/workflows/ push scope bug. If a subagent edits files under .github/workflows/, the edit succeeds locally but fails at push time because the Claude Code OAuth credential lacks the workflow scope. The error surfaces after the entire session budget is spent. Check the workflow script for .github/workflows/ writes before approving.

Claude Code Workflows vs LangGraph, Temporal, and Others

These tools occupy different layers of the stack and are not interchangeable. The right question is which layer you are solving for.

ScenarioBest Tool
Writing, debugging, or refactoring codeClaude Code (conversation mode)
Large codebase task with unknown decompositionClaude Code Dynamic Workflows
Repeatable specialist coding tasksClaude Code Subagents
Complex stateful app workflow with conditional branchingLangGraph
Production agent that must survive crashesTemporal + any agent SDK
Long-running workflow with human approval gatesTemporal
Financial or irreversible multi-step operationsTemporal
Content pipeline with defined role separationCrewAI
SaaS integrations on structured datan8n

Claude Code vs LangGraph. These are not competitors. Claude Code is a development-time tool. LangGraph is a runtime application framework for stateful workflows that run in production. Use Claude Code to build LangGraph applications. The important constraint: Claude Code is locked to Anthropic's Claude models. LangGraph is model-agnostic via LangChain integrations.

Claude Code vs Temporal. Temporal wraps any execution (including Claude-powered agents) in crash-proof durability. Claude Code has no cross-session state persistence, no exactly-once semantics, and no auditable execution history. If your agent touches money, legal records, or any irreversible operation, Temporal belongs in the stack.

The complementary architecture for production AI agents: Claude Agent SDK handles the AI reasoning and tool-use loop. Temporal wraps it for fault tolerance. OpenAI Codex and Replit Agent 3 both chose this split.

Best Practices for Claude Code Workflows

Default to pipeline(), not parallel(). pipeline() starts processing item N+1 as soon as item N finishes its first stage, eliminating idle gaps. Only reach for parallel() when a stage genuinely needs all prior results at once.

Use schema for structured output whenever you need to parse agent results. Passing a JSON Schema to agent() forces the subagent into a structured-output tool call with automatic retry on mismatch. This removes brittle text parsing from your orchestration logic.

Set the 1-hour cache TTL on long workflows. For runs with phases separated by more than a few minutes, the default 5-minute cache TTL will cost you 3x to 6x more than necessary. The 1-hour TTL flag costs 2x the write price but saves far more on reads for multi-phase runs.

Guard budget-sensitive loops. Every infinite-until-convergence loop should check budget.total before iterating: if (budget.total && estimatedTokensUsed > budget.total * 0.8) { log('approaching budget, stopping early'); break }. Without this, the loop runs until the 1,000-agent cap.

Use phase() and log() generously. Well-labeled phases and narrator lines in the /workflows dashboard make it possible to pause a run that is going sideways before it finishes. A workflow with no phase labels is a black box until it finishes.

Use isolation: 'worktree' only when agents genuinely write to the same files. Worktree isolation spawns a separate git worktree per agent, which is correct for parallel file-writing tasks but adds overhead you do not need for read-only agents.

Save workflows that work. Press s in the /workflows dashboard on a completed run and save to .claude/workflows/ (project-shared) or ~/.claude/workflows/ (personal). A workflow you save once becomes a /command usable on every future run with the same pattern.

Frequently Asked Questions

How many agents can Claude Code run in parallel?

Claude Code dynamic workflows cap concurrent agent execution at 16 agents running simultaneously. The total agent count across an entire run is capped at 1,000. These limits are enforced by the workflow runtime regardless of your subscription plan. The concurrency cap may be lower on machines with limited CPU cores.

How do I trigger a Claude Code dynamic workflow?

Three ways: include the word "workflow" anywhere in a prompt (Claude Code highlights the keyword and writes an orchestration script), run the /deep-research command, or set /effort ultracode which automatically plans a workflow for every substantive task in the session. Press alt+w to suppress the keyword trigger for a single prompt without disabling the feature globally.

Is Claude Code dynamic workflow available on the free or Pro plan?

Dynamic workflows are off by default on Pro ($20/month) and must be enabled manually via /config. They are on by default on Max ($100/month and $200/month tiers) and Team plans. On Enterprise plans they are off by default and require admin activation. All plans require CLI v2.1.154 or later.

How is Claude Code different from Cursor for agent workflows?

Claude Code is a terminal-native agentic tool designed for long-running, multi-agent orchestration across an entire codebase. It has hooks, MCP integrations, skills, dynamic workflows, and operates entirely from the command line with full filesystem and shell access. Cursor is IDE-integrated and optimized for rapid single-file editing within VS Code. For daily code editing in an IDE, Cursor wins on ergonomics. For repo-wide migrations, security audits, or multi-agent builds, Claude Code's workflow system has no direct equivalent in Cursor.

What real-world tasks have Claude Code dynamic workflows been used for?

The most cited example is Bun's Zig-to-Rust rewrite: approximately 750,000 lines ported in 11 days to 99.8% test suite pass rate on Linux x64 (PR #30412, merged May 14, 2026). Rakuten cut feature delivery from 24 working days to 5 days using parallel Claude Code sessions. Uber reached 84% Claude Code adoption across roughly 5,000 engineers, with approximately 70% of committed code AI-originated by March 2026.

Wrapping Up

Claude Code dynamic workflows shift orchestration from the model's context window into a JavaScript runtime, which is the structural change that makes 500-agent and 1,000-agent runs viable without quality degradation. The primitives are small and composable. The costs are real and require guardrails. The gotchas (JS-only scripts, banned non-deterministic built-ins, acceptEdits auto-apply, the 5-minute cache cliff) are specific enough to work around once you know them.

Start with a scoped use case: a parallel code review, a documentation sweep across a module boundary, or a security audit on a well-bounded surface. Save the run as a command. Iterate on the script. The workflows that work reliably are the ones you refine over several runs, not the ones you fire at a codebase-wide task on day one.


Posted by @speedy_devv

Continue in Workflow

  • Claude Code ベストプラクティス
    Claude Codeで成果を出すエンジニアを分ける5つの習慣: PRD、モジュラーなCLAUDE.mdのルール、カスタムスラッシュコマンド、/clearリセット、そしてシステム進化の思考法。
  • Claude Code オートモード
    2つ目の Sonnet モデルが、Claude Code のすべてのツール呼び出しを実行前に審査します。オートモードがブロックするもの・許可するもの、そして settings.json に追加される許可ルールについて解説します。
  • Channels, Routines, Teleport, Dispatch
    The four Claude Code features Anthropic shipped in March and April 2026 that turn the CLI into an event-driven coordination layer across phone, web, and desktop.
  • Claude Code Channels
    プラグイン MCPサーバーを使って Claude Code を Telegram、Discord、iMessage に接続する方法。セットアップの手順と、接続する価値のある非同期モバイルワークフローを解説します。
  • Building a Next.js App With Claude Code
    How to use Claude Code to build a full Next.js 16 app — from project setup through App Router, Server Components, and deployment.
  • Claude Code Pricing: What You'll Actually Pay
    Claude Code is free to install. What you pay depends on your plan. A plain-English breakdown of every tier, real usage costs, and which plan fits your workflow.

More from Handbook

  • エージェントの基礎
    Claude Codeでスペシャリストエージェントを構築する5つの方法:タスクサブエージェント、.claude/agents YAML、カスタムスラッシュコマンド、CLAUDE.mdペルソナ、パースペクティブプロンプト。
  • エージェント・ハーネス・エンジニアリング
    ハーネスとは、AIエージェントを構成するモデル以外のすべての層のことです。5つの制御レバー、制約のパラドックス、そしてなぜハーネス設計がモデルよりもエージェントのパフォーマンスを左右するのかを学びましょう。
  • エージェントパターン
    オーケストレーター、ファンアウト、バリデーションチェーン、スペシャリストルーティング、プログレッシブリファインメント、ウォッチドッグ。Claude Code のサブエージェントを組み合わせる6つのオーケストレーション形状。
  • エージェントチームのベストプラクティス
    Claude Code エージェントチームの実証済みパターン。コンテキストが豊富なスポーンプロンプト、適切なサイズのタスク、ファイルオーナーシップ、デリゲートモード、v2.1.33〜v2.1.45 の修正内容。

設定をやめて、構築を始めよう。

AIオーケストレーション付きSaaSビルダーテンプレート。

Claude Code v2.1.122 Release Notes

alwaysLoad in MCP config, PostToolUse hooks for all tools, PR URL session lookup, plugin pruning, and multi-GB memory leak fixes.

Claude Code ベストプラクティス

Claude Codeで成果を出すエンジニアを分ける5つの習慣: PRD、モジュラーなCLAUDE.mdのルール、カスタムスラッシュコマンド、/clearリセット、そしてシステム進化の思考法。

On this page

Table of Contents
What Is Claude Code's Dynamic Workflow System?
How Claude Code Workflows Work: Architecture
Real-World Use Cases for Claude Code Workflows
Claude Code Workflow Costs, Limits, and Efficiency
Caveats and Gotchas Developers Hit
Claude Code Workflows vs LangGraph, Temporal, and Others
Best Practices for Claude Code Workflows
Frequently Asked Questions
How many agents can Claude Code run in parallel?
How do I trigger a Claude Code dynamic workflow?
Is Claude Code dynamic workflow available on the free or Pro plan?
How is Claude Code different from Cursor for agent workflows?
What real-world tasks have Claude Code dynamic workflows been used for?
Wrapping Up

設定をやめて、構築を始めよう。

AIオーケストレーション付きSaaSビルダーテンプレート。