Background Tasks
Run long commands, subagents, and whole sessions in the background, and act on task notifications when they finish.
What You’ll Learn
Some operations take time. Running a full test suite might take 30 seconds. Building a Docker image might take 2 minutes. Deploying to staging might take 5 minutes. Without background tasks, Claude Code would sit idle until each command finished, and so would you.
By the end of this session, you’ll understand:
- Why some tasks should run in the background
- The background task lifecycle: launch, monitor, notify
- How task notifications report completions
- When to use foreground vs. background execution
- How to keep doing useful work while waiting
- When to background a command, a subagent, or a whole session
The Problem
Consider this scenario:
User: "Run the full test suite, then fix any failing tests."
Without background tasks:
AI: Runs test suite...
████████░░░░░░░░░░░░ 45%
... (you wait 90 seconds) ...
████████████████████ 100%
AI: "3 tests failed. Let me fix them."
Those 90 seconds are wasted. The AI could have been reading the test files, analyzing likely failure patterns, or preparing fixes. Instead, it blocked on a synchronous call and did nothing.
This is the idle waiting problem. Synchronous execution means the AI can only do one thing at a time, even when the current operation doesn’t need its attention.
How It Works
Foreground vs. Background
Claude Code supports two execution modes:
Foreground (blocking):
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Start │────►│ Wait... │────►│ Result │
│ command │ │ (idle) │ │ ready │
└──────────┘ └──────────┘ └──────────┘
Time: ============================|
Background (non-blocking):
┌──────────┐ ┌──────────────────────────────┐
│ Start │────►│ Continue working... │
│ command │ │ Write code, read files, plan │
└──────────┘ │ ... │
│ ◄── Notification: "Done!" │
└──────────────────────────────────┘
Time: ====| (productive work fills the gap)
The key difference: in background mode, the AI gets control back immediately and can do other work while the operation runs.
The Background Task Lifecycle
Every background task follows three phases:
┌───────────────────────────────────────────────────────┐
│ Background Task Lifecycle │
│ │
│ Phase 1: LAUNCH │
│ ┌───────────────────────────────────────────┐ │
│ │ Bash call with run_in_background: true │ │
│ │ → command starts as its own process │ │
│ │ → Claude gets a task ID + output file │ │
│ │ → Claude continues with the next action │ │
│ └───────────────────────────────────────────┘ │
│ │
│ Phase 2: MONITOR │
│ ┌───────────────────────────────────────────┐ │
│ │ The process runs independently │ │
│ │ → stdout/stderr go to the output file │ │
│ │ → exit status is tracked │ │
│ │ → no Claude attention required │ │
│ └───────────────────────────────────────────┘ │
│ │
│ Phase 3: NOTIFY │
│ ┌───────────────────────────────────────────┐ │
│ │ Process ends: success, failure, or stop │ │
│ │ → Claude Code sends a task notification │ │
│ │ → an idle session starts a new turn │ │
│ │ → Claude reads the output file and acts │ │
│ └───────────────────────────────────────────┘ │
│ │
└───────────────────────────────────────────────────────┘
Launching a Background Task
The run_in_background parameter is available on the Bash tool:
{
"type": "tool_use",
"name": "Bash",
"input": {
"command": "npm test",
"description": "Run full test suite",
"run_in_background": true
}
}
When this executes:
- The test suite starts running in a separate process
- Claude immediately gets back a background task ID and the path of the file the output is being written to
- The AI’s next action can be anything — it doesn’t have to wait
Compare with a foreground call (the default):
{
"type": "tool_use",
"name": "Bash",
"input": {
"command": "npm test",
"description": "Run full test suite"
}
}
This blocks until npm test finishes or reaches its timeout (two minutes by default; Claude can request up to ten). At the timeout, Claude Code moves the command to the background instead of killing it, unless the command starts with sleep.
You can also background work yourself: press Ctrl+B to move a running command to the background (press it twice inside tmux). Run /tasks to list the background work in the current session and stop any of it.
Task Notifications
When a background task completes, fails, or is stopped, Claude Code sends Claude a task notification. It carries the status, a short summary, and the path of the output file; Claude reads the full output with the Read tool. (The separate TaskOutput tool was removed in Claude Code 2.1.277.) Claude Code marks the notification as not coming from you, so Claude doesn’t treat it as an instruction or an approval.
Turn N:
AI launches background task: "npm test"
AI continues: reads files, writes code...
Turn N+1 (the notification starts it if the session is idle):
[Task notification, not user input]
Task: Run full test suite
Status: failed
Output: <path of the task's output file>
AI reads the output file:
"47 passed, 3 failed
FAIL: src/auth/login.test.ts
FAIL: src/auth/session.test.ts
FAIL: src/api/users.test.ts"
AI: "The test suite found 3 failures. Let me fix them."
The notification arrives naturally in the conversation flow. The AI doesn’t need to poll or check — it’s informed automatically when the background task finishes. When Claude needs to react while a command is still running, such as to new log lines or a changing CI status, it can use the Monitor tool instead, which feeds each new output line back to Claude as it arrives.
What Runs Well in Background
Not every command belongs in the background. Here’s a decision framework:
Need the result to decide your next action?
├── YES → Foreground (blocking)
│ Examples:
│ - "cat package.json" (need to read contents now)
│ - "git status" (need to know state before committing)
│ - "ls src/" (need to know what files exist)
│
└── NO → Background (non-blocking)
Examples:
- "npm test" (can write code while tests run)
- "docker build ." (can prepare deployment config while building)
- "pnpm build" (can write documentation while building)
| Operation | Duration | Background? | Why |
|---|---|---|---|
cat file.txt | < 1s | No | Result needed immediately |
git diff | < 1s | No | Need to see changes now |
npm test | 10-120s | Yes | Can work while tests run |
docker build | 30-300s | Yes | Long build, result not needed immediately |
npm install | 5-30s | Maybe | Depends on whether you need the packages right away |
pnpm build | 5-60s | Yes | Can prepare deploy config in parallel |
eslint . | 5-30s | Yes | Can continue coding while linting |
Interleaving Background and Foreground Work
The real power emerges when you combine background tasks with productive foreground work:
Timeline:
├── Launch: npm test (background)
├── Read: src/auth/login.ts (foreground, instant)
├── Read: src/auth/session.ts (foreground, instant)
├── Edit: fix suspected bug in login.ts (foreground)
├── [Notification: npm test completed, 3 failures]
├── Analyze: compare failures with the fix just made
├── Edit: fix remaining 2 test failures
└── Launch: npm test (background, verify fixes)
The AI used the test suite’s execution time productively: it read the likely-broken files and started fixing the most obvious issue before the test results even came back.
Key Insight
Background tasks let you avoid idle waiting — the AI can do useful work while long operations run. This isn’t just an optimization; it fundamentally changes how the AI approaches complex tasks.
Without background execution, every long operation creates a dead zone in the conversation. The AI launches a build, waits 60 seconds doing nothing, then continues. Those 60 seconds could have been spent reading documentation, writing code, or planning next steps.
The insight goes deeper: background tasks change the AI’s planning strategy. When the AI knows it can run tests in the background, it’s more willing to launch tests early (to get fast feedback) rather than waiting until it thinks everything is perfect. This leads to a more iterative, feedback-driven workflow — closer to how experienced developers actually work.
Think of it like cooking. A good chef doesn’t stand in front of the oven watching the roast. They start the roast, then chop vegetables, prepare the sauce, and set the table. The oven notifies them when it’s done. Background tasks give the AI this same ability to interleave operations.
Hands-On Example
Running Tests While Writing Code
Here’s a realistic workflow that leverages background tasks:
User: "Fix the failing tests in the auth module"
AI Plan:
1. Run test suite in background to identify failures
2. While tests run, read the auth module source code
3. When test results arrive, cross-reference with source
4. Fix each failure
5. Re-run tests in background to verify
Execution:
Step 1: Launch tests in background
→ Bash(command="npm test -- --reporter json", run_in_background=true)
→ task ID and output file path returned immediately
Step 2: Read source files (while tests run)
→ Read("src/auth/middleware.ts")
→ Read("src/auth/routes.ts")
→ Read("src/auth/session.ts")
→ (AI now understands the auth module's structure)
Step 3: Test results arrive
→ Task notification: status failed
→ Read(<output file>): 3 tests failed
- login.test.ts: "Expected 200, got 401"
- session.test.ts: "Token expired error"
- users.test.ts: "Missing required field"
Step 4: Fix with full context
→ AI already read the source files, can immediately
correlate failures with code
→ Edit middleware.ts: fix token validation
→ Edit routes.ts: add missing field
Step 5: Verify in background
→ Bash(command="npm test", run_in_background=true)
→ Continue documenting the changes while tests run
Time Limits for Background Commands
Claude can pass a timeout (in milliseconds) with a background command:
{
"type": "tool_use",
"name": "Bash",
"input": {
"command": "npm run e2e-test",
"description": "Run end-to-end test suite",
"run_in_background": true,
"timeout": 300000
}
}
Whether that limit applies depends on where the session runs (Claude Code 2.1.288 and later):
- Local sessions you work in (terminal, desktop app, VS Code extension): background commands have no time limit. They run until they exit or you stop them, for example from
/tasks. - Unattended sessions (
-pruns, Agent SDK apps, CI jobs, cloud sessions): a background command gets 30 minutes by default, or thetimeoutClaude passes withrun_in_background, up to 2 hours. A-prun given a text prompt defaults to 10 minutes instead. - At the limit, Claude Code stops the command and tells Claude, which can start it again with a longer
timeoutif the work still needs it.
You don’t set timeout yourself; Claude chooses it per call. The BASH_DEFAULT_TIMEOUT_MS and BASH_MAX_TIMEOUT_MS environment variables can raise these limits but never shorten them. Background time limits arrived in Claude Code 2.1.285 and applied to every session until 2.1.288.
Anti-Patterns to Avoid
Bad: Running a quick command in background
→ Bash(command="cat README.md", run_in_background=true)
→ A task ID, an output file, and a later notification are
pure overhead for a <1s operation
Bad: Launching many background tasks that compete for resources
→ 5 parallel "npm test" runs will slow each other down
→ Better: one background test run + foreground analysis
Bad: Launching a background task then immediately waiting for it
→ Bash(command="npm test", run_in_background=true)
→ Bash(command="sleep 30") ← defeats the purpose!
→ Instead: do useful work, let the notification come naturally
Bad: Expecting a foreground subagent's background command to outlive it
→ the command stops when that subagent's run ends
→ Better: start long-lived work from the main conversation
Beyond Commands: Background Subagents and Sessions
Background execution in Claude Code has three layers:
| Layer | How it starts | Where you manage it |
|---|---|---|
| Background command | Claude sets run_in_background, you press Ctrl+B, or a foreground command reaches its timeout | /tasks in the session |
| Background subagent | The default for subagents Claude spawns from the main conversation (Claude Code 2.1.232 and later) | The agent panel and /tasks; its permission prompts appear in your session |
| Background session | /background (alias /bg), claude --bg "<prompt>", or /fork to send a copy while you keep working | claude agents (agent view, a research preview) |
A background session is a full Claude Code conversation that keeps running without a terminal attached. When you background the session you’re in, its running background commands, background subagents, and /loop tasks carry over and keep running; a running Monitor watch, which can’t move, is stopped instead. From your shell:
claude --bg "run the full test suite and fix any failures"
claude agents # agent view: every background session
claude attach <id> # open the session in this terminal
claude logs <id> # print its recent output
claude stop <id> # stop it; the conversation is kept
claude rm <id> # delete it, and its worktree when that is safe
claude --bg prints the short ID these commands take. A session started with claude --bg or from agent view moves into its own git worktree before it edits files, and claude rm keeps a worktree that still holds uncommitted changes or unpushed commits. Session 12 covers those worktree rules.
What Changed
| Foreground Only | With Background Tasks |
|---|---|
| AI idles during long operations | AI works productively while waiting |
| One operation at a time | Interleaved foreground and background work |
| Tests run only when “ready” | Tests run early for fast feedback |
| Sequential workflow | Overlapping execution phases |
| 90s test run = 90s of nothing | 90s test run = 90s of productive coding |
| Build-then-deploy waits twice | Build in background, prepare deploy config simultaneously |
| One terminal per long-running job | Background sessions you can attach to, inspect, and stop from the shell |
Next Session
Session 9 introduces Agent Teams & Communication — how a lead session coordinates independent Claude Code teammates, each with its own context window, through a shared task list and direct messages to tackle problems too large for a single agent.