Claude Code: Building a Parallel AI Agent Pipeline with Subagents and Orchestrator Patterns
A team that significantly shortened the PR code review cycle using nine parallel AI agents is drawing attention. The method involves security checks, code quality analysis, and static analysis running simultaneously, with an orchestrator integrating the results in order of severity to make a final decision. It is a structure where agent teams with separated roles handle tasks that would have resulted in context window saturation and degraded response quality if everything had been entrusted to a single AI session.
Developers who have already used Claude Code or are seriously considering adopting it have likely experienced this limitation. If you cram code reviews, security audits, and implementations into a single session, the context not only fills up quickly but also contaminates subsequent tasks with the context of the preceding work. Claude Code's orchestrator-subagent architecture tackles this problem head-on through role separation and context isolation.
This article covers how to implement parallel code review pipelines and end-to-end development pipelines with actual agent definition files. Additionally, a separate section outlines the criteria for determining when to use and when not to use sub-agents. While assuming you have installed and are familiar with the basic usage of Claude Code, the core concepts are explained sequentially so that even developers new to agent systems can follow along.
Key Concepts
Separation of Roles Between Orchestrator and Sub-Agent
The Orchestrator pattern consists of three layers.
| Hierarchy | Role | Responsibilities |
|---|---|---|
| Orchestrator | Receive high-level goals and break down tasks | Call sub-agents, collect and integrate results |
| Sub-agent | Execute detailed tasks independently | Perform a single delegated task and return the result |
| Agent Teams (Experimental) | Team Lead + Peer Agent Collaboration | Shared Task List, Peer-to-Peer Messaging, File Locking |
사용자 요청
│
▼
┌──────────────────────────────┐
│ 오케스트레이터 │
│ (작업 분해 → 위임 → 통합) │
└──────┬───────────┬────────────┘
│ │
▼ ▼
[서브에이전트A] [서브에이전트B]
독립 컨텍스트 독립 컨텍스트Core Structure: Each sub-agent runs in an independent context window. The work of sub-agent A does not pollute the context of sub-agent B.
Agent Teams Note: CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=true is an experimental feature activated via the environment variable. Currently, it is recommended to approach this as a proof-of-concept rather than for production deployment, and stability is not guaranteed.
Sub-agent definition: .claude/agents/ directory
Sub-agents are defined in the Markdown file under .claude/agents/. Declare the name, role, and allowed tools using YAML front matter, and write the behavioral guidelines in the body.
---
name: security-reviewer
description: 보안 취약점 전문 리뷰어. SQL 인젝션, 인증 취약점, 하드코딩 시크릿을 검사한다.
tools:
- read_file
- bash
---
당신은 보안 전문 코드 리뷰어입니다.
다음 항목을 반드시 검사하세요:
1. SQL 인젝션 가능성
2. 인증 및 세션 관리 취약점
3. 하드코딩된 비밀키 또는 자격증명
4. 입력값 검증 누락
심각도(Critical / High / Medium / Low)로 분류하여 보고하세요.CLAUDE.md vs .claude/agents/*.md: It is a recommended pattern to separate project-wide behavioral rules in CLAUDE.md and sub-agent definitions called by specific roles in .claude/agents/.
Task Tool: Sub-agent Invocation Mechanism
The orchestrator explicitly invokes sub-agents through the Claude Code built-in task tool. Using the task tool loads the .claude/agents/*.md file with the specified agent name and runs it as a standalone Claude session. To create other sub-agents, the tools entry in the orchestrator agent definition file must contain task.
Parallel Execution Principle: When an orchestrator issues multiple task calls within the same response, Claude Code executes them concurrently in separate sessions. This structure is possible because each session has its own context. However, tasks with sequential dependencies (such as when the output of A is the input of B) cannot be executed in parallel.
CLI Execution Method: Start an interactive session with the claude command, then call it by explicitly referencing the orchestrator agent.
# 대화형 세션 시작
claude
# 세션 내에서 오케스트레이터 에이전트 호출 예시:
# "@orchestrator-code-review 에이전트를 사용해서 현재 브랜치의 변경 사항을 리뷰해줘"Use the -p flag when running non-interactively (CI/CD, etc.).
# 비대화형 실행 (CI/CD 파이프라인에서)
claude -p "orchestrator-code-review 에이전트로 \
$(git diff main...HEAD --name-only)를 리뷰하고 \
결과를 review-report.md에 저장해줘" \
--output-format jsonAdvanced: GitHub Actions Integration
If you add the above claude -p "..." command as a step in the GitHub Actions workflow, the code review pipeline will run automatically when a PR is opened. To control this programmatically, you can create an agent directly through the subagents endpoint of the Anthropic Agent SDK and receive the results via streaming.
Checklist for Deciding on Sub-Agent Implementation
Sub-agents are powerful, but applying them to every task only increases cost and complexity. Make your decision based on the criteria below.
✅ When Sub-agents Are Effective
- Tasks can be executed independently (A and B do not need to wait for each other's results)
- Tasks require different expertise (security, performance, and style each require different perspectives)
- Handles large codebases that cannot be managed by a single context window (200K tokens).
- I want to separate the verification phase from the implementation phase (bias blocking)
- A standardized workflow that the entire team can reuse is needed.
❌ If there is an excess of sub-agents
- Simple conversion or summarization tasks completed within 5 minutes
- There is no benefit to parallelization due to strong sequential dependency between tasks.
- Environments sensitive to token costs (sub-agents significantly increase costs compared to standard sessions depending on the number of agents and output length)
- The scope of work for the sub-agent is unclear (if the scopes overlap, result conflicts occur)
Rule of thumb for judgment: "If this task is assigned to two separate experts, are the results independently meaningful?" — If so, they are sub-agent candidates.
Practical Application
Example 1: Parallel Code Review Pipeline
When to use this pattern: When review items are independent and concurrent execution can reduce the overall time required.
PR 변경 파일
│
▼
┌─────────────────────────────────────────────┐
│ 오케스트레이터 │
│ (결과 수집 → Critical~Low 순 통합 → 판정) │
└──────┬──────────┬──────────┬────────────────┘
│ │ │ │
▼ ▼ ▼ ▼
[linter] [security] [code-rev] [quality]
정적분석 취약점검사 개선5선 복잡도분석
(병렬) (병렬) (병렬) (병렬)Definition of Orchestrator Agent
<!-- .claude/agents/orchestrator-code-review.md -->
---
name: orchestrator-code-review
description: PR 코드 리뷰를 전문 에이전트에게 병렬 위임하고 결과를 통합하는 오케스트레이터
tools:
- task
- read_file
---
당신은 코드 리뷰 오케스트레이터입니다.
## 실행 순서
1. 변경된 파일 목록을 파악한다
2. 다음 에이전트를 **동시에** 호출한다:
- `security-reviewer`: 보안 취약점 검사
- `code-quality-reviewer`: 품질 및 복잡도 분석
- `linter-agent`: 정적 분석 및 스타일
3. 모든 에이전트 결과를 수집한다
4. Critical → High → Medium → Low 순으로 통합 리포트를 작성한다
5. 각 이슈에 담당 에이전트 출처를 명시한다
## 출력 형식
### 최종 판정: [APPROVED / REQUEST_CHANGES / BLOCKED]
| 심각도 | 이슈 | 파일:라인 | 출처 에이전트 |
|--------|------|-----------|--------------|The task in the tools entry is the key to creating sub-agents. Without this entry, the orchestrator cannot call other agents and will handle it itself.
Example of Sub-agent Definition
<!-- .claude/agents/linter-agent.md -->
---
name: linter-agent
description: ESLint/Pylint 정적 분석 및 IDE 진단을 수집하여 보고한다
tools:
- bash
- read_file
---
당신은 정적 분석 전문가입니다.
제공된 파일에 대해 다음을 실행하고 결과를 보고하세요:
1. ESLint 또는 Pylint 실행 (bash 사용)
2. 스타일 가이드 위반 항목 목록 작성
3. 자동 수정 가능한 항목과 수동 검토 필요 항목을 구분하여 보고| Agent | Role | Parallel Execution |
|---|---|---|
linter-agent |
Static Analysis, Style Checking | ✅ |
security-reviewer |
SQL Injection, Authentication Vulnerability, Secret Check | ✅ |
code-quality-reviewer |
Complexity, Duplicate Code, Dead Code | ✅ |
orchestrator-code-review |
Result Collection and Integrated Report Generation | ❌ (Sequential) |
Example 2: End-to-End Development + Verification Pipeline
When to use this pattern: A linear pipeline where the output of each stage becomes the input of the next stage. When order is more important than parallelization.
[pm-spec] → [architect-review] → [implementer-tester] → [black-box-verifier]The core of this pattern is separating the final verification step into a separate agent. Implementation agents tend to overlook defects when directly verifying the code they wrote due to the context they already know ("phone game" bias). The verification agent blocks this bias by approaching the process as a black box, completely unaware of the implementation process.
<!-- .claude/agents/pm-spec.md -->
---
name: pm-spec
description: 자연어 요구사항을 구조화된 워킹 스펙 문서로 변환한다
tools:
- write_file
- read_file
---
당신은 시니어 PM입니다. 입력받은 요구사항을 아래 형식의 스펙 문서로 작성하세요.
출력 파일: `docs/spec-{feature-name}.md`
## 스펙 문서 형식
- **목표**: 한 문장 요약
- **사용자 스토리**: As a ... I want ... So that ...
- **수용 기준(AC)**: 체크리스트
- **비기능 요구사항**: 성능, 보안, 접근성
- **범위 외(Out of Scope)**: 명시적 제외 항목<!-- .claude/agents/architect-review.md -->
---
name: architect-review
description: 스펙 문서를 검토하고 기존 아키텍처 기준으로 설계 적합성을 검증한다
tools:
- read_file
- write_file
- bash
---
당신은 시니어 아키텍트입니다. pm-spec이 생성한 스펙 문서를 검토하세요.
검증 항목:
1. 기존 코드베이스와의 정합성 (`src/` 디렉터리 구조 참고)
2. 성능 및 확장성 위험 요소
3. 보안 아키텍처 고려사항
4. 구현 전 해결해야 할 선행 조건
출력: `docs/arch-review-{feature-name}.md`<!-- .claude/agents/implementer-tester.md -->
---
name: implementer-tester
description: 스펙과 아키텍처 리뷰를 바탕으로 코드를 구현하고 테스트를 작성한다
tools:
- read_file
- write_file
- bash
- edit_file
---
당신은 풀스택 엔지니어입니다.
실행 순서:
1. `docs/spec-*.md`와 `docs/arch-review-*.md`를 읽는다
2. 수용 기준을 모두 충족하는 코드를 구현한다
3. 각 AC에 대응하는 유닛 테스트를 작성한다
4. `pnpm test`로 전체 테스트를 실행하고 모두 통과시킨다
5. `README.md` 또는 관련 문서를 업데이트한다<!-- .claude/agents/black-box-verifier.md -->
---
name: black-box-verifier
description: 구현 컨텍스트 없이 완성된 코드를 블랙박스 테스트로 검증한다
tools:
- bash
- read_file
---
당신은 구현 과정을 전혀 모르는 QA 엔지니어입니다.
제공된 코드와 스펙 문서만 보고 독립적으로 검증하세요.
검증 절차:
1. `pnpm test` — 전체 테스트 통과 확인
2. `pnpm build` — 빌드 성공 확인
3. 스펙의 수용 기준을 하나씩 수동 대조
4. 엣지 케이스 3개 이상 추가 테스트
## 중요
구현자의 의도나 설명을 참고하지 마세요. 코드가 스스로 말하게 하세요.Isn't it redundant for both implementer-tester and black-box-verifier to execute pnpm test? implementer-tester is the implementer's perspective of writing and passing tests, and black-box-verifier is the validator's perspective of independently comparing the specification's acceptance criteria with edge cases. They execute the same command for different purposes.
Pros and Cons Analysis
Advantages
| Item | Content |
|---|---|
| Parallel Execution | Process independent subtasks concurrently to reduce total time by several times |
| Context Isolation | Prevents main agent contamination as each sub-agent uses an independent context |
| Role Specialization | Separation of responsibilities into specialized agents for each role, such as security, quality, and documentation |
| Bypass Context Window | Split large tasks exceeding the 200K token limit into subtasks |
| Reusability | Standardize workflows by sharing the .claude/agents/ definition file across the entire team |
Disadvantages and Precautions
| Item | Content | Response Plan |
|---|---|---|
| Increased Token Costs | Costs increase significantly compared to standard sessions depending on the number of agents and output length. Differences are large depending on usage patterns | Maintain a single agent for simple tasks; pre-calculate ROI for parallelization |
| Context Accumulation | The phenomenon where the outputs of parallel subagents all accumulate in the orchestrator context window (named "Context Bubbling" in this article) | Simplify the subagent output format |
| Loss of Intermediate Information | Intermediate information may be lost as the context becomes longer (limitations identified in Anthropic research) | Summarize key information and place it at the beginning/end |
| Excessive Delegation | Tendency to delegate tasks to sub-agents even when the model can handle them directly | Specify "Direct Handling Requirements" in Orchestrator Prompts |
| Coordination Complexity | Debugging is more complex than a single agent when scope overlaps between agents | Explicitly document the scope of responsibility for each agent |
"Context bubbling" is a term used in this article and is not an official term. It refers to a phenomenon where the outputs of parallel sub-agents accumulate in the orchestrator context window, causing the orchestrator's context consumption to skyrocket as the number of agents increases.
The Most Common Mistakes in Practice
Mistake 1: Delegating all tasks to a sub-agent
Dividing simple tasks that can be completed in 5 minutes into sub-agents only increases communication overhead and token costs between the orchestrator and sub-agents. Apply sub-agents only to tasks that can be executed independently, offer clear parallelization benefits, and require specialized context. You can use the previously presented adoption decision checklist as the criteria for judgment.
Mistake 2: Assumption of Implicit State Sharing Between Sub-agents
It is often assumed that Sub-Agent B automatically recognizes files generated by Sub-Agent A. Since sub-agents run in an independent context, the file path and expected output format must be explicitly passed to the orchestrator prompt.
# 잘못된 방식 (암묵적 의존)
`pm-spec` 에이전트를 실행한 후 `architect-review`를 실행하세요.
# 올바른 방식 (명시적 전달)
`pm-spec` 에이전트를 실행하여 `docs/spec-login-feature.md`를 생성하세요.
완료되면 `architect-review` 에이전트에 다음을 전달하여 실행하세요:
"검토할 스펙 파일: docs/spec-login-feature.md"Mistake 3: Relying on Auto-routing
Even if the description field matches the current task well, the orchestrator often handles it directly in the main session without calling the sub-agent. Explicit calling via the task tool is currently much more reliable. Specify at the orchestrator prompt which agent to call and when, along with its name.
In Conclusion
The essence of the Sub-Agent pattern is not to use more AI, but to transform the architecture to achieve quality and scale impossible with a single agent by handling complex tasks like a team of experts with separated roles.
3 Steps to Start Right Now — However, a project with Claude Code installed is a prerequisite:
- Create a
.claude/agents/security-reviewer.mdfile to add a security review agent to an existing project. Check out over 100 ready-to-use templates in awesome-claude-code-subagents. - Select one of the tasks you currently perform most repeatedly (PR reviews, test writing, documentation updates) and design it as an orchestrator-subagent pipeline. You can use the structure of Example 1 or Example 2 in this article as a starting point.
- Set up
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=trueand explore Agent Teams. It is recommended to approach this with the purpose of directly experiencing the peer-to-peer agent collaboration pattern rather than deploying it to production.
Resources to Read First: The official documentation Create custom subagents and How and when to use subagents serves as the direct starting point for this article. The remaining reference materials are for advanced study.
Next Post: How to Build an Autonomous DevOps Pipeline by Connecting External Tools Like GitHub, Slack, and Sentry to Claude Code Subagents Using MCP (Model Context Protocol)
Reference Materials
Key Materials (Start Here)
- Create custom subagents | Claude Code Official Documentation
- How and when to use subagents in Claude Code | Claude Blog
Advanced Materials
- Orchestrate teams of Claude Code sessions | Claude Code Official Documentation
- Multi-agent coordination patterns: Five approaches and when to use them | Claude Blog
- When to use multi-agent systems (and when not to) | Claude Blog
- Building effective agents | Anthropic Research
- How we built our multi-agent research system | Anthropic Engineering
- The Task Tool: Claude Code's Agent Orchestration System | DEV Community
- 9 Parallel AI Agents That Review My Code (Claude Code Setup) | HAMY
- Shipyard | Multi-agent orchestration for Claude Code in 2026
- Best practices for Claude Code subagents | PubNub Blog
- Connect Claude Code to tools via MCP | Claude Code 공식 문서
- Subagents in the SDK | Claude API Docs
- GitHub - VoltAgent/awesome-claude-code-subagents
- GitHub - wshobson/agents
- GitHub - ruvnet/ruflo