Monorepo Tools: Nx, Turborepo, and Git-Aware Workspace Management

Manage monorepos with Git using Nx, Turborepo, and workspace-aware tooling. Learn affected builds, caching strategies, and versioning for multi-package repositories.

published: reading time: 20 min read author: Geek Workbench updated: November 23, 2026
Quick Summary

Nx and Turborepo select tasks from workspace changes and dependency graphs, then reuse cached results when declared inputs match. This guide uses versioned Nx and Turborepo examples, explains cache inputs, outputs, trust boundaries, and deterministic tasks, and includes a dependency-aware test-selection exercise.

Introduction

A monorepo keeps related apps and packages in one repository. This can make cross-package changes easier to review, but CI still needs a dependency graph and task configuration to select work safely.

The examples below target Nx 24.0.6 and Turborepo 2.11.12. Their docs and command behavior change over time, so pin the CLI in the workspace lockfile and check the Nx 24 release notes and Turborepo 2.11.12 release when upgrading. Both tools can select tasks based on changed files and workspace dependencies; the result depends on an accurate project graph and correct task inputs. Nx 24 makes task-based affected selection the default in new workspaces; upgraded workspaces can retain the legacy project-based setting until affected.legacy is removed.

This post covers task selection, cache configuration, a reproducible comparison method, and a small exercise for tracing test selection through a dependency graph.

When to Use / When Not to Use

Use monorepo tools when:

  • You have multiple packages that share dependencies
  • You need atomic commits across packages
  • Your CI pipeline is slow from building everything
  • You want unified tooling and standards
  • You need to track cross-package changes

Avoid monorepo tools when:

  • You have a single package or app
  • Your packages are truly independent
  • Your team can’t handle the tooling complexity
  • You need separate deployment pipelines per package

Core Concepts

Monorepo tools work by building a dependency graph and using Git to detect changes:

flowchart TD
    A[Git Push] --> B[Detect Changed Files]
    B --> C[Map Files to Packages]
    C --> D[Build Dependency Graph]
    D --> E[Compute Affected Set]
    E --> F{Cached?}
    F -->|Yes| G[Use Cache]
    F -->|No| H[Build Package]
    G --> I[Aggregate Results]
    H --> I
    I --> J[Deploy Affected]

Architecture and Flow Diagram

sequenceDiagram
    participant Dev as Developer
    participant Git as Git Repository
    participant Tool as Nx/Turborepo
    participant Graph as Dependency Graph
    participant Cache as Remote Cache
    participant CI as CI Pipeline

    Dev->>Git: Push changes
    Git->>Tool: Trigger pipeline
    Tool->>Git: git diff --name-only HEAD~1
    Git-->>Tool: Changed files
    Tool->>Graph: Map files to packages
    Graph->>Graph: Compute affected packages
    Graph-->>Tool: Affected set
    Tool->>Cache: Check cache for each package
    Cache-->>Tool: Cache hits/misses
    Tool->>CI: Build only cache misses
    CI-->>Tool: Build results
    Tool->>Cache: Store new results
    Tool-->>Dev: Pipeline complete

Step-by-Step Guide

1. Nx Setup

# Create Nx workspace
npx create-nx-workspace@24.0.6 my-monorepo

# Or add to existing repo
npx nx@24.0.6 init

Project configuration:

// nx.json
{
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "cache": true
    },
    "test": {
      "dependsOn": ["build"],
      "cache": true
    },
    "lint": {
      "cache": true
    }
  },
  "defaultBase": "main"
}

Affected builds:

# Select affected test tasks (base/head must be available locally)
nx affected -t test --base=origin/main --head=HEAD

# Select affected build tasks and required dependency tasks
nx affected -t build --base=origin/main --head=HEAD


# Run with parallelism
nx affected -t test --base=origin/main --head=HEAD --parallel=4

2. Turborepo Setup

# Initialize Turborepo
npx turbo@2.11.12 init

# Or add to existing workspace
npm install --save-dev turbo@2.11.12

Task configuration:

// turbo.json
{
  "$schema": "https://turborepo.com/schema.json",
  "tasks": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": ["dist/**"]
    },
    "test": {
      "dependsOn": ["build"],
      "outputs": [],
      "inputs": ["$TURBO_DEFAULT$", "test/**/*.ts"]
    },
    "lint": {
      "outputs": []
    },
    "dev": {
      "cache": false,
      "persistent": true
    }
  }
}

Cache correctness: deterministic inputs and outputs

