What is an Nx Python monorepo, and who does what between uv and Nx?
An Nx Python monorepo is a single repository where Python services live as members of a uv workspace and Nx orchestrates work across those members and any TypeScript, Go, or other projects next to them. The two tools have separate jobs.
uv owns the Python environment. It resolves dependencies for every workspace member together, writes one uv.lock at the root, and manages the shared virtual environment. Because there is one lockfile, two services cannot drift onto incompatible versions of the same library without the resolver reporting a conflict.
Nx owns task execution. It runs targets such as test, lint, and build, caches their results, and uses its project graph to work out which projects a change affects.
Keep these responsibilities separate. If Nx targets install packages, you get a second resolution path that can disagree with the lockfile. If you script uv to decide what to rebuild, you lose Nx's caching and graph. Each tool should hand off to the other at a clear boundary: Nx targets call uv run, and uv never decides what runs.
This setup suits platform and backend teams whose Python APIs feed TypeScript frontends or generated clients. One graph then covers changes that cross the language boundary.
repo/
├── pyproject.toml (uv workspace root)
├── uv.lock (single lock, all members)
├── services/
│ ├── orders/ pyproject.toml + project.json
│ └── billing/ pyproject.toml + project.json
├── libs/
│ └── py-common/ pyproject.toml + project.json
└── clients/
└── orders-ts/ project.json (generated from orders API)
Nx project graph:
py-common ──► orders ──► orders-ts
py-common ──► billing
┌───────────────────────── uv: resolve, lock, venv ─────────────────────────┐
│ pyproject.toml (workspace root) uv.lock (one lock, all members) │
│ .venv (shared virtual environment) │
└─────────┬───────────────────────────┬───────────────────────────┬─────────┘
│ │ │
┌───────▼────────┐ ┌───────▼────────┐ ┌───────▼────────┐
│services/orders │ │services/billing│ │ libs/py-common │
│ pyproject.toml │ │ pyproject.toml │ │ pyproject.toml │
│ project.json │ │ project.json │ │ project.json │
└───────┬────────┘ └───────┬────────┘ └───────┬────────┘
│ │ │
└───────────────────────────┼───────────────────────────┘
│ Nx reads project.json targets
┌─────────────────────────────────────▼─────────────────────────────────────┐
│ Nx: run targets, cache results, compute affected projects │
│ │
│ py-common ──► orders ──► orders-ts (clients/, generated TS client) │
│ py-common ──► billing │
│ │
│ each target (test, lint, build) ──► uv run <command> │
│ uv never decides what runs; Nx never installs packages │
└───────────────────────────────────────────────────────────────────────────┘
uv owns the root pyproject.toml, the single uv.lock, and the shared virtual environment for every Python member. Nx reads each member's project.json, builds a project graph that reaches the generated TypeScript client, and runs each target through uv run.
How do you lay out a uv workspace inside an Nx repo?
The root pyproject.toml declares the workspace. Under [tool.uv.workspace], set members to globs such as services/* and libs/*. uv then treats every matching directory with its own pyproject.toml as a member. All members share one virtual environment and one uv.lock at the repo root. This root file only coordinates the workspace. It does not need to describe a deployable package.
Each service and library keeps its own pyproject.toml with its own [project] name, dependencies, and build backend. This keeps ownership local. A change to orders dependencies edits a file inside services/orders/, so Nx attributes the change to that project.
Internal libraries
When orders imports py-common, list py-common in its [project] dependencies. Then map it in [tool.uv.sources] with py-common = { workspace = true }. uv resolves it from the repo rather than an index and installs it as an editable member. Edits to the library are visible to the service immediately, with no rebuild or reinstall step.
Nx targets
Give each member a project.json whose test, lint, typecheck, and build targets use nx:run-commands to call uv run --package orders …, for example with pytest, ruff check, or mypy. The --package flag runs the command in the context of that member. Nx owns orchestration and caching, while uv owns the environment, so neither duplicates the other.
The single-lockfile constraint
uv resolves one version of each package for the entire workspace. Suppose two services need incompatible versions of the same package, such as different major versions of an ORM. Resolution fails. You cannot keep both in one workspace. You have to split one service into a separate uv project with its own lockfile, and Nx can still orchestrate it.
# file: pyproject.toml (repo root, coordinates the workspace only)
[tool.uv.workspace]
members = ["services/*", "libs/*"]
# file: services/orders/pyproject.toml (owned by the orders project)
[project]
name = "orders"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = ["py-common"] # internal library, declared like any other dep
[tool.uv.sources]
py-common = { workspace = true } # resolve from the repo and install as editable
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
# file: services/orders/project.json (Nx orchestrates and caches, uv runs)
{
"name": "orders",
"targets": {
"test": { "executor": "nx:run-commands",
"options": { "command": "uv run --package orders pytest services/orders" } },
"lint": { "executor": "nx:run-commands",
"options": { "command": "uv run --package orders ruff check services/orders" } },
"typecheck": { "executor": "nx:run-commands",
"options": { "command": "uv run --package orders mypy services/orders" } },
"build": { "executor": "nx:run-commands",
"options": { "command": "uv build --package orders" } }
}
}
A virtual uv workspace root, a service pyproject.toml that pulls an internal library in as a workspace source, and an Nx project.json whose targets delegate to uv with --package.
How does Nx learn Python dependency edges it cannot see?
Nx builds its project graph by analysing source files, and its built-in analysis understands JavaScript and TypeScript imports. It does not parse Python import statements, and it does not read pyproject.toml. If billing-api depends on the workspace package shared-models, Nx won't know. A change to shared-models will not mark billing-api as affected.
The simplest fix is to list the edge by hand in implicitDependencies in each project's configuration. This works, but the edge is now recorded in two places. Developers update pyproject.toml because uv needs it to resolve the dependency. They forget the Nx entry because nothing breaks when it is wrong.
The more robust fix is a small local plugin that implements Nx's createDependencies hook:
- Read the workspace
membersglobs from the rootpyproject.toml. - Map each member's
[project] nameto its Nx project. - For each member, take every dependency whose
[tool.uv.sources]entry hasworkspace = true. - Emit a static edge from that member to the matching project.
This drifts less because uv's own configuration is the only source of truth. A wrong declaration fails uv sync, so it gets fixed. The cost is code ownership: the platform team must maintain the plugin, test it against fixture workspaces, and keep it working as Nx's plugin API changes. The plugin also reports only what is declared. An undeclared import that works by accident remains invisible to it.
implicitDependencies |
Local plugin | |
|---|---|---|
| Drift | High; edges are recorded twice | Low; reads the uv config |
| Maintenance cost | Spread across every team | Owned by the platform team |
| Accuracy | Whatever someone typed | Declared workspace dependencies |
| How it fails | Silently skips affected projects | Plugin errors, or undeclared imports are missed |
// tools/nx-uv-plugin/index.ts: local plugin, registered under "plugins" in nx.json
import { CreateDependencies, DependencyType, RawProjectGraphDependency } from '@nx/devkit';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { parse } from 'smol-toml';
// Normalise package names (PEP 503) so 'Shared_Models' matches 'shared-models'.
const norm = (n: string) => n.toLowerCase().replace(/[-_.]+/g, '-');
export const createDependencies: CreateDependencies = (_opts, ctx) => {
// Map each uv member's [project] name to its Nx project and parsed pyproject.
// Simplification: assumes uv members are also Nx projects, instead of expanding globs.
const byPkg = new Map<string, { nxName: string; file: string; toml: any }>();
for (const [nxName, cfg] of Object.entries(ctx.projects)) {
const file = join(cfg.root, 'pyproject.toml');
if (!existsSync(join(ctx.workspaceRoot, file))) continue;
const toml: any = parse(readFileSync(join(ctx.workspaceRoot, file), 'utf8'));
if (toml.project?.name) byPkg.set(norm(toml.project.name), { nxName, file, toml });
}
const edges: RawProjectGraphDependency[] = [];
for (const { nxName, file, toml } of byPkg.values()) {
const sources = toml.tool?.uv?.sources ?? {};
for (const spec of toml.project?.dependencies ?? []) {
// 'shared-models>=0.1' -> 'shared-models'
const name = norm(String(spec).match(/^[A-Za-z0-9][A-Za-z0-9._-]*/)?.[0] ?? '');
// Only workspace sources become edges; PyPI dependencies are ignored.
const isWorkspace = Object.entries(sources).some(
([k, v]: [string, any]) => norm(k) === name && v?.workspace === true,
);
const target = byPkg.get(name);
if (isWorkspace && target) {
edges.push({ source: nxName, target: target.nxName, type: DependencyType.static, sourceFile: file });
}
}
}
return edges;
};
Sketch of a local Nx plugin whose createDependencies hook reads each member's pyproject.toml and emits a static graph edge for every dependency marked workspace = true in [tool.uv.sources].
How should you define cache inputs and outputs for Python targets?
A Python target's cache key should cover everything that can change its result. For a uv project, that means the source and test globs under the project root, the project's pyproject.toml, and the workspace uv.lock. Add the Python interpreter version as a runtime input, because Nx does not detect it on its own. Include the OS and architecture if you ship compiled wheels. Also declare any environment variables your code or tests read, such as feature flags or PYTHONHASHSEED.
Exclude __pycache__, .pytest_cache, .mypy_cache, .ruff_cache, and .venv from both inputs and outputs. As inputs, these directories change on every run and destroy cache hits. As outputs, they restore stale bytecode and machine-specific virtualenv paths onto other machines. Outputs should be the artifacts you actually need replayed, such as dist/ wheels or coverage reports.
The trade-offs
uv keeps one lockfile for the whole workspace. If uv.lock is an input, bumping any dependency marks every Python project as affected and invalidates all of their caches. That result is correct but expensive. Narrowing it requires custom logic that maps lockfile changes to the packages each project resolves. If that mapping misses a transitive dependency, you get a false cache hit, and Nx replays a passing result that your new dependency set never produced.
Remote caching has a similar risk. If you leave out an environment factor, such as an interpreter minor version or a system library, a hash computed on one machine can match a result produced on a different machine, and Nx will replay it.
Tests that touch the network, a database, or shared state should usually have caching disabled. Their outcome depends on things outside the hash, so a cached pass only shows that the external system worked at some earlier point.
{
"name": "billing-core",
"namedInputs": {
"pySource": [
"{projectRoot}/src/**/*.py",
"{projectRoot}/tests/**/*.py",
"{projectRoot}/pyproject.toml",
"{workspaceRoot}/uv.lock",
"!{projectRoot}/**/__pycache__/**",
"!{projectRoot}/.pytest_cache/**",
"!{projectRoot}/.mypy_cache/**",
"!{projectRoot}/.ruff_cache/**",
"!{projectRoot}/.venv/**"
],
"pyEnv": [
{ "runtime": "uv run --no-sync python -c \"import sys, platform; print(sys.version, platform.system(), platform.machine())\"" },
{ "env": "PYTHONHASHSEED" },
{ "env": "BILLING_FEATURE_FLAGS" }
]
},
"targets": {
"build": {
"executor": "nx:run-commands",
"options": { "command": "uv build", "cwd": "{projectRoot}" },
"inputs": ["pySource", "pyEnv"],
"outputs": ["{projectRoot}/dist"],
"cache": true
},
"test": {
"executor": "nx:run-commands",
"options": { "command": "uv run pytest tests/unit --cov=src --cov-report=html:coverage", "cwd": "{projectRoot}" },
"inputs": ["pySource", "pyEnv"],
"outputs": ["{projectRoot}/coverage"],
"cache": true
},
"integration-test": {
"executor": "nx:run-commands",
"options": { "command": "uv run pytest tests/integration", "cwd": "{projectRoot}" },
"cache": false
}
}
}
A project.json that hashes sources, pyproject.toml, uv.lock, interpreter version, OS/arch and env vars, excludes tool caches and .venv, caches only dist and coverage, and disables caching for integration tests.
How do affected tests work in CI for Python and cross-language projects?
In CI, run nx affected -t test --base=origin/main --head=HEAD. Nx diffs the two refs, maps changed files to projects, then walks the graph outward to find every dependent. Edit libs/pricing, and each service declaring it as a workspace dependency is retested along with the library itself.
The graph only knows the edges it has been given. If services/billing imports pricing but the dependency was never declared in pyproject.toml or as an implicit dependency, billing's tests are skipped. Nothing fails or warns. The pipeline shows green because the test that would have caught the regression never ran.
Cross-language edges need the same care. Give the API service an openapi target that exports its schema. Then make the TypeScript client's generate target depend on it with dependsOn pointing at the API project's openapi target, and add the API as an implicit dependency of the client. When a backend change alters the schema, the client is marked affected and gets regenerated and type-checked in the same run.
For installs, use uv sync --locked, or --frozen if you have a separate lockfile check. If uv.lock has drifted from pyproject.toml, CI fails instead of quietly re-resolving. Persist uv's cache directory (UV_CACHE_DIR) under a key derived from uv.lock, and keep it separate from Nx's task cache. The two are invalidated by different things.
Illustrative estimate. Assume 12 Python projects, a full test run of 20 minutes, and a typical PR that affects 3 projects. That PR's test run takes about 5 minutes, which saves roughly 15 minutes. These numbers are assumed, not measured.
What does the day-to-day developer workflow look like?
Run uv sync once at the repository root. Because every Python service is a workspace member, this resolves one lockfile and builds one shared virtual environment. Nobody has to keep per-service environments in sync, and an incompatible pin between two services fails at resolution time instead of at runtime.
For tests, there are two entry points. nx test billing runs the target with caching and builds any upstream targets first. It is also the same command CI runs, so use it before pushing. Running uv run pytest inside the service directory skips the Nx daemon and graph computation. That makes it the better fit for a tight edit-test loop where you pass pytest flags and want results in seconds. Both use the same environment, so their results should not diverge.
Adding a member takes three steps:
- Workspace membership. Make sure the new directory matches the
membersglobs in the rootpyproject.toml. Declare dependencies on sibling packages with workspace sources so uv resolves them locally. project.json. Give the project a unique name and define its targets.- Graph edges. If a plugin infers edges from
pyproject.toml, it handles this. Otherwise, addimplicitDependenciestoproject.json. Runnx graphto confirm the edges appear before you open the PR.
The ongoing cost is two mental models. uv answers "what is installed," and Nx answers "what runs and what is affected." A missing edge produces no error. It produces affected runs that silently skip tests. Nx also requires Node.js and a JavaScript package install, which Python-only contributors may not expect. Document this in onboarding, pin the Node version in the repo, or provide a dev container that already includes both toolchains.
When should you avoid Nx for Python, and what are the alternatives?
Nx earns its place when the graph is large and mixed-language. Outside that, the costs show up first.
Small Python-only repos. With a handful of packages, running the full suite is cheap and the project graph adds little. Every command now goes through Node and a plugin layer, so contributors have one more tool to debug when a target misbehaves.
Services that need conflicting dependency versions. A uv workspace resolves every member against one shared lockfile. If one service must stay on an older major version of a library that another service has moved past, the workspace cannot satisfy both. Splitting them into separate workspaces resolves the conflict, but it also weakens what Nx can infer about the edges between them.
Teams that cannot maintain a graph plugin. Inferred dependency edges rely on code that parses pyproject.toml files. When nobody owns that code, packaging changes break it without any error, and affected detection starts skipping projects it should run.
| Approach | Setup cost | Affected detection correctness | Caching | Maintenance burden |
|---|---|---|---|---|
| Plain uv + CI path filters | Low | Coarse; misses transitive edges unless filters list them | Only what CI provides | Path filters drift as packages move |
| Multiple separate uv workspaces | Low to medium | Accurate within each workspace, none across them | Per-workspace, via CI | Duplicate tooling and lockfile updates |
Nx with hand-maintained implicitDependencies |
Medium | Correct only while the list stays current | Full Nx caching | Manual edits on every new internal dependency |
Choose path filters for small Python-only repos. Split into separate workspaces when dependency versions conflict. Use hand-maintained implicit dependencies when you need Nx caching but have no one to own a plugin.
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 python 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
.envby 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.