Monorepo Tooling: Nx, Turborepo and Bazel for Large Codebases

Last spring I watched a team of 60 engineers lose nearly three hours of CI capacity every single day because their monorepo ran every test for every pull request. The repository itself wasn't the problem — it was the absence of tooling that could reason about what had actually changed. They had consolidated ten polyrepos into one to share UI components and backend contracts, but without a computation model, trunk-based development devolved into a queue of red builds and frustrated rebases. If you are consolidating code at scale, the choice between Nx, Turborepo, and Bazel is not about developer preference; it is about how you want to model dependencies, distribute cache, and enforce correctness over the next three years. In my experience, picking the wrong abstraction early costs far more than migrating later.

Why a Monorepo Collapses Without a Computation-Aware Task Graph

A monorepo is often sold as a version control strategy, but the version control part is the easy half. Git handles a single tree with thousands of packages reasonably well, especially when you pair it with a disciplined approach to branching such as Git Branching Strategies: Trunk-Based, GitFlow and Ship/Show/Ask. Where teams get into trouble is execution: how do you know which of your 200 packages need to be built, tested, or linted after a one-line change in a shared utility?

The naive answer is to run everything. At 50 packages that works. At 150 packages with end-to-end tests and Docker builds, it bankrupts your CI minutes and destroys developer feedback loops. I've found that the psychological threshold is about 90 seconds. If a developer cannot get local feedback in under 90 seconds after saving a file, they stop running tests locally and offload verification to CI, which then becomes slower for everyone.

This is the core problem the three tools solve differently. All three build a directed acyclic graph (DAG) of your workspace, but they derive that graph from different sources of truth. Nx infers it from imports and explicit project metadata. Turborepo declares it via pipeline configuration. Bazel requires you to declare it exhaustively in build files. The fidelity of that graph determines whether you can safely skip work.

From File Watching to Project Graph Reasoning

Legacy tooling like Lerna or Yarn workspaces plus ad-hoc npm scripts treats the monorepo as a flat collection of folders. Each package has its own build command, but there is no global understanding of the relationship between them. You end up writing shell scripts that try to topologically sort packages with lerna run build --since, which is fragile and slow because it still shells out and parses file changes at runtime without caching.

Modern tooling inverts this. The graph is computed once, cached, and then queried. In my current codebase of roughly 180 packages, our Nx project graph calculation takes ~1.2 seconds cold and ~120ms warm with daemon enabled. That upfront cost pays for itself because every subsequent command — nx affected --target=test, nx graph, dependency linting — reuses the same structure. Turborepo and Bazel make the same trade, but with different assumptions about how explicit you must be.

Nx's Project Graph and Affected Analysis: Trading Precision for Velocity

Nx is the most opinionated about developer experience. It tries to infer as much as possible automatically so teams can adopt incrementally without rewriting build definitions. That pragmatism is why I often recommend it to product teams migrating from an existing polyrepo or a loosely-organized monorepo.

At its core, Nx builds a graph by scanning source files for imports, examining package.json dependencies, and merging in explicit dependencies declared in project.json or package.json#nx. You can visualize it at any time with nx graph, and more importantly, you can query it. The nx affected mechanism diffs the current branch against main (using git merge-base under the hood) and then walks the graph to find all projects affected by the changed files.

// project.json for a shared UI library
{
  "name": "ui-components",
  "sourceRoot": "libs/ui-components/src",
  "projectType": "library",
  "targets": {
    "build": {
      "executor": "@nx/vite:build",
      "outputs": ["{options.outputPath}"],
      "options": { "outputPath": "dist/libs/ui-components" }
    },
    "test": {
      "executor": "@nx/vitest:vitest",
      "inputs": ["default", "^production"]
    },
    "lint": {
      "executor": "@nx/eslint:lint",
      "inputs": ["default", "{workspaceRoot}/.eslintrc.json"]
    }
  }
}

Notice the inputs and outputs fields. This is where Nx has evolved closest to Bazel. You are telling the hasher what constitutes an input for a target. By default, Nx uses default (all source files plus relevant config) and ^production (the production inputs of dependencies). When configured correctly, Nx's computation cache can be distributed via Nx Cloud or a self-hosted remote cache, and I've seen cache hit rates above 78% on main branch CI for frontend-heavy repos.