Both tools can replay a result when a task’s cache key matches. Cache only tasks whose same declared inputs produce the same outputs. A hermetic task reads files and environment values it declares, writes to its declared output paths, and does not depend on hidden machine state. If the task reads an undeclared config file, a missing input can produce a stale cache hit. If it writes an undeclared artifact, a cache hit may not restore that file.

Task behavior Cache setup
Build reads source, lockfile, config, and a compiler version Include relevant files and toolchain values as inputs; declare generated files as outputs.
Unit test uses fixed fixtures and deterministic code Cache only if the result and reports are reproducible from declared inputs.
Test calls a live API or shared database Do not cache by default; external state can change without changing the key.
Deploy, publish, or migration task changes external state Mark non-cacheable and run under explicit release controls.

When an input changes, the task should rerun; changing outputs alone does not invalidate a cache key. Keep the input set complete, and avoid timestamps, random values, and untracked environment differences unless they are explicit inputs. Do not put credentials in cache keys, logs, or cached outputs. Nx’s input reference and output guide describe the fields; Turborepo’s cache guide documents its task hashes and output restoration.

Running tasks:

# Run build for all packages
npx turbo@2.11.12 run build

# Run only for changed packages
npx turbo@2.11.12 run build --affected

# Run with concurrency
npx turbo@2.11.12 run build --concurrency=4

# Dry run to see what would execute
npx turbo@2.11.12 run build --dry-run

3. Git Integration Patterns

Nx with Git:

# Compare against main branch
nx affected -t test --base=origin/main --head=HEAD

# Compare against last successful build
nx affected -t test --base=HEAD~1 --head=HEAD

# Custom range
nx affected -t test --base=v1.0.0 --head=v1.1.0

Turborepo with Git:

# Select affected build tasks relative to the CI base
npx turbo@2.11.12 run build --affected

# Filter specific package
npx turbo@2.11.12 run build --filter=my-package

# Select a package and its dependencies
npx turbo@2.11.12 run build --filter=my-package^...

Dependency-aware test-selection exercise

Assume a workspace declares these package dependencies:

apps/storefront -> packages/ui -> packages/date-utils
apps/admin      -> packages/ui

If a change only touches packages/date-utils, identify the test tasks for packages/date-utils, packages/ui, and apps/storefront. apps/admin is outside this dependency path, so its tests should not be selected for that change. If the change touches packages/ui, tests for both apps should be selected. Run the task-selection command and inspect the output before relying on it in CI:

# Nx 24: compare the feature branch to the fetched base.
npx nx@24.0.6 affected -t test --base=origin/main --head=HEAD

# Turborepo 2.11: select affected test tasks.
npx turbo@2.11.12 run test --affected

If the selected set differs from the graph, check declared workspace dependencies, project configuration, and the base commit available to CI. Then add a regression exercise for a shared package change so future graph edits do not silently narrow test selection.

4. Remote Caching Setup

Nx Cloud:

npx nx@24.0.6 connect
# Configure CI tokens in the CI secret store, not in nx.json.

Turborepo Remote Cache:

# Use Vercel Remote Cache
npx turbo@2.11.12 login
npx turbo@2.11.12 link

npx turbo@2.11.12 run build

For Nx Cloud, use a read-only token on untrusted pull requests and reserve read-write access for trusted protected branches. Keep tokens in CI secrets, never in nx.json. For Turborepo, configure the remote-cache provider’s CI credentials and permissions according to its security model. Cache entries can contain build artifacts and terminal output, so exclude secrets and sensitive data from both. See the official Nx cache security guide, Nx cache inputs guide, and Turborepo caching guide.

5. CI Configuration

# GitHub Actions with Nx
name: CI
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
jobs:
  ci:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v4
        with:
          node-version: 24
      - run: npm ci
      - run: npx nx affected -t lint test build --parallel=3
        env:
          NX_CLOUD_ACCESS_TOKEN: ${{ secrets.NX_CLOUD_ACCESS_TOKEN }}

Production Failure Scenarios

Scenario What can happen Response
A cache entry is suspect A task restores an artifact that does not match the expected build. Stop reading that entry, rebuild from trusted inputs, and inspect the cache provider’s integrity and access controls.
The dependency graph misses an edge An affected run omits a task that depends on a changed package. Check workspace declarations and tool configuration. Clearing a local daemon cache does not repair a missing dependency declaration.
The remote cache is unavailable CI may rebuild tasks or fail, depending on the tool and provider configuration. Decide whether uncached execution is allowed and document the expected behavior. Do not assume a local fallback without configuring and checking it.
The CI base commit is missing Changed-file or affected-task selection cannot compare the intended revisions. Fetch the required base and head commits, then verify the comparison range used by CI.

