Claudeadvanced

How to Use Background Agents and Subagents in Claude Code

Master Claude Code's background agent and subagent capabilities to run parallel tasks, delegate work, and build complex automated workflows. Learn Task tool patterns for efficient multi-agent orchestration.

9 min readUpdated January 2025

Want us to handle this for you?

Get expert help →

Claude Code's agent architecture enables sophisticated multi-agent workflows where you can delegate tasks to specialized subagents, run operations in parallel, and orchestrate complex automated processes. Understanding how to leverage background agents effectively can dramatically improve your productivity when working with large codebases or complex multi-step tasks.

Understanding Claude Code's Agent Architecture

Claude Code operates as an agentic AI system where the main session acts as a primary agent with access to various tools. This primary agent can spawn subagents to handle specific tasks, creating a hierarchical task execution model.

The architecture consists of three layers:

  1. Primary Agent: Your main Claude Code session that interprets commands, plans work, and coordinates subagents
  2. Subagents: Specialized agents spawned via the Task tool for focused work on specific problems
  3. Background Agents: Subagents that run asynchronously, allowing the primary agent to continue other work

Each agent maintains its own context window but shares access to the same underlying tools (file system, bash, grep, etc.). This enables true parallel execution without blocking your main workflow.

When to Use Background Agents vs Inline Execution

Choosing between inline execution and background agents depends on task characteristics:

Use inline execution when:

  • Tasks require immediate results for decision-making
  • Operations are quick (under 30 seconds)
  • You need to see output before proceeding
  • Tasks have dependencies on each other

Use background agents when:

  • Tasks are independent and can run in parallel
  • Operations are long-running (builds, tests, large searches)
  • You want to continue working while tasks complete
  • Multiple similar tasks can be batched

Example scenarios for background agents:

  • Running test suites across multiple modules
  • Searching large codebases for patterns
  • Building documentation for multiple components
  • Analyzing security vulnerabilities across services

Spawning Subagents with the Task Tool

The Task tool is your interface for creating subagents. Here's how to use it effectively.

Basic Task Creation

To spawn a subagent for a specific task:

Create a task to analyze the authentication module for security vulnerabilities.
Focus on SQL injection, XSS, and authentication bypass risks.

Claude Code will use TaskCreate to spawn a subagent with a clear objective. The subagent receives its own context and works independently until completion.

Task Tool Parameters

When Claude Code creates tasks internally, it uses these key parameters:

  • subject: Brief task title in imperative form ("Analyze auth module")
  • description: Detailed requirements and acceptance criteria
  • activeForm: Present continuous form for status display ("Analyzing auth module")
  • metadata: Optional key-value pairs for task categorization

Structuring Effective Task Descriptions

Well-structured task descriptions lead to better subagent performance:

Subject: Review API rate limiting implementation

Description:
1. Examine rate limiting logic in /src/middleware/rateLimiter.ts
2. Verify limits are applied consistently across all endpoints
3. Check for bypass vulnerabilities in header handling
4. Report any endpoints missing rate limiting
5. Suggest improvements for distributed rate limiting

Acceptance criteria:
- List of all rate-limited endpoints with their limits
- Any security concerns identified
- Recommendations for improvements

Available Subagent Types

Claude Code can spawn different types of subagents based on the task requirements:

General-Purpose Agents

Handle broad tasks like code analysis, documentation, or multi-step investigations. These have full tool access and can read, write, and execute commands.

Explore Agents

Specialized for codebase exploration without modification. Use these when you need to understand code structure, find patterns, or investigate issues without changing anything.

Plan Agents

Focus on creating detailed plans and task breakdowns. They analyze requirements and produce structured action plans that other agents can execute.

Bash Agents

Optimized for command-line operations. Use these for running builds, tests, deployments, or system administration tasks.

Background Execution with run_in_background

To run a task asynchronously, the Task tool accepts the run_in_background parameter:

Create a background task to run the full test suite while I continue
working on the authentication refactor.

When a background agent is spawned:

  1. Claude Code creates the task with run_in_background: true
  2. You receive a task ID for tracking
  3. The subagent begins execution independently
  4. You continue with your main work
  5. Background agent reports completion when finished

