What is an Nx protobuf library and why make it own the contract?

An Nx protobuf library is a single Nx project that holds your .proto files and also owns the step that turns them into code. Each service does not run its own protoc invocation. Instead, it depends on a per-language generated output, such as a TypeScript package or a Go module, and that dependency is declared in the Nx project graph. The contract becomes a first-class node in the graph, not a folder that scripts happen to read.

That placement is what makes the pattern better than hand-maintained scripts. Once the contract is a node, Nx can work out which services are affected by a change to a .proto file. It can cache generated output keyed on the proto sources and the tool config. It can also run a breaking-change check as an ordinary target on the contract project. A shell script in tools/ has no idea who consumes its output, so it can do none of this.

The pattern suits backend and platform teams running several gRPC services in one Nx workspace. It pays off most in polyglot workspaces, where generating stubs for each language by hand is the first thing to drift.

Adopt it when two or more services share contracts and deploy independently. Avoid it in these cases:

  • You have a single service.
  • Most consumers of the contracts live outside the repository.
  • The team won't take on maintaining codegen toolchains.

The time saving is direct. Nobody has to remember to regenerate stubs, and CI rebuilds and tests only the services that depend on the changed contract.

Who should use it?

The pattern fits a specific kind of workspace. Use it if most of these are true:

  • Several gRPC services share message and service definitions. The value comes from one contract feeding many consumers. With a single producer and a single consumer, a plain generate script is enough.
  • The services live in one Nx workspace. The pattern relies on the Nx project graph to connect contracts to consumers. Services in other repositories never appear in that graph.
  • More than one language consumes the contracts. A Go backend and a TypeScript BFF that both read orders.proto are the typical case. Each language has its own plugins and output layout, and keeping them in step by hand is where drift starts.
  • Services deploy independently. If everything always ships together from one commit, wire compatibility between versions matters less, and the breaking-change checks described below matter less with it.
  • Someone owns the codegen toolchain. Usually a platform or developer-experience engineer. That person pins buf and plugin versions, upgrades them deliberately and keeps the generate target's inputs accurate.

Within those teams, the people who interact with the library differ. Contract authors edit .proto files and deal with lint and breaking-change failures. Service developers mostly consume generated clients and rarely touch codegen configuration. The platform owner maintains buf.gen.yaml, the plugin pins and the Nx target definitions. If no one is willing to take that last role, the setup degrades into unpinned plugins and stale caches. A simpler approach is the better choice in that case.

How does it work?

The whole mechanism is a chain of Nx projects linked by dependency edges, with codegen modelled as an ordinary cacheable target:

  1. Contracts live in one project. The proto library contains only .proto files and buf configuration. Its directory layout matches the proto package names, so every file has exactly one import path.
  2. A generate target runs codegen. The target runs buf generate (or protoc) using pinned plugins and writes per-language output. Its inputs are the proto sources, the buf configs and the plugin pin file. Its outputs are the generated directories.
  3. Generated code lands in per-language libraries. proto-ts, proto-go and similar projects hold the output. Services depend on these, never on each other.
  4. Consumers declare the ordering. Service build and typecheck targets use dependsOn: ["^generate"], so generated code exists before anything compiles against it.
  5. Nx hashes and caches. Before running generate, Nx computes a hash from the declared inputs. If a matching entry exists in the local or remote cache, Nx restores the outputs instead of running buf. Running buf happens only when the contract, the config or the plugin versions actually change.
  6. Affected detection follows the edges. When a .proto file changes, nx affected walks from the proto library through the generated libraries to every consuming service. CI builds and tests that set and nothing else.
  7. Contract checks run as targets too. buf lint and buf breaking are separate cacheable targets on the proto library. They run in the same affected pipeline and fail the build before an incompatible schema reaches any service.

The rest of this guide covers each step in detail: layout, the generate target, dependency wiring, a worked example, the commit-or-generate decision and breaking-change protection.

How should you lay out proto sources and generated code?