Where Nx's Inference Helps and Hurts

The inference layer saves weeks of configuration, but it can hide issues. Dynamic imports, path aliases that bypass TypeScript configuration, and runtime plugin loading will not be detected automatically. I once spent two days debugging why a change to a feature flag service didn't trigger affected tests — the consumer used a string-based injector key that the graph couldn't parse. We fixed it by adding an explicit implicitDependencies entry, but it reinforced that you still need to audit the graph via nx show projects --affected --target=test before trusting it blindly.

Nx also provides powerful code generation and workspace linting. The enforce-module-boundaries ESLint rule lets you forbid circular dependencies or enforce that feature-* apps cannot import from each other, only from libs/shared/*. For large organizations, this architectural guardrail is often more valuable than raw build speed. Combined with Git Hooks for Automation: Pre-commit, Pre-push and CI Integration, you can prevent boundary violations before they reach code review.

Turborepo's Convention-Based Pipeline and Remote Caching Economics

If Nx is an integrated platform, Turborepo is a focused accelerator. Built by Vercel, it deliberately does less: it orchestrates tasks, caches outputs, and parallelizes execution, but it leaves code generation, scaffolding, and linting boundaries to other tools. In my experience, this minimalism is exactly why frontend-heavy teams adopt it so quickly — you can be up and running in an afternoon without committing to the Nx plugin ecosystem.

Turborepo's model centers on turbo.json. You declare a pipeline where each task defines its dependencies (dependsOn), inputs, outputs, and cache behavior. Turborepo then constructs a task graph that is the cross product of your workspace packages and pipeline tasks, sorted topologically.

{
  "$schema": "https://turbo.build/schema.json",
  "globalDependencies": ["**/.env.*local"],
  "pipeline": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": ["dist/**", ".next/**", "!.next/cache/**"],
      "inputs": ["src/**", "package.json", "tsconfig.json"]
    },
    "test": {
      "dependsOn": ["build"],
      "outputs": ["coverage/**"],
      "inputs": ["src/**", "__tests__/**"]
    },
    "lint": {
      "outputs": []
    },
    "dev": {
      "cache": false,
      "persistent": true
    }
  }
}

The ^build syntax is crucial. It means "run the build task of all dependencies before this package's build." Unlike Bazel, Turborepo does not require you to declare inter-package dependencies in the pipeline itself; it reads them from your package manager workspaces (npm, pnpm, Yarn). This keeps duplication low but means the accuracy of your graph is only as good as your package.json dependency declarations. I've found pnpm workspaces to be the most reliable here because pnpm's strictness forces you to be explicit.

Remote Caching as a Cost Center

Turborepo's remote caching is where the economics become visible. Using Vercel Remote Cache or a self-hosted S3-compatible store, every task hash is checked remotely before execution. For Vercel-hosted projects and for Next.js applications, the integration is seamless. For other environments, you need to evaluate egress and storage costs. One team I worked with saw CI times drop from 22 minutes to 6 minutes after enabling remote caching, but their cache storage grew to 340GB within two months because they cached .next/cache inadvertently until we added the exclusion pattern shown above.

Turborepo also intentionally avoids daemons and long-running processes. Every turbo run invocation recomputes hashes. This makes it more predictable and easier to debug than Nx's daemon, but slightly slower on repeated local runs. For teams that value simplicity over maximum local incrementality, that trade is often worth it. Referencing standards like MDN Web Docs for output definitions (for example, understanding what dist/** actually emits for ESM vs CJS) helps you define outputs precisely and avoid cache poisoning.

Bazel's Hermetic Build Graph: Correctness Guarantees That Cost You Flexibility

Bazel is in a different category entirely. Where Nx and Turborepo meet you where you are — JavaScript, TypeScript, Node.js — Bazel asks you to describe your entire build hermetically. Hermetic means every input, toolchain, and environment variable is declared explicitly, and the build is sandboxed so it cannot access undeclared files or network resources. This is how Google builds billions of lines of code reproducibly, and it is also why Bazel adoption fails when teams underestimate the migration cost.

Every package needs a BUILD.bazel file that declares targets, sources, deps, and toolchain constraints. Bazel does not scan your imports to guess dependencies; you tell it.

load("@aspect_rules_js//js:defs.bzl", "js_library")
load("@aspect_rules_ts//ts:defs.bzl", "ts_project")
load("@aspect_rules_jest//jest:defs.bzl", "jest_test")

ts_project(
    name = "ui_components",
    srcs = glob(["src/**/*.ts", "src/**/*.tsx"]),
    declaration = True,
    tsconfig = "//:tsconfig.json",
    deps = [
        "//libs/design-tokens:tokens",
        "//libs/utils:utils",
        "@npm//react",
        "@npm//@types/react",
    ],
)