Compare the Tools in Your Workspace

Nx and Turborepo overlap in task selection and caching, but their configuration models and extra workspace features differ. Compare them on the same repository instead of relying on general speed or complexity rankings.

Check What to record for each tool
Workspace fit Supported package managers, languages, project graph inputs, and existing configuration.
Task selection Selected task list for the same base/head change, including a shared-library change.
Cache correctness Declared file and environment inputs, outputs restored, and behavior after changing a lockfile or config.
Access and trust Who can read or write remote entries from developer machines, trusted CI, and untrusted pull requests.
Operations Upgrade process, debugging tools, provider access, and the work required to maintain configuration.

Use a clean checkout, pin tool versions in the lockfile, and run a cold and warm-cache pass for the same task set. Compare the task plan and outputs first, then record elapsed time and resource use on the same runner. Keep the test workspace and commands with the result so a later upgrade can be compared fairly.

Implementation Snippets

Nx workspace with affected deployment:

# Deploy only affected apps
nx affected --target=deploy --base=main --parallel=1

Turborepo with package filtering:

# Build package and its dependencies
turbo run build --filter=my-package^...

# Build everything except specific package
turbo run build --filter=!my-package

If a repository needs custom selection, derive it from the same declared dependency graph as the build tool. A file-path grep can find changed packages, but it will miss downstream consumers unless it also traverses workspace dependencies. Keep the tool’s dry-run output as a CI artifact when investigating selection behavior.

Monitoring Task Selection and Cache Behavior

  • Logs: Log affected package computation and cache hit rates
  • Metrics: Track build time savings from affected builds
  • Alerts: Alert on cache misses and graph computation failures
  • Dashboards: Monitor monorepo health and build performance
  • Traces: Trace file changes through dependency graph to builds

Cache Security

Remote cache entries can contain build artifacts and terminal output. Treat the cache as a data store with separate read and write permissions:

  • Keep credentials out of task outputs, logs, and declared artifacts.
  • Give untrusted pull requests read-only access only when those entries are safe to expose; do not let untrusted jobs publish trusted cache entries.
  • Scope CI tokens to the repository and cache actions they need, and keep them in the CI secret store.
  • Check the selected provider’s transport, storage, retention, and integrity controls instead of assuming every remote cache signs or encrypts entries in the same way.
  • Make cacheable tasks deterministic and declare all files and environment variables that can affect their outputs.

Common Pitfalls / Anti-Patterns

Anti-Pattern Why It’s Bad Fix
Not configuring cache outputs Cache misses on every run Define outputs in turbo.json/nx.json
Ignoring dependency graph Wrong affected computation Validate graph regularly
Shallow clone in CI Can’t compute affected Use fetch-depth: 0
No cache retention policy Stored artifacts may exceed operational needs Set retention with the selected provider
Mixing package managers Inconsistent resolution Use workspaces consistently

Quick Recap Checklist

  • Choose Nx or Turborepo based on needs
  • Configure pipeline with proper inputs/outputs
  • Set up remote caching
  • Configure CI with affected builds
  • Validate dependency graph accuracy
  • Monitor cache hit rates
  • Document workspace structure
  • Set up cache eviction policies

Extended Architecture Diagram

flowchart TD
    subgraph "Git Repository"
        A[packages/ui] --> B[packages/api]
        A --> C[apps/web]
        B --> C
        B --> D[apps/admin]
    end

    subgraph "Change Detection"
        E[git diff --name-only] --> F{Changed Files}
        F --> G[Map to packages/ui]
        F --> H[Map to packages/api]
    end

    subgraph "Dependency Graph"
        G --> I[apps/web depends on ui]
        G --> J[apps/admin depends on api]
        H --> J
        H --> I
    end

    subgraph "Affected Set"
        I --> K[Build ui, api, web, admin]
        J --> K
    end

    subgraph "Cache Layer"
        K --> L{Cache Hit?}
        L -->|Yes| M[Download artifacts]
        L -->|No| N[Build and cache]
    end

Affected Selection Can Miss a Task

A shared package changes, but a CI task is not selected for one of its consumers. The cause may be a missing workspace dependency declaration, a project-graph plugin that does not model a generated or runtime dependency, or a base/head range that does not include the change. Nx and Turborepo build their graphs from their configured inputs; do not assume every tool can infer every dependency from arbitrary source files.

