Skip to content
How to share build cache across git worktrees, tool by tool

How to share build cache across git worktrees, tool by tool

To share build cache across git worktrees, point each one at a single store per tool, as Bun and Turborepo do, and keep build output like node_modules per worktree.

Aaron Delasy
Aaron DelasyFounder

To share build cache across git worktrees, point each worktree at one store per tool, as Bun and Turborepo do, and keep build output like node_modules in each worktree. Both of those share with no setup, and both still went wrong for me. A fresh worktree with a warm Bun cache spent 14.3 seconds writing 2.4 GB of node_modules, and Turborepo handed a second worktree build output that named the first one's folder.

I give each agent its own worktree when I'm running several Claude Code agents, so a cold start is a cost I pay once per agent. On November 25, 2026 I tested the tools my per-worktree dev container ships with: git 2.39.5, Bun 1.4.6, Turborepo 2.11.10 and Terraform 1.15.8. I didn't test npm, pnpm, Go, Cargo, Gradle, ccache, sccache, Nx, Next.js or Docker, so for those I quote their own docs, and the Angular part comes from a GitHub issue.

Shared stores live outside the checkout, build output lives inside

Bun, npm, pnpm and Go keep their caches in the home directory by default, so every worktree of every repo on the machine already shares them. Go's docs call its build cache "safe for concurrent invocations of the go command", and npm's cache is "fully verified for integrity on both insertion and extraction". Bun's install cache and pnpm's store hardlink packages into each project from one copy on Linux, and pnpm's docs add that "hard links are only possible on the same filesystem".

The other kind is output a build writes in place: node_modules, Cargo's target, Next.js's .next/cache, a dist folder. Each one sits inside the checkout, so a new worktree starts without it, and removing the worktree deletes it with the folder (a plain git worktree remove deleted node_modules/ in my cleanup tests). Two agents building into one of these at once is a race I don't want to debug, so I copy them between worktrees and never share them.