Checking Agent Status and Retrieving Results

Monitor and retrieve results from background agents using these patterns.

Listing Active Tasks

To see all tasks and their status:

Show me the current task list and status of background agents.

Claude Code will use TaskList to display:

  • Task IDs and subjects
  • Current status (pending, in_progress, completed)
  • Owner assignment
  • Blocking dependencies

Retrieving Task Results

Once a background agent completes:

Get the results from task ID xyz that was analyzing security vulnerabilities.

TaskGet retrieves full task details including:

  • Complete description and requirements
  • Final status and completion notes
  • Any blockers encountered
  • Dependencies on other tasks

TaskOutput for Background Results

For long-running background tasks, use TaskOutput to retrieve results:

What's the output from the test suite background task?

Coordinating Multiple Parallel Agents

Complex workflows often require orchestrating multiple agents working simultaneously.

Parallel Task Spawning

When tasks are independent, spawn them in parallel:

Run these three tasks in parallel:
1. Analyze frontend bundle size and suggest optimizations
2. Check backend API response times against benchmarks
3. Review database query performance for N+1 issues

Claude Code will create multiple tasks that execute concurrently, significantly reducing total completion time.

Task Dependencies

Some tasks must wait for others. Use blocking relationships:

Task A: Generate API documentation from source code
Task B: Review documentation for accuracy (blocked by Task A)
Task C: Publish documentation to site (blocked by Task B)

TaskUpdate establishes these relationships via addBlockedBy and addBlocks parameters.

Aggregating Results

After parallel tasks complete, aggregate findings:

Combine the results from all three performance analysis tasks
into a unified report with prioritized recommendations.

Best Practices for Multi-Agent Workflows

Follow these guidelines for effective agent orchestration:

1. Clear Task Boundaries Each task should have a single, well-defined objective. Avoid multi-purpose tasks that try to accomplish too many things.

2. Appropriate Granularity Tasks that are too small create overhead; tasks that are too large become unwieldy. Aim for tasks that take 1-5 minutes of focused work.

3. Avoid File Conflicts When multiple agents might modify the same files, either:

  • Serialize those tasks with blocking dependencies
  • Assign different file sets to different agents
  • Have agents create separate output files that you merge

4. Resource Awareness Background agents consume system resources. Limit concurrent agents based on your system capacity, typically 2-4 simultaneous agents.

5. Regular Status Checks For long-running workflows, periodically check task status to catch issues early rather than discovering problems after hours of execution.

Error Handling and Debugging Agents

When agents encounter problems, use these debugging strategies.

Common Issues

Agent stalls or hangs:

  • Check if waiting for user input (permissions)
  • Verify network connectivity for API calls
  • Review task description for ambiguity

Unexpected results:

  • Task description may be unclear
  • Agent may have insufficient context
  • Required files or dependencies may be missing

Debugging Steps

  1. Review task details: Use TaskGet to see full task specification
  2. Check task logs: Background tasks maintain execution logs
  3. Verify preconditions: Ensure files/dependencies exist
  4. Test incrementally: Break complex tasks into smaller testable units

Recovery Strategies

If an agent fails:

  • Update task status to reset
  • Modify description with clarifications
  • Re-run with additional context
  • Split into smaller, more focused tasks

Next Steps

After mastering background agents:

  1. Explore automation hooks: Combine agents with Claude Code hooks for fully automated workflows
  2. Build custom task templates: Create reusable task patterns for common operations
  3. Integrate with CI/CD: Use agents within continuous integration pipelines
  4. Monitor performance: Track agent execution times to optimize task distribution

Need help building sophisticated AI-powered development workflows? Inventive HQ specializes in AI integration for development teams. Contact us to discuss how we can accelerate your engineering productivity with Claude Code and other AI tools.

Frequently Asked Questions

Find answers to common questions

Background agents are Claude Code sessions that run independently of your main conversation. You can spawn them to handle tasks in parallel while continuing your primary work. They run asynchronously and report back when complete.

Need Professional IT & Security Help?

Our team of experts is ready to help protect and optimize your technology infrastructure.