What is an Nx Go monorepo and how does Nx caching differ from Go build caching?

In an Nx Go monorepo, every Go module (each directory with its own go.mod) is registered as an Nx project with its own targets. A go.work file at the repository root lists those modules, so the Go toolchain resolves imports between them from local source and does not fetch published versions. Nx manages orchestration: the project graph, task ordering, and which projects a change affects. Go handles compilation.

Nx and Go each have a cache, and they work at different levels:

Nx task cache Go build cache
Unit of caching A whole target run (build, test, lint) Individual compiled packages and test results
Cache key Hash of declared inputs: files, env vars, runtime values, dependency outputs Source content, imports, build flags, toolchain, relevant env
On a hit Skips the process; restores output files and replays terminal logs Reuses compiled objects; prints (cached) for tests
Correctness risk Stale hits if an input is missing from the hash Very low, because Go derives keys from what the compiler actually reads
Scope Local, and optionally shared across machines Local to GOCACHE on one machine

The two caches fill each other's gaps. On a miss, the Go cache still makes the rebuild incremental, so only changed packages recompile. Nx avoids starting the toolchain at all, which matters on fresh CI runners where GOCACHE is empty unless you restore it.

During a build, Nx checks first. It computes the task hash, and on a hit it replays the stored result. On a miss it runs go build or go test, and the Go toolchain then checks its own cache package by package.

  nx run api:build
        |
        v
+--------------------------------------------+
| Nx task runner                             |
|  hash inputs: files, env, deps' outputs    |
+--------------------------------------------+
        |
        v
+------------------+   hit   +-------------------------------+
| Nx task cache    |-------->| restore outputs, replay logs  |
| (local / remote) |         | go toolchain never starts     |
+------------------+         +-------------------------------+
        | miss
        v
+--------------------------------------------+
| go build / go test   (resolves via go.work)|
+--------------------------------------------+
        | per package
        v
+------------------+   hit   +-------------------------------+
| Go build cache   |-------->| reuse compiled pkg / (cached) |
| ($GOCACHE)       |         | test result                   |
+------------------+         +-------------------------------+
        | miss
        v
+--------------------------------------------+
| compile changed packages, run tests        |
+--------------------------------------------+
        |
        v
  outputs + logs stored in Nx cache under the task hash

Nx checks its task cache first and skips the Go toolchain entirely on a hit. On a miss, go build or go test runs and checks the Go build cache package by package, so only changed packages recompile.

How does an Nx Go monorepo work end to end?

When you run a command such as nx run orders-service:build or nx affected -t test, Nx goes through the same sequence each time:

  1. Project discovery. Nx scans the workspace for project.json files, or for projects inferred by a plugin. Each one becomes a node in the project graph, with a name, a root directory, and a set of targets.
  2. Graph construction. Nx adds edges between projects. For Go, these edges do not appear automatically. They come from implicitDependencies you declare, or from a plugin that reads go.mod, go.work, or imports. The graph decides which projects count as dependencies when Nx hashes inputs and computes affected projects.
  3. Task planning. Nx expands the requested targets into tasks (one per project and target), applies dependsOn rules to order them, and runs independent tasks in parallel.
  4. Hashing. For each task, Nx combines the contents of the files matched by the target's inputs, the values of declared env and runtime inputs, and the hashes of the relevant dependency projects. The result is a single task hash.
  5. Cache lookup. If the hash exists in the local cache, or in a configured shared cache, Nx restores the declared outputs and replays the stored terminal output. The command does not run.
  6. Execution on a miss. Nx runs the target's command, in this setup a go invocation through nx:run-commands. Go resolves local modules through go.work, reuses whatever it can from GOCACHE, and compiles the rest.
  7. Storage. If the command succeeds, Nx stores its outputs and logs under the task hash, so the next identical run is a hit.

Nx never inspects Go semantics while doing this. It knows only the files, variables, and graph edges you declare. That is why the rest of this article is mostly about getting the graph and the inputs right. Correct declarations produce correct cache hits. A missing declaration produces a stale one.

Who should use Nx for Go services, and when should you avoid it?

Nx earns its place when a repository holds several Go services that share internal libraries. In that layout, a change to a shared package can ripple into many binaries, and someone has to decide what to rebuild and retest. Nx answers that question from its project graph instead of relying on a hand-maintained CI script. The payoff grows with the number of services, because affected detection lets CI skip the projects a commit cannot have touched.

Two other cases favour Nx:

  • Cross-language orchestration. If a Go API and the TypeScript client generated from it live in the same repository, one task runner can order those steps.
  • Shared or remote caching. Go's build cache is local to a machine and a user. Nx can share task results across developers and CI runners, so a test suite that passed on one machine does not run again on another for the same inputs.

When it costs more than it returns

For a single small module, Go's own cache already removes most repeated compile work. Wrapping it in Nx adds a layer whose main effect is extra configuration.