Keep the proto library free of anything except .proto files and a buf.yaml. Lay out the directories to match the package names. A file declaring package acme.orders.v1; belongs at libs/proto/acme/orders/v1/orders.proto, and libs/proto is the buf module root and import root.

This alignment matters because every generator derives output paths and import statements from the path a file is imported by, not from where it sits on disk. If orders.proto is imported as orders/v1/orders.proto from one root and as acme/orders/v1/orders.proto from another, each language breaks differently:

  • Python emits modules whose imports don't resolve as packages.
  • TypeScript generates relative imports that point at missing files.
  • Go ends up with go_package options that no longer match the output directories.

Buf's lint rules for directory and package matching catch this early.

Where generated code lives

Option A: inside the proto library Option B: thin library per language
Project graph One node proto plus proto-ts, proto-go, proto-py
Toolchain exposure Every consumer depends on all generated languages A service depends only on its language's library
Cache granularity Any codegen change invalidates everything Each language caches separately
Setup cost Low More project configs and targets

Option B is usually the better choice past a handful of services. A TypeScript service depends on proto-ts and never touches Go or Python tooling, so a broken Python plugin doesn't block its build.

One library or one per domain

A single proto library is the simplest setup. The cost is that every .proto edit marks every consumer as affected. Splitting into per-domain libraries such as proto-orders and proto-billing narrows the affected set. In exchange, you maintain more buf and Nx configuration and must manage cross-library imports explicitly, including shared types like money or pagination.

version: v2
lint:
  use:
    # STANDARD includes PACKAGE_DIRECTORY_MATCH, which fails when
    # acme.orders.v1 is not at acme/orders/v1/. It also includes
    # PACKAGE_VERSION_SUFFIX, which requires the trailing .v1.
    - STANDARD
breaking:
  use:
    # Catch wire-incompatible changes before the affected services rebuild.
    - FILE

This buf.yaml for a proto-only library makes libs/proto the single import root, and its lint rules fail the build when a proto package name doesn't match its directory.

How does grpc codegen with buf work as a cacheable Nx target?

Inside the library, buf.yaml declares the module: where the .proto roots live, plus lint and breaking-change rules. buf.gen.yaml lists the plugins (one for message types and one for gRPC stubs, per language) and the out path for each. A generate target in the library's project.json runs buf generate. If buf isn't an option, the same target can call protoc directly with explicit --proto_path and plugin flags. You lose buf's linting and module resolution, but the caching model stays the same. Whichever you use, pin every plugin version yourself so that a given input always produces byte-identical output.

For Nx to restore codegen from cache, the target needs accurate boundaries:

  • inputs: the .proto files, buf.yaml, buf.gen.yaml, and whatever file holds the plugin version pins.
  • outputs: each generated directory.
  • Consumers: their build and typecheck targets declare dependsOn: ["^generate"], so generation runs, or restores, before anything compiles against it.

Getting inputs wrong fails in two directions. If they are too narrow, for example the protos are listed but the plugin pins are not, a plugin upgrade restores stale code without warning. If they are too broad, for example the whole workspace is listed, unrelated edits change the hash and the cache almost never hits.

Where plugins execute is a trade-off. Remote or hosted execution removes local installs but adds a network dependency to every uncached build. Local execution keeps builds offline but makes you manage the toolchain. In a polyglot repo, unpinned compilers or runtimes produce output that differs between machines, so cache entries created on one machine won't match what another machine would generate.

{
  "targetDefaults": {
    "generate": {
      "executor": "nx:run-commands",
      "options": {
        "command": "buf generate",
        "cwd": "{projectRoot}"
      },
      "cache": true,
      "inputs": [
        "{projectRoot}/proto/**/*.proto",
        "{projectRoot}/buf.yaml",
        "{projectRoot}/buf.gen.yaml",
        "{projectRoot}/plugin-versions.json"
      ],
      "outputs": [
        "{projectRoot}/gen/ts",
        "{projectRoot}/gen/go"
      ]
    },
    "build": {
      "dependsOn": ["^generate", "^build"]
    },
    "typecheck": {
      "dependsOn": ["^generate"]
    }
  }
}