Diagram of the two kinds of build cache: shared stores outside the checkouts (Bun install cache, npm cache, pnpm store, Go build cache, Gradle caches, Playwright browsers, Terraform providers and Turborepo's cache in the main worktree) above three worktrees that each keep their own node_modules, target, .next/cache and dist folders
CacheDefault locationShared by worktrees by defaultSettingCatch
Bun install cache~/.bun/install/cacheYesBUN_INSTALL_CACHE_DIRCopies instead of linking across mounts (tested)
npm cache~/.npmYescacheNone in its docs
pnpm store~/.local/share/pnpm/store on LinuxYes, one store per diskstoreDirCopies when the store is on another disk
Go build cachego-build in the user cache directoryYesGOCACHENone in its docs
Gradle dependency cacheGRADLE_USER_HOME/cachesYesGRADLE_USER_HOMEIts locks need processes that can talk to each other
Gradle build cacheThe Gradle user homeOff until enabledorg.gradle.caching=trueInputs are keyed by absolute path by default
TurborepoThe main worktree's .turbo/cacheYes, tested on 2.11.10cacheDir turns sharing offRestores outputs unchanged, paths included (tested)
Nx~/.nx/<id>/cacheYes, per its docscacheDirectoryNot tested here
Playwright browsers~/.cache/ms-playwright on LinuxYesPLAYWRIGHT_BROWSERS_PATHRemoves browser versions nothing uses any more
Terraform providersNot cachedNoTF_PLUGIN_CACHE_DIR"Not guaranteed to be concurrency safe"
Cargo build outputtarget at the workspace rootNoCARGO_TARGET_DIR, build.build-dirShares nothing across paths without sccache

Bun copies from its cache when the cache sits on another mount

Bun 1.4.6 hardlinks packages from its cache into node_modules on Linux, and a hardlink can't cross a mount point, so a cache on a Docker volume gets copied instead. My setup gives every worktree its own dev container, capped at 8 CPUs and 16 GB because a few parallel agents can run a machine out of memory. Each container bind-mounts the main worktree at its real path, with the linked worktrees inside it, and shares three named Docker volumes with the others, for Bun's install cache, Playwright's browsers and Terraform's providers.

Diagram of my dev container setup: one ext4 disk holds a bind mount with the main checkout and its worktrees, each with its own node_modules, and three named volumes every container shares (Bun install cache 2.7 GB, Playwright browsers 681 MB, Terraform providers 3.4 GB); three dev containers at 8 CPUs and 16 GB each

That looked like one install cache shared by every worktree. To check, I timed a fresh install of this repo's lockfile in an empty directory with the cache warm. Bun installed 1,351 packages in 14.3 seconds and wrote 2.4 GB in 126,318 files. The file I sampled had a link count of 1, and a link count of 1 means a copy.

Bun's docs say it hardlinks on Linux and falls back to copying files when it can't. It couldn't here. /bun-cache and the bind mount sit on the same ext4 disk, but they're separate mounts, and a plain ln from one into the other fails with Invalid cross-device link. The install still reported success, and only stat showed the copies.

Bun 1.4.6 install results on one ext4 disk: with the cache on a different mount, ln fails with Invalid cross-device link and this repo's install copies 1,351 packages, 2.4 GB in 126,318 files, in 14.3 seconds; with the cache inside the same bind mount, a 3-package install takes 21 ms and a sampled file has a link count of 2

A throwaway repo with three packages (TypeScript, Prettier and Zod) made the difference plain. With the cache inside the same mount as the checkout, a warm install took 21 ms and typescript.js had a link count of 2, one for the cache and one for the worktree. With the cache on a different mount it took 145 ms and wrote a fresh 37 MB copy.

Moving the cache into a folder inside the bind mount gave me the hardlinks back. Bun's global store works too: with BUN_INSTALL_GLOBAL_STORE=1 and the isolated linker, the entries in node_modules/.bun become symlinks into the cache's links/ folder, and a symlink can cross mounts. My test's node_modules dropped to 16 KB and a reinstall took 13 ms. Its docs go as far as saying "every additional checkout, branch worktree, or CI workspace after that is free". But those symlinks point at /bun-cache, a path that only exists inside the container, so every tool on the host sees a broken node_modules. I'd move the cache.

Terraform gets this right in the same container. With TF_PLUGIN_CACHE_DIR set, the providers in this worktree's .terraform/providers are symlinks into /tf-plugin-cache, so each provider binary exists once on disk. The CLI config docs warn that the plugin cache "is not guaranteed to be concurrency safe", so I keep terraform init to one worktree at a time.

Turborepo shares its cache between worktrees by default

Turborepo 2.11.10 points a linked worktree at the main worktree's .turbo/cache with no configuration, and my second worktree's build was an 18 ms cache hit. I built a one-package repo in its main worktree, which missed and filled the cache, then ran the same build in a worktree made with git worktree add. Turborepo printed Remote caching disabled, using shared worktree cache and cache hit, replaying logs, and no .turbo/cache appeared in the new worktree.

The caching docs say the same thing: Turborepo "automatically shares the local filesystem cache between the main worktree and any linked worktrees". Setting "cacheDir": ".turbo/cache" in turbo.json turned that off, and both worktrees missed with a cache each, because an explicit relative value "resolves from the root of the current worktree and disables sharing" (configuration reference).

Turborepo 2.11.10 test output: the main worktree's build misses and fills the cache; the linked worktree prints using shared worktree cache and replays the hit in 18 ms, but its restored dist/built-in.txt names the main worktree's folder; with cacheDir set to .turbo/cache both worktrees miss

Restored outputs come back byte for byte. The reference says cache artifacts "are restored without rewriting their contents", and my test build wrote its own working directory into dist/built-in.txt. In the feature worktree, that restored file named the main worktree's folder. A build that writes an absolute path into its output hands that path to every worktree. I'd fix those outputs rather than turn sharing off, because the shared hit is the whole point.

The shared cache also grows for every worktree at once. This repo's main worktree holds 25 GB in 48,618 files under .turbo/cache, and TURBO_CACHE_MAX_AGE and TURBO_CACHE_MAX_SIZE in the same reference set how it's evicted.

Nx shares through the home directory instead, since its cacheDirectory "defaults to ~/.nx/<id>/cache, shared by every checkout of the workspace". Angular's build cache didn't share until this year. Angular CLI issue #33321, opened on June 7, 2026, reported four worktrees holding about 140 GB of duplicated cache, and it closed on July 7 with a change titled "share persistent build cache across git worktrees".

Cargo and Gradle need a setting before worktrees share anything

Cargo writes build output to a target directory at the workspace root, so each git worktree compiles every dependency again unless sccache sits in front of rustc. Cargo's build cache docs name sccache as the tool that "can be used to share built dependencies across different workspaces", set up with RUSTC_WRAPPER=sccache. You can also point several worktrees at one CARGO_TARGET_DIR. The docs don't say what happens when two builds write to it at once, and I couldn't test it, since my container has no Cargo.

A Rust forum thread from November 18, 2026 tried both. On a project with about 550 dependencies, sccache with base directories set gave the second worktree 723 hits and 81 misses. The poster's shared CARGO_BUILD_BUILD_DIR attempt, in their words, "clearly shows I'm doing the build dir sharing wrong". And sccache never covers every crate. Its Rust notes say "crates that invoke the system linker cannot be cached", which covers bin, dylib, cdylib and proc-macro crates, and incremental crates aren't cached by default.

Chart of Cargo and sccache across worktrees: without sccache each worktree's target folder builds everything again; with RUSTC_WRAPPER=sccache a Rust forum user's second worktree of about 550 dependencies got 723 cache hits and 81 misses, and linker crates and incremental crates are not cached

Cargo's build.build-dir setting takes templates such as {workspace-path-hash}, a hash of the manifest path, so one parent folder can hold every worktree's build. That moves the build out of the checkout but shares nothing, because each worktree's path hashes differently.

Gradle splits its cache in two. Its dependency cache lives in GRADLE_USER_HOME/caches, so every worktree already shares it, and file-based locking lets several Gradle processes use it at once. The same page says that only works when "the different Gradle processes can communicate together", which is "usually not the case for containerized builds". Mounting one Gradle home into a container per worktree, the way I share Bun's cache, is the setup that page warns about. The build cache, which stores task outputs, is off until you pass --build-cache or set org.gradle.caching=true in gradle.properties, and it lives in the Gradle user home as well.

Absolute paths decide whether a shared cache hits

By default, ccache hashes the current working directory into the key of every debug compile, so a second git worktree misses what the first one cached. Its manual's fix for debug builds is -fdebug-prefix-map=$PWD=., which takes the directory out of the debug info and out of the hash with it. For compile commands that carry absolute paths, it says to "set base_dir to a common parent directory", and ccache then rewrites those paths as relative ones before the compiler sees them. The manual also calls that "kind of a brittle hack", because the dependency files it writes lose their absolute paths, which can break dependency detection in Make and Ninja. I'd make the build use relative paths first, as the manual also suggests.

sccache has the same knob. SCCACHE_BASEDIRS "enables cache hits across different absolute paths", and its configuration docs list Git worktrees as a use for it. The Rust notes warn about the reverse case. With base directories set, a crate that reads env!("CARGO_MANIFEST_DIR") can get a hit compiled in another checkout, with that checkout's path inside it. For Rust's own output there's also rustc's --remap-path-prefix, which rewrites a path prefix "in all output, including compiler diagnostics, debug information, macro expansions".

Diagram of a ccache key in two worktrees: with the defaults the working directory goes into the hash, so the main worktree and a linked worktree get different keys and miss; with base_dir on a common parent and -fdebug-prefix-map=$PWD=. both compute the same key and hit

Gradle's build cache has the same problem, since task "input files are identified by default by their absolute path". A custom task's inputs need @PathSensitive(PathSensitivity.RELATIVE) to hit from another directory, and the build cache guide suggests "adding tests to ensure that the task inputs are relocatable".

Build time alone doesn't prove a hit, so check each tool's own counters: ccache -s, sccache --show-stats and the cache hit line Turborepo prints for each task.

Docker layers are shared by every worktree on one machine

Every worktree on one machine builds against the same Docker layer cache, because Docker's default builder "uses the BuildKit library bundled with the daemon" and keeps its cache there. BuildKit "automatically caches the build result in its own internal cache" (cache backends), and none of the inputs in the invalidation rules is the build context's path. COPY and ADD use a "cache checksum from file metadata" that ignores the modification time, and RUN uses the command string. So the same Dockerfile and files built from two worktrees reuse the same layers.

Diagram from Docker's docs: docker build in the main worktree and in feature-a both go to the default builder, whose BuildKit cache sits outside both checkouts; COPY and ADD hit on a checksum from file metadata without mtime, RUN on the command string, and the checkout's path is not one of the inputs; --cache-to and --cache-from are for CI runners that keep nothing between runs

--cache-to and --cache-from are for machines that don't keep that cache. The backends page calls an external cache "almost essential in CI/CD build environments", which "usually have little-to-no persistence between runs". On a single machine I'd leave them out.

I haven't tested this part, because my dev container has no Docker inside it. A per-worktree container reaches this cache only through the host's daemon, such as a mounted docker.sock, and sandboxing coding agents covers what that socket hands an agent.

A post-checkout hook for new worktrees

Git runs the post-checkout hook after git worktree add with a null previous HEAD (githooks), so the hook can tell a new worktree from a branch switch. Hooks live in the repository's shared .git/hooks, so one file covers every worktree, and on git 2.39.5 it ran inside the new one. Mine copies apps/web/.next/cache from the main worktree, then runs bun install, which links packages from Bun's install cache:

sh
#!/bin/sh
# .git/hooks/post-checkout: git worktree add runs it inside the new worktree
[ "$1" = 0000000000000000000000000000000000000000 ] || exit 0

main=$(git worktree list --porcelain | sed -n '1s/^worktree //p')
[ "$main" = "$(pwd -P)" ] && exit 0

for dir in apps/web/.next/cache; do
  [ -d "$main/$dir" ] || continue
  mkdir -p "$(dirname "$dir")"
  case "$(uname)" in
    Darwin) cp -Rc "$main/$dir" "$dir" ;;
    *) cp -R --reflink=auto "$main/$dir" "$dir" ;;
  esac
