Claude Code worktrees: isolate ports, data and parallel changes
Claude Code worktrees allow multiple coding sessions to work on separate branches of the same Git repository without overwriting each other’s files. However, separate source directories do not automatically mean separate development environments. Two sessions can still fight over a localhost port, modify the same test database or run against the wrong backend.
This practical guide builds two worktrees running a small Python application, assigns each a different port and SQLite database, deliberately creates a port collision and demonstrates recovery. It also covers environment configuration, shared resources and the validation required before merging parallel changes.
Working configuration: two Claude Code sessions
| Resource | Worktree Alpha | Worktree Beta |
|---|---|---|
| Git branch | feature-alpha | feature-beta |
| Application port | 8101 | 8102 |
| Application URL | 127.0.0.1:8101 | 127.0.0.1:8102 |
| Database | runtime/test.sqlite3 | runtime/test.sqlite3 |
| Environment file | Own .env.local | Own .env.local |
| Expected behaviour | Writes stay in Alpha | Writes stay in Beta |
Notice that the database filenames are identical. They remain isolated because each resolves relative to its own worktree directory. An absolute path pointing to one shared database would remove that protection.
Verification: The Git worktree, Python server, SQLite isolation and port-collision sequence were exercised locally on Linux. Both applications ran independently, a port collision produced an address-in-use error, and recovery preserved the separate databases. Claude Code itself was not installed in the test environment, so its CLI behaviour is described using the current official documentation rather than claimed as an end-to-end Claude test.
What Git worktrees isolate and what remains shared
A worktree creates another checkout with its own working files, index and checked-out branch. Git history and the underlying repository remain shared. The operating system does not create a separate network, container or database merely because another directory exists.
| Component | Automatically isolated? | Practical requirement |
|---|---|---|
| Source files and uncommitted edits | Yes | Keep each session in its assigned worktree |
| Checked-out branch | Yes | Use a separate branch for each task |
| Git history and remote | No | Review shared repository operations |
| Localhost ports | No | Allocate a different port per application instance |
| Database contents | No | Use distinct paths, databases or schemas |
| Ignored environment files | Not copied by Git | Provision each checkout explicitly |
| Docker containers and volumes | No | Separate Compose projects and persistent resources |
| External APIs, queues and storage | No | Use dedicated test resources or mocks |
The recurring difficulty developers encounter with parallel coding agents is not usually creating worktrees. It is discovering that a browser test is talking to another branch’s API, or that a migration has changed data used by a second session. Source isolation is only the first layer.
Step 1: create a minimal application with persistent test data
This example requires Git and Python 3.10 or later. It uses Python’s standard HTTP server and SQLite modules, avoiding package installations so that runtime isolation can be examined without dependency-management complications.
Create a repository containing a file named server.py with the following code:
import json
import sqlite3
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
settings = {}
for line in Path('.env.local').read_text(encoding='utf-8').splitlines():
line = line.strip()
if line and not line.startswith('#'):
key, sep, value = line.partition('=')
if sep:
settings[key.strip()] = value.strip()
port = int(settings['APP_PORT'])
label = settings['TREE_LABEL']
database = Path(settings['DB_FILE']).resolve()
database.parent.mkdir(parents=True, exist_ok=True)
with sqlite3.connect(database) as connection:
connection.execute(
'CREATE TABLE IF NOT EXISTS events (label TEXT NOT NULL)'
)
class Handler(BaseHTTPRequestHandler):
def report(self):
with sqlite3.connect(database) as connection:
rows = connection.execute(
'SELECT COUNT(*) FROM events'
).fetchone()[0]
payload = json.dumps({
'tree': label,
'port': port,
'db': str(database),
'rows': rows
}).encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def do_GET(self):
if self.path != '/status':
return self.send_error(404)
self.report()
def do_POST(self):
if self.path != '/hit':
return self.send_error(404)
with sqlite3.connect(database) as connection:
connection.execute(
'INSERT INTO events VALUES (?)', (label,)
)
self.report()
print(f'{label}: http://127.0.0.1:{port}/status', flush=True)
ThreadingHTTPServer(
('127.0.0.1', port), Handler
).serve_forever()
The application exposes two endpoints. GET /status reports the running worktree, port, resolved database path and record count. POST /hit inserts one database record. These are sufficient to identify both a process collision and unintended shared data.
It deliberately binds to 127.0.0.1 and has no authentication. It is a local development fixture, not an application to expose publicly.
Track configuration templates, not runtime data
Create .env.example:
APP_PORT=8101
TREE_LABEL=alpha
DB_FILE=runtime/test.sqlite3
Add these rules to .gitignore:
/.claude/worktrees/
/.env.local
/runtime/
The tracked template documents the required variables. Each worktree gets its own ignored configuration and runtime database. Keeping the worktree directory ignored also prevents nested checkouts created by Claude Code from appearing as untracked content in the original checkout.
Commit the application, template and ignore rules before creating worktrees. New checkouts do not inherit uncommitted application files from your current working directory.
Step 2: create two worktrees from a known commit
Claude Code supports the --worktree flag, abbreviated to -w. Run these commands in separate terminals from your repository root:
claude --worktree feature-alpha
claude --worktree feature-beta
Claude Code normally creates the directories under .claude/worktrees/, using branches named worktree-feature-alpha and worktree-feature-beta. Its default branch starting point is discussed below.
For deterministic manual setup, including when Claude Code is unavailable, create the worktrees directly with Git instead:
git worktree add -b feature-alpha .claude/worktrees/feature-alpha
git worktree add -b feature-beta .claude/worktrees/feature-beta
git worktree list
The local application test used this second method. To run Claude Code in either manually created checkout, change into that directory and execute claude.
Anthropic’s official Claude Code worktree documentation describes native worktree creation, isolated subagents, configuration sharing and cleanup behaviour. The runtime configuration below is the additional engineering work needed for simultaneous applications.
Step 3: assign separate ports and database paths
Create an ignored .env.local in each new checkout. For Alpha, use:
APP_PORT=8101
TREE_LABEL=alpha
DB_FILE=runtime/test.sqlite3
For Beta, use:
APP_PORT=8102
TREE_LABEL=beta
DB_FILE=runtime/test.sqlite3
These files belong respectively in .claude/worktrees/feature-alpha/.env.local and .claude/worktrees/feature-beta/.env.local.
Open an additional terminal for each application. Start each server from its worktree root so relative configuration and database paths resolve correctly:
# Terminal A
cd .claude/worktrees/feature-alpha
python3 server.py
# Terminal B, starting again from the repository root
cd .claude/worktrees/feature-beta
python3 server.py
On Windows, use python if python3 is unavailable. The example environment files can be created using PowerShell’s Set-Content rather than a Unix shell.
Step 4: prove that a database write stays inside one worktree
With both processes running, query the two status endpoints:
curl -s http://127.0.0.1:8101/status
curl -s http://127.0.0.1:8102/status
Both should report zero records on freshly created databases, but their db values must point to different absolute files. Now insert a record into Alpha only:
curl -s -X POST http://127.0.0.1:8101/hit
curl -s http://127.0.0.1:8101/status
curl -s http://127.0.0.1:8102/status
In PowerShell, use curl.exe for the same curl syntax.
| Check | Observed result in the initial local run |
|---|---|
| Alpha status before write | rows: 0 |
| Beta status before write | rows: 0 |
| POST to Alpha | rows: 1 |
| Alpha after write | rows: 1 |
| Beta after Alpha write | rows: 0 |
This verifies something more meaningful than two successful server startups. Alpha changed its own database while Beta’s record count remained unchanged. A repeated run will have different absolute counts because SQLite persists the existing records, so compare the before-and-after values rather than expecting zero every time.
For automated checks, assert that the reported worktree labels match the requested ports, the resolved database paths differ, and a POST to one instance changes only its own record count. A passing health check without those identity checks can conceal a test hitting the wrong application.
Step 5: deliberately create a port collision and recover
A useful isolation test must fail predictably when its configuration is wrong. Keep Alpha running on port 8101. Stop the Beta server using Ctrl+C, then change Beta’s environment file to:
APP_PORT=8101
TREE_LABEL=beta
DB_FILE=runtime/test.sqlite3
Restart Beta. Both applications are now attempting to bind to the same address and port. In the Linux test, the second process exited with code 1 and the error OSError: [Errno 98] Address already in use. The exact error text differs across operating systems.
Recovery procedure
- Confirm which application already owns the requested port. Do not terminate it merely because the second Agent wants to start.
- Restore Beta’s
APP_PORTto8102. - Leave Beta’s database configuration unchanged.
- Restart Beta from its worktree root.
- Query both status endpoints and confirm their labels, database paths and existing record counts.
In the local recovery exercise, Alpha continued running, Beta restarted successfully on port 8102, and their database record counts remained separate. The test was repeated with additional records in Alpha to confirm that the recovery did not reset its data.
This failure is comparatively easy to detect because the Python server refuses to start. Some development servers automatically select another available port. That can be more dangerous: the Agent reports a working application while browser tests silently target an unexpected address. For multi-worktree testing, configure servers to fail on port conflicts instead of choosing fallback ports.
The hidden configuration trap: copied environment files can recreate collisions
Claude Code can copy selected ignored files into newly created worktrees using a repository-level .worktreeinclude file. This is useful for local configuration, but copying an environment file unchanged does not make its contents safe for parallel execution.
Suppose the original checkout contains these values:
APP_PORT=3000
DATABASE_URL=postgresql://localhost/application_test
REDIS_URL=redis://localhost:6379/0
If both worktrees inherit those values, they can compete for port 3000, mutate the same PostgreSQL database and consume jobs from the same Redis queue. The files are physically separate, but the resources they identify are not.
Use .worktreeinclude only for files whose contents are appropriate to copy. Generate worktree-specific port numbers, database names and service identifiers afterwards. Manual git worktree add does not perform Claude Code’s additional ignored-file copying, so provision those files yourself when using Git directly.
Prevent Claude from silently changing its assigned environment
Add a short runtime section to the project’s CLAUDE.md:
## Worktree runtime rules
- Read .env.local before starting development services.
- Never change APP_PORT or DB_FILE silently.
- Do not connect tests to production or staging databases.
- Do not reuse another worktree's running API or worker.
- Report the active port and resolved database path.
- Run validation and inspect the diff before committing.
These are operating instructions, not a security boundary. For stronger enforcement, use startup scripts that validate resource ownership and refuse conflicting configuration. Claude Code permissions and hooks can restrict some actions, but they should not be assumed to provide complete operating-system isolation.
A second trap: the new worktree may start from the wrong commit
Claude Code’s native worktree creation uses worktree.baseRef to determine the starting point. The default value, fresh, normally starts from the repository’s remote default branch. This can surprise developers who have made useful local commits that haven’t been pushed yet.
If a parallel session must inherit the current local committed state, configure the setting in Claude Code’s settings:
{
"worktree": {
"baseRef": "head"
}
}
The head option starts from the current local HEAD. It does not copy uncommitted file changes. Also, because this configuration changes the starting point for future worktrees, it should not be enabled universally without considering the team’s branching workflow.
Before assigning parallel tasks, compare the starting commit using git rev-parse HEAD inside each checkout. If the second Agent is missing a recent schema change, dependency update or shared interface, fix its base before development begins. Otherwise, both agents may produce individually valid changes against incompatible assumptions.
Scaling beyond two worktrees requires a resource allocation policy
For two small applications, assigning ports manually is manageable. For five agents running frontend, API, database and background worker processes, it becomes error-prone. The better approach is to allocate a numbered resource slot per worktree.
| Slot | Frontend | API | Database name | Compose project |
|---|---|---|---|---|
| 1 | 5101 | 8101 | app_test_1 | app_wt_1 |
| 2 | 5102 | 8102 | app_test_2 | app_wt_2 |
| 3 | 5103 | 8103 | app_test_3 | app_wt_3 |
These are example allocations, not automatically assigned Claude Code settings. A repository script can calculate them from a worktree identifier and generate local configuration before starting services. The script must still check port availability because a numbering convention does not reserve a port.
Docker Compose users should assign distinct project names and check named volumes, host-port mappings and external service connections. Setting COMPOSE_PROJECT_NAME alone will not isolate two applications if both still connect to the same external database or bind a fixed host port.
External side effects deserve tighter controls. Use separate test queues, storage prefixes, email sandboxes, and webhook destinations where possible. Do not allow a parallel testing Agent to exercise production payment, notification or deletion workflows simply because its source directory is isolated.
See more of our reporting in Google Top Stories, AI Overviews and AI Mode.
Validate parallel changes before merging into main
Passing tests in two separate worktrees does not prove that the combined application will pass. Each branch may introduce an independently reasonable change to an API, configuration file or schema that becomes incompatible after merging.
Use the following validation sequence after Claude finishes each task.
- Check the runtime identity. Confirm the active worktree, port, database and services used for testing.
- Run branch-local checks. Execute the relevant unit tests, linting, type checks and integration tests in that checkout.
- Inspect the actual diff. Look for unexpected environment edits, migrations, deleted tests and changes outside the assigned task.
- Commit each branch separately. Preserve a reviewable boundary between the two agents’ work.
- Merge into an integration checkout. Resolve conflicts deliberately rather than allowing an Agent to discard another branch’s changes.
- Test the combined result. Rerun integration and browser tests against processes started from the merged code.
For the example Python application, the basic checks inside each worktree are:
python3 -m py_compile server.py
git diff --check
git status --short
git diff --stat
Then run the endpoint checks against the correct application and database. After reviewing and committing the changes, merge them using your normal pull-request workflow or, for a local example, merge the branches sequentially:
git switch main
git merge --no-ff feature-alpha
git merge --no-ff feature-beta
python3 -m py_compile server.py
These merge commands assume the manually created branches from Step 2. Native Claude Code worktrees have different default branch names. Stop development services before retiring their worktrees, and run the full application tests on the combined tree with a fresh integration database where appropriate.
If a migration changes a shared schema, test a clean database setup as well as migration from the previous schema. Two successful isolated migrations do not establish that their combined order is valid.
Clean up safely without losing unfinished Agent work
Worktrees can accumulate ignored build artefacts, databases, background processes and uncommitted edits. Deleting a directory before inspecting its state may lose valuable work while leaving services or external resources running.
Before removal, inspect:
git worktree list
git -C .claude/worktrees/feature-alpha status --short
git -C .claude/worktrees/feature-beta status --short
Stop processes, preserve any required test data, confirm the branches have been merged, and then remove the worktrees. For the manual setup:
git worktree remove .claude/worktrees/feature-alpha
git worktree remove .claude/worktrees/feature-beta
Claude Code’s own named worktree sessions use an exit and retention workflow that may offer to keep the worktree. Worktrees can also be locked while background sessions are running. Do not default to forced removal when Git refuses to delete a checkout. Determine whether an active session, uncommitted edit or retained resource is responsible first.
When parallel Claude Code sessions are worth the overhead
Worktrees are most useful when tasks have independent acceptance criteria and limited overlap: one Agent can implement a contained feature while another fixes a separate test failure. They are less useful when both tasks repeatedly edit the same schema, shared interface or configuration file. In that case, serialising the dependency-heavy work often saves more time than adding agents.
Parallel sessions also consume additional Claude usage capacity. Measure the number of accepted changes and review cycles rather than assuming two agents produce twice the useful work. Our Claude Code pricing guide explains how heavier usage affects subscription allowances and API billing.
If your main difficulty is choosing between terminal-led autonomous changes and closer editor supervision, the Claude Code vs Cursor comparison covers that workflow decision separately.
Recommended operating rule: every parallel worktree should have a known starting commit, named resource allocation, isolated test data, recorded test results and a clear cleanup owner. Merge only after the combined application has been checked. Without those controls, separate Git directories can make simultaneous development look safer than it actually is.