jest_test(
    name = "unit_test",
    data = [":ui_components"],
    node_modules = "//:node_modules",
)

js_library(
    name = "pkg",
    srcs = [":ui_components"],
    visibility = ["//visibility:public"],
)

Note the explicitness: if ui_components imports from libs/design-tokens but you forget to list it in deps, the build fails in the sandbox even if it works on your laptop because your laptop has the file on disk and the sandbox does not. I've found that this strictness is valuable at scale — it eliminates the "works on my machine" class of failures — but it requires a cultural shift. Engineers can no longer add a quick import and push; they must maintain build files.

Action Graph, Sandboxing, and the Language Agnostic Payoff

Bazel's power emerges when your monorepo is not just JavaScript. If you build Go services, Python ML pipelines, Docker images, and protobuf-generated clients in the same repository, Bazel gives you a single tool that understands all of them with correct incremental builds and remote execution. Nx and Turborepo are excellent for JS/TS but delegate to other tooling for non-JS languages. Bazel can build the Go binary, compile the TypeScript client from the same proto, and push the container, all with a shared cache key scheme.

The cost is operational. You'll need to maintain rulesets (rules_js, rules_ts, rules_go), manage toolchain versions, and train the team on Starlark. Build performance is exceptional once remote execution (RBE) is configured, but without RBE, Bazel can feel slower locally than Nx or Turborepo because sandboxing has overhead. I typically see teams succeed with Bazel when they have dedicated build infrastructure engineers and a polyglot codebase larger than ~500k lines. Below that, the ROI rarely justifies the complexity.

Modeling Cross-Project Dependencies Without Creating a Distributed Monolith

The most common failure mode I see is not tool choice but dependency hygiene. A monorepo makes it trivial to import anything from anywhere, and without guardrails you quickly create a distributed monolith — dozens of packages that appear independent but are tightly coupled through deep imports.

All three tools give you mechanisms to prevent this, but you have to use them intentionally. In Nx, you can tag projects and then define constraints in .eslintrc.json:

For example, tag scope:shared, scope:feature-dashboard, type:lib and enforce that scope:feature-* can only depend on scope:shared and not on each other. This is validated at lint time and in CI. Turborepo does not have this built-in; I've paired it with tools like eslint-plugin-boundaries or Knip to achieve similar enforcement. Bazel enforces visibility natively via visibility attributes, which is stronger because the build fails if you violate it, not just the linter.

Another practical consideration is versioning strategy. If you publish libraries from the monorepo, you need a consistent approach to version bumps. This is where Conventional Commits: Automating Changelogs and Semantic Versioning becomes essential. I've standardized on conventional commits plus Nx release or Changesets (which pairs well with Turborepo) to automatically bump affected packages based on commit history walking the graph. Bazel teams often use a different pattern — building all artifacts at a single version (a monorepo-wide version) which simplifies reasoning but complicates external publishing.

Structuring Boundaries for Parallelism

Think about your graph shape. A star graph where every app depends on a single shared-ui library will serialize builds around that library. A layered graph — tokens -> primitives -> components -> features -> apps — allows much higher parallelism. In my experience, dedicating a day to restructuring imports into layers yields more CI speedup than any caching optimization. Tools can only parallelize what your architecture allows them to. I recommend auditing your graph monthly with nx graph or bazel query --output graph and addressing nodes with high fan-in.

Incremental Adoption: Strangling a Polyrepo Into a Monorepo Without Halting Feature Delivery

Almost no team gets to start greenfield. The migration path matters more than the end state because you need to ship features while moving. I've migrated two polyrepos into monorepos using the strangler pattern: create the monorepo shell, move one or two low-risk packages first, wire up tooling, prove CI savings, then migrate in waves.