done

bun install --frozen-lockfile

In a throwaway repo it copied a 2 MB .next/cache and finished bun install in 10 ms with the packages hardlinked from the cache, and a later git checkout -b in the same worktree left everything alone. cp --reflink=auto clones the files where the filesystem supports it and will "fall back to the standard copy behavior" where it doesn't (GNU cp), which on my ext4 disk meant a full copy. On macOS, cp -c clones with clonefile(2) and falls back to a plain copy too. GNU cp 9.1, the one in my container, rejects -c with invalid option -- 'c', which is why the hook checks uname.

Diagram of the post-checkout hook: git worktree add runs it in the new folder with a null previous HEAD, it copies apps/web/.next/cache from the main worktree with cp --reflink=auto, then bun install --frozen-lockfile hardlinks 3 packages in 10 ms; a later git checkout -b in that worktree exits without copying

I copy .next/cache and never symlink it. Next.js keeps it "shared between builds" of one project (CI build caching), and a symlink would turn that into one cache written by two agents building different branches at the same moment.

The rest is set once for the machine, in a shell profile or a config file: TF_PLUGIN_CACHE_DIR pointing at a folder that already exists, since "Terraform will not create the directory itself"; RUSTC_WRAPPER=sccache with SCCACHE_BASEDIRS; and org.gradle.caching=true in gradle.properties.

How build caches work in Aldena's sandboxes

Aldena gives each conversation its own sandbox, and the checkout, the build output and anything the setup script installs live in that sandbox. Aldena is my product, so read this section as the pitch it is. A conversation, meaning the chat you start plus every chat its agents hand work to, clones the repository into its own sandbox, so the hook and the Bun install cache volume above don't carry over.

The warm-up moves into the project's setup script in Settings → Server, which runs once on each new sandbox, in /project, with sudo and the project's environment variables. bun install --frozen-lockfile and npx playwright install go there. The sandbox sleeps 30 minutes after its last command and keeps its files until the conversation sits quiet for 7 days, so a conversation picked up the next day finds its node_modules and build output where it left them.

For build output that should outlive one conversation, a remote cache fits better than any local folder. Turborepo's Remote Cache reads TURBO_TOKEN, "the Bearer token to access the Remote Cache", and TURBO_TEAM from the environment (CI guide). I haven't run that pairing in a sandbox yet. Environment variables in Aldena are set per project, and only that project's agents can use them, so the Turborepo token reaches no other project.

Ready when you are

Spin up your first project.

One project per client, product, or piece of work, staffed with intake, requirements, build and code review agents.