The cost does not end at setup. Nx is a second build system, with its own config files, a background daemon, cache directories and plugin versions to keep aligned. When a cache hit looks wrong, engineers must work out whether Nx or the Go toolchain served the result. Every new hire learns both. If no one on the team will own that surface, the speedup rarely survives the first confusing stale build.

What are the alternatives to Nx for Go monorepos?

Nx is one option among several. The main alternatives trade setup cost against how precise the rebuild decisions are:

Alternative How it decides what to build Strengths Weaknesses
Plain Go toolchain with go.work Run go build ./... and go test ./... across every module, and rely on GOCACHE No extra tooling. The Go cache keys are accurate No task-level skipping. Every module's commands start on every run. Cold CI runners recompile everything unless GOCACHE is restored
Make, shell scripts, or CI path filters Hand-written rules or per-directory path triggers in the CI config Simple and transparent for a few services Path filters do not follow imports, so a change to a shared library can skip its consumers. The rules drift as the repository grows
Custom affected detection with go list Map the changed files from git diff to packages, then use go list -deps to find the packages that depend on them Uses Go's real import graph, so no edges are maintained by hand You write and maintain the script yourself. No cross-machine result caching
Build systems with native Go rules Build rules declare every source and dependency. Actions run hermetically and their results are cached by content Precise, fine-grained caching and remote execution. Strong correctness guarantees Large up-front migration. Developers have to learn a new build language. Go modules must be mirrored into the build system's own dependency declarations
Separate repositories per service Each repository builds only itself. Shared libraries are versioned and consumed as published modules Clear ownership and simple per-repo CI Cross-cutting changes need coordinated releases across repositories. You cannot test a library change against all its callers in one commit

Nx sits between scripts and a full hermetic build system. It provides graph-aware affected runs and shared task caching without replacing the Go toolchain. In exchange, its correctness depends on inputs you declare instead of inputs it observes. If your repository is Go-only and stays small, plain go.work with a restored GOCACHE may be enough. If you need hermetic, fine-grained builds across many languages, a build system with native Go rules may justify its migration cost.

How do you lay out Go modules and go.work for Nx?

Give every deployable service and every shared library its own directory and its own go.mod, for example services/orders, services/billing, and libs/auth. Each directory becomes one Nx project, so the project boundary and the module boundary match. When they match, Nx can build a project graph from the module graph without guessing which package belongs to which project.

At the repository root, a go.work file lists those directories with use directives. In workspace mode, when services/orders imports libs/auth, the toolchain resolves it to the local directory instead of downloading the version pinned in orders/go.mod. This removes the need for replace directives pointing at ../../libs/auth. Those directives are easy to commit by accident, and they break anyone who consumes the module from outside the repository.

Decide the go.work policy once

Two policies are reasonable:

  • Commit go.work and go.work.sum. Local development and CI both build against the code in the repository, so a library change and its callers are tested together.
  • Keep go.work local and set GOWORK=off in CI. Each module builds against the dependency versions in its own go.mod. This shows what an external consumer, or an independently released service, would actually compile.

The two modes can produce different binaries from the same source. With workspace mode on, orders picks up an unreleased change in libs/auth. With GOWORK=off, it uses the last tagged version. Nx does not know which mode produced a cached artifact unless you tell it. Whichever policy you choose, include go.work, go.work.sum, and the GOWORK environment variable in the cache inputs. Otherwise a result cached in one mode can be replayed as a hit in the other.

go work init ./services/orders ./services/billing ./libs/auth

cat > nx.json <<'EOF'
{
  "namedInputs": {
    "goModule": [
      "{projectRoot}/**/*.go",
      "{projectRoot}/go.mod",
      "{projectRoot}/go.sum"
    ],
    "goWorkspace": [
      "{workspaceRoot}/go.work",
      "{workspaceRoot}/go.work.sum",
      { "env": "GOWORK" }
    ]
  },
  "targetDefaults": {
    "build": {
      "cache": true,
      "inputs": ["goModule", "^goModule", "goWorkspace"]
    },
    "test": {
      "cache": true,
      "inputs": ["goModule", "^goModule", "goWorkspace"]
    }
  }
}
EOF

GOWORK=off npx nx run-many -t build test

This example creates a root go.work for three local modules and configures nx.json so that go.work, go.work.sum and the GOWORK environment variable are cache inputs for every build and test target, which keeps results from workspace mode and GOWORK=off cached separately.

How do you define build, test, and lint targets in project.json?