An nx.json targetDefaults block that hashes only the protos, buf configs and plugin pin file for a cacheable generate target, lists the generated directories as outputs, and makes consumers' build and typecheck targets run or restore generate first.

How do you make a .proto change mark every dependent service as affected?

Nx decides what is affected from the project graph, so a .proto edit only reaches a service if an edge connects them. The most reliable edge is a real import. When a TypeScript service imports the generated client through its workspace path alias, Nx infers the dependency from source analysis, and the edge stays correct as code changes. For languages Nx doesn't analyze natively, a language plugin may infer edges from module files. Otherwise, you declare implicitDependencies in the service's project.json.

Implicit dependencies carry a real risk. Nothing checks that they are complete. If a new service starts consuming the generated Go package and nobody adds the edge, nx affected silently leaves that service out, and CI reports green on a contract change that was never built or tested against it. Prefer inferred imports where you can, and treat every hand-written edge as something to review.

Verify the wiring instead of assuming it. Open nx graph and confirm that the proto library feeds each generated library, and that each generated library feeds its consumers. Then touch a .proto file and run nx show projects --affected or nx affected -t build. Every consuming service should appear in the output.

Finally, tag projects by role, for example type:contract, type:generated-client and type:service. Then configure the @nx/enforce-module-boundaries lint rule so that services may depend only on contract and generated-client projects. This blocks one service from importing another's implementation and keeps the proto library as the only coupling point. The rule runs through ESLint, so it covers JavaScript and TypeScript projects. Other languages need their own enforcement, such as a module-path check in the Go build or a review rule on import statements.

// eslint.config.mjs (workspace root)
// Services may depend only on contracts and generated clients, so the
// proto library stays the only coupling point between services.
import nx from '@nx/eslint-plugin';

export default [
  ...nx.configs['flat/base'],
  ...nx.configs['flat/typescript'],
  {
    files: ['**/*.ts', '**/*.js'],
    rules: {
      '@nx/enforce-module-boundaries': [
        'error',
        {
          depConstraints: [
            {
              // A service never imports another service's code.
              sourceTag: 'type:service',
              onlyDependOnLibsWithTags: ['type:contract', 'type:generated-client'],
            },
            {
              // Generated clients are built only from the .proto contracts.
              sourceTag: 'type:generated-client',
              onlyDependOnLibsWithTags: ['type:contract'],
            },
            {
              // Contracts sit at the bottom of the graph.
              sourceTag: 'type:contract',
              onlyDependOnLibsWithTags: ['type:contract'],
            },
          ],
        },
      ],
    },
  },
];

// Each project declares its role in project.json, for example:
//   "tags": ["type:service"]
// Verify the edges with: nx graph
// Then edit a .proto file and check: nx show projects --affected

An ESLint flat config that uses @nx/enforce-module-boundaries with role tags, so services can import only contract and generated-client projects and never each other.

Worked example: one contract, two languages, three services

The workspace

Assume one contract and three consumers:

  • contracts-proto holds the .proto files and owns the buf generate target.
  • contracts-ts contains the generated TypeScript client and depends on contracts-proto.
  • contracts-go contains the generated Go stubs and also depends on contracts-proto.
  • orders-api (Go) and billing-worker (Go) depend on contracts-go.
  • web-bff (TypeScript) depends on contracts-ts.

The graph is a diamond with a single root. No service depends on another service, so the proto library is the only path through which a change in one can reach another.

Editing one message

Suppose you add a field to OrderCreated. The hash of contracts-proto changes, so its generate target runs again. Both generated libraries list the proto library's outputs as inputs, so they rebuild, and all three services rebuild and retest. Nx hashes tasks by their inputs, not by whether a dependency's output actually changed. A comment-only edit to a .proto file therefore causes the same full cascade. That cost is deliberate, because it means no consumer can silently keep building against a stale contract.