Inspect the graph and task plan for the pinned version, then check package-manager declarations, project configuration, generated-file inputs, and the Git revisions used by CI. nx reset can clear local Nx daemon or cache state, but it does not add a missing dependency edge. Turborepo cache bypass options likewise do not repair task-graph configuration. Add a shared-package change to the dependency-aware test-selection exercise above and compare the selected tasks with the expected dependents.

Observability Checklist

Track data that helps explain whether task selection and cache reuse are correct:

  • Record the changed-file range, affected projects, and selected tasks for CI runs.
  • Compare the selected set with a full run after changes to graph configuration or package declarations.
  • Track cache hits, misses, restores, and task duration by task; investigate changes instead of applying a universal target.
  • Record which input change invalidated an expensive task, especially lockfiles, tool versions, environment variables, or shared configuration.
  • Monitor remote-cache storage and retention through the provider’s supported controls.
  • Keep a small dependency-graph exercise in CI or review training so changes to workspace declarations are understood.

Cross-Roadmap References

Interview Questions

1. How do Nx and Turborepo determine which packages are affected?

They compare the current Git state against a base reference (usually main branch), identify changed files, map those files to packages, then traverse the dependency graph to find all packages that depend on changed ones. This ensures that if package A changes, package B (which depends on A) is also rebuilt.

2. What's the difference between Nx and Turborepo?

Nx provides project-graph, task, and workspace features with plugin support. Turborepo focuses on task orchestration and caching for JavaScript and TypeScript workspaces. Both can select work and reuse cache entries; compare configuration effort, graph accuracy, security controls, and required integrations in the same workspace.

3. Why is fetch-depth: 0 critical for monorepo CI?

Monorepo tools need Git history to compute affected packages. With shallow clones, they can't compare against the base branch and may either build everything or miss affected packages. fetch-depth: 0 ensures full history is available for accurate change detection.

4. How does remote caching work in monorepo tools?

Before building a package, the tool computes a hash from input files, dependencies, and environment. It checks the remote cache for this hash. If found, it downloads the cached artifacts instead of building. If not found, it builds and uploads the result to the cache for future use.

5. How do you handle versioning in a monorepo?

Use fixed versioning (all packages share one version) or independent versioning (each package versions separately). Tools like Changesets or Lerna manage independent versioning with changelog generation. For fixed versioning, semantic-release can version the entire workspace together.

6. What strategies exist for optimizing monorepo build performance at scale?

Key strategies include: sparse checkout (only fetch needed packages), module federation for shared dependencies, build caching at both local and remote levels, affected-based execution to skip unchanged packages, parallel execution with proper task orchestration, output caching to reuse build artifacts, and dependency minimization to reduce the graph size. For extreme scale, consider Bazel with its distributed caching and remote execution capabilities.

7. How do you debug a stale dependency graph in monorepo tools?

Inspect the project graph and dry-run task plan for the pinned tool version. Check workspace dependency declarations and project configuration, then compare the selected tasks with the expected dependents. Tools such as dependency-cruiser can help find source imports that cross package boundaries. Clearing a local cache may help rule out stale local state, but it does not fix an undeclared dependency edge.

8. What are the security implications of remote caching in monorepos?

Remote caches can expose sensitive artifacts or accept entries written by an untrusted job. Keep secrets out of outputs and logs, restrict write access to trusted jobs, scope provider tokens, and verify the provider’s documented transport, storage, and integrity controls. Cache only deterministic tasks with complete inputs.

9. How does Turborepo's Rust-based core differ from Nx's TypeScript implementation in practice?

Implementation language alone does not predict performance for a workspace. Pin both tools, run the same task graph on the same runner with cold and warm caches, and compare selected tasks, outputs, elapsed time, and resource use. Also compare the integrations and configuration your team needs.

10. Describe the trade-offs between local caching and remote caching for monorepo CI.

Local cache: Reuses results on the same machine and depends on local disk. Remote cache: Can share entries across machines, but needs network access, credentials, and access controls. Configure each tool and provider for the fallback behavior and retention policy you want; do not assume those defaults are identical.

11. How do monorepo tools handle circular dependencies between packages?

Use each tool’s graph or task-plan output to inspect the dependency model and check its current cycle behavior for the pinned version. Resolution: refactor to extract shared code into a new package both depend on, merge competing packages if they're tightly coupled, or use peer dependencies strategically. Prevention: enforce dependency rules via ESLint plugins (e.g., import/order), use dependency-cruiser in CI, establish package boundary conventions.