Each Go module gets a project.json with three targets, all using the nx:run-commands executor. The executor only runs a shell command. Nx decides whether to run it at all, based on the fields around it.

  • command: the Go invocation. For example, go build -o {workspaceRoot}/dist/{projectRoot}/server ./cmd/server, go test ./..., and go vet ./.... The -o path matters. If the binary lands inside the module directory, Nx has no declared location to restore it to, and the binary may end up hashed as a source file. A dedicated dist path keeps outputs separate from inputs.
  • cwd: set this to {projectRoot}. Go resolves ./... and go.mod relative to the working directory, so running from the workspace root would test the wrong package set.
  • inputs: reference the named input from the previous section, so every target hashes .go files, go.mod, go.sum, and the workspace files.
  • outputs: only build needs this, pointing at {workspaceRoot}/dist/{projectRoot}. For test and lint, Nx caches and replays the terminal output, which is all those targets produce.
  • cache: true for all three.
  • dependsOn: usually leave it empty. go build compiles dependent packages itself, so adding ^build only schedules redundant work. Use dependsOn for real prerequisites, such as a generate target that runs go generate.

Split tests that use a database, network, or other external service into a separate integration-test target. Set cache: false on it. A passing result says nothing about tomorrow's database state. If you do want to cache it, add the relevant dependencies as env or runtime inputs, such as a schema version or container image digest.

{
  "name": "orders-service",
  "projectType": "application",
  "targets": {
    "build": {
      "executor": "nx:run-commands",
      "options": {
        "command": "go build -o {workspaceRoot}/dist/{projectRoot}/server ./cmd/server",
        "cwd": "{projectRoot}"
      },
      "inputs": ["go"],
      "outputs": ["{workspaceRoot}/dist/{projectRoot}"],
      "cache": true
    },
    "test": {
      "executor": "nx:run-commands",
      "options": { "command": "go test ./...", "cwd": "{projectRoot}" },
      "inputs": ["go"],
      "cache": true
    },
    "lint": {
      "executor": "nx:run-commands",
      "options": { "command": "go vet ./...", "cwd": "{projectRoot}" },
      "inputs": ["go"],
      "cache": true
    },
    "integration-test": {
      "executor": "nx:run-commands",
      "options": {
        "command": "go test -tags=integration ./...",
        "cwd": "{projectRoot}"
      },
      "cache": false
    }
  }
}

A project.json for a Go service. The build, test and lint targets run Go commands from the module root, hash the shared "go" named input, and write the binary to a dist path that Nx can restore from cache. The database-backed integration tests run as a separate target with cache: false.

Which cache inputs prevent stale Nx hits for Go code?

Define a production named input in nx.json for everything that shapes a binary. Have build consume production and ^production, so changes in dependency modules also invalidate the hash. Define a second named input for tests that adds _test.go files and test fixtures. Declaring each set once keeps every Go project in sync. Without named inputs, one project's project.json eventually omits go.sum and nobody notices.

Exclude _test.go from production with a negated glob. Test files never reach the binary, so including them makes a test-only edit trigger a pointless rebuild.

Input Why it matters What happens if it's missing
{projectRoot}/**/*.go, minus *_test.go Source compiled into the binary Stale binary is replayed after a code change
go.mod, go.sum Pin dependency versions A dependency bump replays the old build
go.work Decides which local modules replace remote ones Workspace edits are silently ignored
//go:embed assets Compiled into the binary as bytes Binary ships old templates or migrations
Generated code or its generator inputs Often produced outside the project's globs Hash misses schema changes
GOOS, GOARCH, CGO_ENABLED, GOWORK as env inputs Change the output without touching files A Linux binary is restored on a macOS runner
go version as a runtime input The toolchain changes codegen and vet rules Shared or remote caches mix toolchains

Both failure modes are silent. A missing build input replays an outdated binary that looks valid. A missing test input replays a green result for code that would now fail. The table rows only help if each one is listed in the named inputs.

{
  "namedInputs": {
    // Everything that shapes the compiled binary. Test files are excluded.
    "production": [
      "{projectRoot}/**/*.go",
      "!{projectRoot}/**/*_test.go",
      "{projectRoot}/go.mod",
      "{projectRoot}/go.sum",
      "{workspaceRoot}/go.work",
      "{workspaceRoot}/go.work.sum",
      // Files pulled in via //go:embed
      "{projectRoot}/templates/**/*",
      "{projectRoot}/migrations/**/*",
      // Generator input that lives outside the project root
      "{workspaceRoot}/api/openapi.yaml",
      { "env": "GOOS" },
      { "env": "GOARCH" },
      { "env": "CGO_ENABLED" },
      { "env": "GOWORK" },
      // Toolchain version, so shared or remote caches never mix compilers
      { "runtime": "go version" }
    ],
    // Build inputs plus the test sources and fixtures
    "goTest": [
      "production",
      "{projectRoot}/**/*_test.go",
      "{projectRoot}/testdata/**/*"
    ]
  },
  "targetDefaults": {
    // ^production: changes in dependency modules also invalidate the hash
    "build": { "cache": true, "inputs": ["production", "^production"] },
    "test": { "cache": true, "inputs": ["goTest", "^production"] }
  }
}