Editing one service

Now change a handler inside billing-worker instead. Only that project's hash changes. Its build and tests run. The proto library and both generated libraries are restored from cache, and so are orders-api and web-bff. Nothing is regenerated. A routine service change costs one project's work, and only edits to the shared contract fan out across the workspace.

                  +--------------------+
                  |  contracts-proto   |
                  |  (buf generate)    |
                  | A: REGEN  B: CACHE |
                  +--------------------+
                      |            |
           +----------+            +----------+
           v                                  v
+--------------------+              +--------------------+
|    contracts-ts    |              |    contracts-go    |
| A: BUILD  B: CACHE |              | A: BUILD  B: CACHE |
+--------------------+              +--------------------+
           |                             |          |
           |                       +-----+          +-------+
           v                       v                        v
+--------------------+   +--------------------+   +--------------------+
|    web-bff (TS)    |   |  orders-api (Go)   |   | billing-worker (Go)|
| A: BUILD  B: CACHE |   | A: BUILD  B: CACHE |   | A: BUILD  B: BUILD |
+--------------------+   +--------------------+   +--------------------+

 A = add a field to OrderCreated: all six projects run
 B = edit a billing-worker handler: one project runs, five restore
 REGEN = buf generate runs   BUILD = rebuild + retest   CACHE = restored

Illustrative dependency graph for one proto library, two generated libraries and three services, showing which tasks run or are restored from cache when a shared message changes (A) versus when only billing-worker's own code changes (B).

Should you commit generated code or generate it in CI?

That caching behaviour shapes the choice. When generation is a cached target, regenerating on demand costs little, and committing the output becomes a question of convenience rather than speed.

Concern Commit generated code Generate in CI and locally
IDE experience Types resolve right after checkout Broken imports until the first codegen run
Fresh clone Builds without buf or language plugins Needs the full toolchain before anything compiles
Review noise and conflicts Large diffs. Parallel .proto edits conflict in generated files Diffs show only .proto changes
Stale-code risk High if someone skips regeneration, so CI must regenerate and fail on any diff None, because output always derives from source
Toolchain burden Only contract editors need it, but versions must still be pinned Every developer and every CI job needs pinned buf and plugins
Non-Nx consumers Can read files from the repo, but this couples them to your layout Nothing exists outside the build

Committing moves cost onto reviewers and onto a CI drift check, which you must have or stale code will eventually ship. Generating moves cost onto onboarding and environment setup. If you already pin the toolchain in a dev container or similar, that cost is small. For most monorepos where all consumers live inside the workspace, generating and relying on the cache is the cheaper long-run option.

Neither option serves consumers outside the monorepo. They cannot depend on an Nx library, and Nx has no mechanism for distributing contracts beyond the workspace. External services and partner teams need a separate publishing step, such as versioned language packages or a schema registry. Budget for that pipeline whichever option you choose.

How do you prevent breaking changes between independently deployed services?

Inside the workspace, the protection comes from two extra targets on the proto library: one that runs buf lint and one that runs buf breaking against the main branch. Lint enforces naming and package conventions so that generated code stays predictable across languages. The breaking check compares the current schema with the one on main and fails when a field is renumbered, its type changes, or it disappears without being reserved. These are wire-level problems that no compiler will report. A renumbered field still compiles in every service, but it decodes as garbage or as a default value for any peer using the old number.

Because both targets depend only on the .proto sources, they are cacheable and run only when the contract changes. Add them to the same affected pipeline that builds the services.

The rules that keep the check passing:

  • Only add fields. Never reuse or change an existing field number.
  • Reserve removed fields. When you delete a field, reserve both its number and its name so nobody can reintroduce it with a different meaning.
  • Version breaking changes. If a change can't be made additively, put it in a new package under a v2 directory next to v1, and keep serving both until every consumer has moved.