With Nx, this is particularly smooth because nx init can wrap an existing pnpm workspace without moving files. You can keep your existing npm scripts and add Nx targets gradually. Turborepo is similar — add a root turbo.json and it will wrap your existing scripts with zero file moves. This low friction is intentional.

Bazel requires a more committed approach. You need to decide early whether you will use rules_js with npm workspaces or full-managed external dependencies via npm_translate_lock. I have seen teams attempt a hybrid — running Bazel only for CI and npm scripts locally — but that defeats reproducibility and guarantees drift. If you choose Bazel, commit to using it locally as well, and invest in build-time support during the migration. Pair your migration with Git Hooks for Automation: Pre-commit, Pre-push and CI Integration to enforce that new code follows the new build definitions.

A practical migration checklist I use includes: first, normalize package managers and lockfiles; second, consolidate CI workflows into a single affected-aware workflow; third, enable remote caching early (even with low hit rate, it builds team habits); fourth, enforce module boundaries from day one on new code even if legacy code is grandfathered. This incremental enforcement, often informed by referencing IETF RFC Standards for any shared protocol contracts you generate (like OpenAPI or protobuf over HTTP), keeps the migration from becoming a months-long freeze.

Capability Nx Turborepo Bazel
Graph source of truth Inferred from imports + explicit config Inferred from package manager workspaces + pipeline Explicit in BUILD files (hermetic)
Language scope JS/TS first-class, plugins for others JS/TS focused Polyglot (Go, Java, Python, JS, Docker)
Local cache / daemon Daemon + local cache, fast warm runs File-system cache, no daemon Sandboxed local cache + optional RBE
Remote caching Nx Cloud / self-hosted, high hit rate Vercel / self-hosted S3, simple setup Buildbarn / EngFlow, requires RBE
Learning curve Moderate, gradual adoption Low, convention over config High, requires Starlark + toolchains
Architectural enforcement Module boundary lint rules External via ESLint plugins Visibility + build graph enforcement
Ideal team size 20–200 engineers 5–80 engineers 100+ engineers, dedicated build team

Frequently Asked Questions

Should we choose Nx or Turborepo for a Next.js-heavy monorepo under 50 packages?

For under 50 packages with heavy Next.js usage, I usually recommend Turborepo. Its pipeline model maps directly to Next.js build outputs and its integration with Vercel remote caching is zero-friction. You will get 70–80% of the benefit with minimal configuration. Consider Nx if you need scaffolding, module boundary enforcement, or plan to scale past 100 packages within a year, as Nx's affected analysis and graph tooling become more valuable as complexity grows.

How do we avoid cache poisoning when enabling remote caching?

Define inputs and outputs precisely and avoid caching non-deterministic artifacts. Exclude caches within caches (e.g., .next/cache, node_modules/.cache), pin toolchain versions, and include lockfiles in your hash inputs. In Nx, use inputs and namedInputs to be explicit; in Turborepo, audit pipeline.outputs per task. I've found that running turbo run build --dry-run or nx show hash --target=build locally before enabling remote writes helps surface missing inputs before they corrupt shared cache.

Is Bazel worth it if our codebase is primarily TypeScript?

Usually not unless you have specific requirements that Nx/Turborepo cannot meet: strict hermetic reproducibility for compliance, remote execution at massive scale, or a polyglot build spanning languages beyond JavaScript. For a pure TypeScript monorepo, the incremental correctness Bazel provides rarely offsets the maintenance cost of BUILD files and rulesets. I've seen TypeScript-only teams adopt Bazel and later revert to Nx because developer velocity mattered more than bit-for-bit reproducibility.

Can we mix tools or migrate from Turborepo to Nx later?

Yes, and this is common. Both Nx and Turborepo read package.json workspaces, so they can coexist briefly. A pragmatic path is to start with Turborepo for fast wins, then wrap it with Nx using npx nx init --integrated which preserves your turbo.json as Nx targets during transition. For Bazel, mixing is harder because of hermeticity assumptions; plan for a definitive cutover rather than long-term coexistence. In either case, keep your Git history clean with atomic moves so git log --follow remains useful for forensics.

Related Articles

References & Standards: Python Documentation · MDN Web Docs · IETF RFC Standards