An nx.json that declares shared production and goTest named inputs once, covering Go sources, module and workspace files, embedded assets, generator inputs, build-affecting env vars and the toolchain version, and applies them to every Go project's build and test targets.

How do Nx affected commands know which Go services changed?

nx affected does two things. It maps the files changed between a base and head commit to the projects that own them. Then it walks the project graph to find every project that depends on those owners. The second step is where Go repos break. Nx does not read Go imports by default, so a change to libs/auth marks only libs/auth as affected. The services that import it are skipped, and CI ships them untested.

You can close that gap in two ways:

Approach How edges are created Failure mode Upkeep
Manual implicitDependencies You list dependent projects in each project.json Drifts when someone adds or removes an import and forgets the file Every import change across module boundaries
Community nx-go plugin Infers edges from go.mod requires, go.work, or parsed imports Inference gaps, such as missed replace directives or unsupported layouts Plugin upgrades and compatibility with your Nx version

Manual lists suit a handful of stable modules. Past that, they become a second dependency graph that nobody reviews. A plugin removes that duplication, but you depend on someone else's maintenance. Before adopting one, check that it is actively released and supports your layout (multi-module or single module). Also check whether it generates targets or only graph edges.

Whichever approach you use, open nx graph after changing a shared module and confirm that every importing service shows an edge. If the graph is wrong, the affected list and the cache scope are wrong too.

You can also skip Nx for this step. Plain Go tooling, such as go list -deps combined with a git diff, can compute the affected packages. Build systems with native Go rules can derive the graph directly from source.

How do you run affected Go builds in CI and verify the cache is correct?

For pull requests, compare against the merge base with the target branch, not the target branch's current tip. Pass --base as the target branch ref and --head as the commit under test, then run nx affected -t build test lint. Nx resolves the merge base itself, but only if that commit exists locally. Shallow clones cause most CI surprises here. If the merge base is missing, the diff comes out wrong. You either miss services that changed or rebuild everything. Fetch full history, or at least enough commits to reach the merge base. Fail the job if git merge-base returns nothing, so the run doesn't quietly fall back to a full build. On the main branch, use the last commit that passed CI as the base, not HEAD~1, so commits from a failed run aren't skipped.

Persist GOCACHE and GOMODCACHE in their own cache entries, keyed on the go.sum files. Keep them out of Nx's cache directory. The Nx cache replays whole task results. The Go caches speed up the tasks that actually run. If you mix them, an eviction or corruption in one breaks the other.

Verifying the cache

  1. Edit a .go file in one service and rerun. Only that service and its dependents should run. Every other target should replay from cache.
  2. Edit something outside every declared input, such as a README. Every target should be a cache hit.
  3. If results look wrong, rerun with --verbose and compare the task hash details between the two runs. Look for an input that is missing or that changes on every run.
  4. Use --skip-nx-cache for a periodic full build as a backstop.

Illustrative estimate (assumed inputs): 20 services, full CI 25 minutes, typical PR affects 3 services and takes 6 minutes, 15 engineers each waiting on 4 PR runs a day. Each run saves 19 minutes, which works out to about 19 engineer-hours of waiting per day. Expect less in practice, because engineers switch to other work while CI runs.

How can Nx save engineering time in a Go monorepo?

The time savings come from four sources. Each depends on the graph and inputs described above being correct.

  • Shorter CI feedback on pull requests. nx affected limits a run to the services a change can reach, and the task cache skips any of those whose inputs have not changed since an earlier run. Engineers wait for a few services instead of the whole repository. The illustrative estimate in the previous section shows how to size this for your own repository: replace the assumed service count, durations, and run frequency with figures from your CI history.
  • Fewer repeated runs across machines. With a shared cache, a test result produced by CI on a branch can be replayed when a developer runs the same target locally at the same commit, and the reverse also works. Go's local GOCACHE cannot do this, because it lives on one machine.
  • Less hand-maintained CI logic. Without a task runner, someone writes and updates the scripts or path filters that decide which services to build and in what order. With Nx, that decision comes from the project graph and the targetDefaults in nx.json. Adding a service then means adding a project.json instead of editing pipeline rules.
  • Faster diagnosis of change impact. nx graph and nx affected show which services a change to a shared library reaches before it merges. That shortens reviews of cross-cutting changes and makes it less likely that a consumer breaks after release.

The savings have offsetting costs. These include the setup and upkeep described in the section on when to avoid Nx, and the time spent investigating stale hits when an input is missing. The savings tend to exceed those costs when the repository has many services, frequent pull requests, and long test suites. They also need someone who owns the Nx configuration and runs the verification steps above periodically. In a small repository with fast tests, Go's own cache already captures most of the benefit, and the net saving may be close to zero.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to nx go monorepo, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.