A monorepo can make deploys feel atomic, but they aren't. Comparing against main only proves that services built from the same commit agree with each other. In production, the payment service may still be running last week's build. During any rolling deploy, old and new pods exchange messages. Wire compatibility with contracts that are already deployed is the requirement, and agreement inside the repository doesn't guarantee it.

How can it save engineering time?

The savings come from removing manual steps and from narrowing what CI has to do. Each one maps to a mechanism described above:

  • No manual regeneration. Because consumers declare dependsOn: ["^generate"], building or type-checking a service produces current stubs automatically. Nobody has to remember a script, and nobody spends an afternoon debugging a service compiled against an old client.
  • Cache hits instead of repeated codegen. With accurate inputs, buf generate runs once per contract change. Every later build on any machine sharing the cache restores the output rather than invoking plugins again.
  • CI scoped to the affected set. A service-only change builds and tests one project. Only contract edits fan out, and they fan out to exactly the services that consume them.
  • Breaking changes caught at review time. buf breaking fails the pull request. Without it, the same problem surfaces as decode errors or silently defaulted fields in a running system, which takes far longer to trace back to a renumbered field.
  • Fewer cross-language inconsistencies. One import root and pinned plugins mean the Go, TypeScript and Python outputs come from the same schema with the same tool versions. That removes a class of "works in one service, fails in another" investigations.
  • Less review noise. If you generate rather than commit, contract diffs show only .proto changes, and parallel edits don't conflict inside generated files.

To size the CI effect for your own workspace, work it through with your own numbers. As an illustrative estimate with assumed inputs: assume 12 services, a full build-and-test of 6 minutes per service, and 40 merged changes a week, of which 4 touch a .proto file and the rest touch a single service. Assume also that each contract change affects all 12 services. Rebuilding everything on every change would cost 40 × 12 × 6 = 2,880 service-minutes a week. With affected builds, the 4 contract changes cost 4 × 12 × 6 = 288 minutes and the 36 single-service changes cost 36 × 1 × 6 = 216 minutes, for 504 minutes in total. These figures are illustrative, not measured. Real results depend on how your graph is split, how often contracts change, and whether caches are shared between CI runners and developer machines.

The pattern also has ongoing costs that offset part of the savings: maintaining plugin pins, keeping target inputs accurate, and reviewing hand-written dependency edges. Those costs fall mostly on one toolchain owner. The savings spread across every service team.

What are the alternatives to a shared Nx protobuf library?

The shared library is not the only way to handle shared contracts. Each alternative trades setup effort against how much drift it tolerates and how precisely CI can scope a build.

Approach Setup cost Drift risk Affected-build precision External consumers
Per-service proto copies None High None; nothing links the copies Poor
Separate contracts repo with published packages Medium Low inside a version, high across stale pins Coarse; driven by version bumps Good
Schema registry Medium to high Low, enforced at publish time Outside the monorepo graph Good
Plain scripts, no Nx targets Low Low None; everything rebuilds or nothing does Poor
Shared Nx protobuf library Medium Low Per project, from the graph Needs extra publishing

Per-service copies fail without any visible error. Two copies of order.proto diverge one field at a time. Nothing reports the divergence until a decode error shows up in production.

A separate contracts repository is the right choice when consumers outside your monorepo need the contracts. Versioned packages give those consumers a stable artifact. The cost is a publish-and-bump cycle for every change. Services can also pin old versions indefinitely, which moves the drift problem into dependency management.

A schema registry centralizes breaking-change checks for many repositories. It does not know about your Nx project graph, so it cannot tell you which services to rebuild.

Plain scripts produce correct output. They throw away caching and affected detection, which are the main reasons to run codegen through Nx.

If every producer and consumer lives in one monorepo, the Nx library is usually worth its setup cost. If external consumers depend on the contracts, keep the Nx library and also publish from it.

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 protobuf library, 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.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

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.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • 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.