12. What strategies help reduce the blast radius of changes in a large monorepo?

Strategies include: enforce acyclic dependencies between packages, use plugin architecture to isolate core from extensions, implement package boundaries with strict import rules, adopt incremental migration rather than bulk refactoring, leverage affected builds to limit CI scope, design stable API boundaries between packages (avoid internal exposure), use feature flags for cross-cutting changes, and measure coupling metrics to detect growing dependencies.

13. How do you migrate an existing multi-package repository to use monorepo tooling?

Migration steps: 1) Document current package structure and dependencies, 2) Choose tooling (Nx vs Turborepo based on needs), 3) Set up workspace configuration with minimal changes, 4) Configure affected builds with wide base (build all initially), 5) Set up remote caching, 6) Add CI pipeline with affected detection, 7) Incrementally tighten the affected base from main to feature branches. Use the initialization or migration commands documented for the pinned tool version, then review the generated configuration.

14. How does monorepo caching interact with environment-specific builds?

If a task reads an environment variable that affects its output, declare it in the task configuration so the cache key accounts for it. Keep secrets out of that configuration and the task output. Check the pinned Nx or Turborepo documentation for the exact environment-input fields; do not assume dev, staging, and production results can safely share a cache entry.

15. What role does GitOps play in monorepo build orchestration?

Affected-task selection usually compares revisions in version control, then maps changed files onto configured projects and dependencies. Ensure CI fetches the base and head commits used for that comparison. GitOps can trigger the workflow, but it is separate from how Nx or Turborepo builds the project graph.

16. How do you handle monorepo tool configuration drift across teams?

Mitigation strategies: centralized configuration in root-level nx.json/turbo.json with strict linting, preset configurations distributed as packages (e.g., @company/eslint-config), CI validation that rejects non-conforming configs, codegen templates via Nx generators for consistent project setup, configuration as code checked into repo with PR review requirements, and automated updates via migration scripts when tool versions change.

17. What metrics should teams track to measure monorepo health?

Key metrics: affected package ratio (packages changed per total), cache hit rate (local and remote), build time per package (identify bottlenecks), dependency graph depth (longest chain), cross-package coupling (how often packages affect each other), PR size vs. affected scope correlation, time to first meaningful build, and cache storage growth rate. Dashboard these in CI and review trends weekly to catch architectural degradation early.

18. How do monorepo tools compare in handling monolithic versus modular application structures?

For modular architectures (well-defined packages with clear boundaries), both Nx and Turborepo excel at affected-based builds and caching. For monolithic apps (single large codebase split artificially), tools struggle because the dependency graph is shallow and almost everything is "affected" on each change. Recommendation: if monolith is too large, split into meaningful packages with explicit dependencies rather than artificially folder-structured packages. The tools work best when there's a genuine dependency graph to traverse.

19. What strategies exist for handling different package publish cadences in a monorepo?

Strategies: fixed versioning (all packages release together, simpler but less flexible), independent versioning (each package versions via Changesets/Lerna, more complex but targeted), release channels (canary/beta/stable per package), delayed publishing (staging area with batched releases), and aggregation releases (combine multiple package changes into single release). Choose based on coupling: highly coupled packages benefit from fixed versioning; independent packages suit independent versioning.

20. How does affected-based rebuilding interact with database migrations?

Database migrations are stateful operations that don't fit cleanly into file-based change detection. Strategies: mark migrations as always-affected for their package, use separate migration pipelines that run unconditionally when schema changes are detected, configure explicit dependencies between app packages and migration packages, and ensure migrations run before dependent apps via proper task ordering. Consider using tags like nx-ignore for non-code changes or implementing a migration flag system in your CI.

Further Reading

Conclusion

Nx and Turborepo combine version-control changes with a workspace dependency graph to select tasks. Correct selection depends on declared dependencies, complete task inputs, and a valid base/head comparison. Keep those details visible in CI and compare tool behavior against the needs of the repository.

Category

Related Posts

Git Submodules and Subtrees: Managing External Dependencies

Master git submodules and subtrees for including external repositories. Learn the trade-offs, synchronization workflows, dependency management patterns, and when to use each approach.

#git #version-control #submodules

Centralized vs Distributed VCS: Team Trade-offs

Compare centralized and distributed version control by offline work, repository size, access control, branching, review, and migration effort.

#git #version-control #svn

Automated Changelog Generation

Generate release notes from structured commits, choose a release policy, and add changelog generation to CI without treating every merge as a release.

#git #version-control #changelog