We are going to design a monorepo build system that emphasizes remote caching, sandboxing, and hermeticity.
The goal is to have reproducible builds that can be cached remotely and run in a sandboxed environment to avoid any host system dependencies.
Steps:
-
Choose a build system that supports remote caching and hermetic builds by design. We'll use Nx because it has built-in support for remote caching and can be configured for hermetic builds.
-
Set up a monorepo with Nx. We can use create-nx-workspace to initialize.
-
Configure remote caching. We'll use Nx Cloud for remote caching. Alternatively, we can set up our own remote cache with a service like AWS S3, but for simplicity and integration, Nx Cloud is recommended.
-
Ensure hermeticity by:
- Using Docker or a similar containerization tool to run the build in a sandboxed environment with all dependencies included.
- Using exact versions of all tools (Node.js, npm/yarn, etc.) and ensuring that the build does not depend on any globally installed tools.
-
Configure the build to use the remote cache even when running in the sandbox.
-
Optionally, set up a CI/CD pipeline that uses the same sandboxed environment and remote cache.
Let's break down the steps:
Step 1: Create Nx workspace
npx create-nx-workspace@latest my-monorepo --preset=ts
This creates a TypeScript monorepo.
Step 2: Install and configure Nx Cloud for remote caching.
In the workspace, run:
npx nx connect-to-nx-cloud
This will set up Nx Cloud and configure the nx.json for distributed caching.
Step 3: Configure hermetic builds.
We want to run the build inside a Docker container. We'll create a Dockerfile that installs the exact Node version and any other dependencies.
However, note that Nx Cloud's distributed caching works by hashing the inputs (source code, configs, environment variables, etc.) and the command. So we need to make sure that the same hash is produced regardless of the environment.
To achieve hermeticity, we need to:
a) Use a fixed Node.js version. We can use engines field in package.json and also use a Docker base image with that exact Node version.
b) Use package locks (package-lock.json or yarn.lock) and ensure that we use the same package manager and version.
c) Avoid any environment-specific configurations. Use environment variables only if they are part of the hash? Actually, Nx by default includes environment variables in the hash? We need to check.
According to Nx documentation:
- By default, Nx does not include environment variables in the cache hash. But you can configure it.
We want to be hermetic, so we should set the environment variables to fixed values in the build environment.
d) Use a sandboxed environment (Docker) that has the same filesystem layout and same tools.
Example Dockerfile:
FROM node:18-alpine
WORKDIR /app
COPY . .
RUN npm ci
# Then run the build command, but we want to also use the remote cache.
# We can set the NX_CLOUD_* environment variables for authentication?
# Alternatively, we can use an Nx Cloud token.
# But note: the remote cache is keyed by the hash. The hash must be the same as when we run locally or in CI.
# We need to make sure that the Docker build context includes everything that is needed for the hash.
# Actually, we don't want to run the build during the Docker build, because we want to use the remote cache when we run the container.
# Instead, we will build the Docker image and then run the build inside the container, using the remote cache.
# Alternatively, we can have the Dockerfile just set up the environment and then run the build command when the container is run.
# Let's change the approach:
We'll create a Docker image that has all the dependencies (Node, npm, etc.) and then when we run the container, we mount the source code and run the build.
But then the source code is not in the image, so the hash will be based on the mounted source. That's okay because the source is the same.
However, the Docker image itself is part of the environment? We want the build to be independent of the Docker image? Actually, the Docker image is the environment.
We want the build to be hermetic, meaning that if we run the same build with the same source code, we get the same output.
But if we change the Docker image (even if the source is the same) then the build might be different because the tools are different.
So we must fix the Docker image version. We'll tag our Docker image with a version that corresponds to the Node version and other tool versions.
Then, when we run the build, we use that specific Docker image.
But note: the hash computed by Nx does not include the Docker image version. So if we run the same source code with two different Docker images, we might get the same hash but different outputs.
Therefore, we must include the Docker image version (or the versions of all tools) in the hash.
How to do that?
We can set an environment variable that includes the Docker image version (or a hash of the Dockerfile and its base image) and include that environment variable in the Nx hash.
Nx allows you to set `cacheableOperations` and also to set `namedInputs` and `environment` variables that are included in the hash.
Alternatively, we can set a fixed environment variable in the Docker image and then configure Nx to include that environment variable in the hash.
Steps:
- In the Dockerfile, set an environment variable, e.g., `DOCKER_IMAGE_VERSION` to the version of the Docker image (or the base image version and the Dockerfile content hash).
- In `nx.json`, set:
"namedInputs": {
"production": [
"default",
"{workspaceRoot}/Dockerfile",
"{workspaceRoot}/.dockerignore"
],
"environment": [
"DOCKER_IMAGE_VERSION"
]
}
But note: the Dockerfile might change and we want to invalidate the cache if the Dockerfile changes? Actually, the Dockerfile is not used in the build step inside the container? Wait, the Dockerfile is used to build the image, but the build step inside the container does not use the Dockerfile. So if we change the Dockerfile and rebuild the image, then the image version changes and we want the build cache to be invalid.
However, the build step inside the container doesn't see the Dockerfile unless we mount it. We are going to mount the source code, but not necessarily the Dockerfile.
So we have two options:
1. Include the Dockerfile in the source code that is mounted? Then it will be part of the source hash.
2. Or, set an environment variable in the Docker image that represents the image version, and then include that environment variable in the Nx hash.
Option 2 seems better because we don't want to change the source code just to update the Docker image.
But how do we set the environment variable in the Docker image to reflect the Dockerfile and base image?
We can compute a hash of the Dockerfile and the base image tag and set that as the environment variable when building the Docker image.
Then, when we run the container, that environment variable is set and Nx will include it in the hash.
However, note that the environment variable must be set in the build environment (inside the container) and Nx must be configured to include it.
Alternatively, we can set the environment variable when running the container and then pass it to Nx.
But Nx by default does not include environment variables in the hash. We have to explicitly include them.
We can set in `nx.json`:
"targetDefaults": {
"build": {
"cache": true,
"dependsOn": ["^build"],
"inputs": [
"production",
"environment"
]
}
}
And then define the "environment" namedInput to include the environment variable we care about.
But note: the environment variable must be set in the environment where Nx runs (inside the container). So we set it in the Dockerfile or when running the container.
Let's do:
Dockerfile:
FROM node:18-alpine
ARG DOCKER_IMAGE_VERSION
ENV DOCKER_IMAGE_VERSION=${DOCKER_IMAGE_VERSION}
WORKDIR /app
COPY . .
RUN npm ci
CMD ["sh", "-c", "nx run-many --target=build --all"]
Then when building the Docker image, we pass the build arg:
docker build --build-arg DOCKER_IMAGE_VERSION=$(git rev-parse HEAD) -t my-monorepo:latest .
But note: the Docker image version might not change with every source code change? We want to invalidate the cache when the Docker image changes, but not necessarily when the source code changes (because source code change will already invalidate). Actually, if the Docker image changes, we want to rebuild because the tools might be different. But if the source code changes, we also want to rebuild. So we want to include both.
However, the source code is already included in the hash. The DOCKER_IMAGE_VERSION is an additional check.
But wait: if we change the Dockerfile and rebuild the image, then the DOCKER_IMAGE_VERSION changes, and then the hash changes, so we rebuild. But note that the source code might be the same, but the tools are different, so we must rebuild.
This seems correct.
However, there is a chicken and egg problem: the Docker image version is set at build time of the Docker image, but we want to run the build inside the container and use the remote cache. The remote cache key (hash) must be the same as when we ran without the container? Actually, we are changing the environment, so the hash should be different.
But we want to be able to use the same remote cache for builds run in different environments? Not necessarily. We want hermetic builds, so if the environment (Docker image) is different, we should not use the same cache.
So including the DOCKER_IMAGE_VERSION in the hash is correct.
But note: when we run the build in the container, the source code is mounted from the host. The host source code is the same as when we run without the container? Yes, but without the container we might be using a different Node version. So we want to use a different cache.
Therefore, we must have two different caches: one for the host environment and one for the container environment? Or we can just have one cache that includes the environment.
Since we are including the DOCKER_IMAGE_VERSION in the hash, the cache entries will be separate.
Step 4: Configure Nx to include the environment variable.
In `nx.json`:
{
...
"namedInputs": {
"production": [
"default",
"{workspaceRoot}/Dockerfile",
"{workspaceRoot}/.dockerignore"
],
"environment": [
"DOCKER_IMAGE_VERSION"
]
},
"targetDefaults": {
"build": {
"cache": true,
"inputs": [
"production",
"environment"
]
}
}
}
But note: the `default` namedInput already includes the source code, configuration files, etc.
Step 5: CI/CD integration.
In CI, we can build the Docker image and then run the build inside the container. We must pass the same DOCKER_IMAGE_VERSION that we used when building the image? Actually, we set it in the Dockerfile at build time, so when we run the container, it's set.
But note: the DOCKER_IMAGE_VERSION must be the same for the same Docker image. So we should tag the Docker image with a version and set the DOCKER_IMAGE_VERSION to that tag.
Alternatively, we can set the DOCKER_IMAGE_VERSION to the Docker image ID or the git commit that produced the Dockerfile? But we are building the Docker image from the Dockerfile, so we can set the build arg to the git commit of the Dockerfile? Or the Dockerfile itself?
Actually, we want the DOCKER_IMAGE_VERSION to change if the Dockerfile or the base image changes. We can compute a hash of the Dockerfile and the base image tag and use that.
But for simplicity, we can use the Docker image tag as the version. Then we set the build arg to the same tag.
Then, when we run the container, we set the environment variable to the same tag? Actually, we set it in the Dockerfile at build time, so it's baked into the image.
So when we run the container, the environment variable is set to the tag we used when building.
Then, when we run the build inside the container, Nx will use that environment variable as part of the hash.
Step 6: Local development.
We don't want to run the build in a container locally? We can, but it's heavy. We can run the build locally and use the same remote cache? But then the environment is different (local Node version vs container Node version). So the cache would be separate because the DOCKER_IMAGE_VERSION would be different? Actually, locally we don't set DOCKER_IMAGE_VERSION? Then Nx will not include it? But we configured Nx to include the environment variable. If it's not set, then it's included as undefined? That would be a different hash than when it's set.
So we have to set DOCKER_IMAGE_VERSION even when building locally? But we don't have a Docker image locally? We can set it to a fixed string for local, e.g., "local". Then when we run in the container, it's set to the Docker image tag.
But then the cache would be separate between local and container.
Alternatively, we can avoid using the container locally and just rely on the host environment. Then we don't set DOCKER_IMAGE_VERSION and we don't include it in the hash? But we want the same cache to be used in CI and locally? Not necessarily, because the environments are different.
Actually, we want the builds to be hermetic, so we should use the same environment everywhere. That means we should use the Docker container even locally.
But for speed, we might not want to. So we have two options:
Option A: Use the same environment (Docker) everywhere. Then we set DOCKER_IMAGE_VERSION to the same value in both local and CI (the Docker image tag). Then we can share the cache.
Option B: Use different environments and have separate caches.
Since we are aiming for hermeticity, we should use the same environment. So we should use the Docker container even locally.
However, for development, we might want to run the build without the container for speed. Then we break hermeticity? Not necessarily, if we use the exact same Node version and tools as in the container. We can use `nvm` to switch to the same Node version and use the same package manager version.
But then we are not sandboxed. So we might have other differences (like global packages, OS, etc.).
Given the requirement for sandboxing and hermeticity, we should use the container for all builds.
Step 7: Summary.
- Create Nx workspace.
- Set up Nx Cloud for remote caching.
- Create a Dockerfile that sets an environment variable DOCKER_IMAGE_VERSION (passed as build arg) and installs dependencies.
- Configure Nx to include the DOCKER_IMAGE_VERSION in the cache hash.
- Build the Docker image with a tag and set the build arg to that tag.
- Run the build inside the container, which will use the remote cache (via Nx Cloud) and include the DOCKER_IMAGE_VERSION in the hash.
This way, if we change the Docker image (by changing the Dockerfile or base image) we get a new hash and rebuild. If we change the source code, we also get a new hash and rebuild (and if the same build has been done before with the same Docker image and same source, we get a cache hit from remote).
Step 8: Implementation.
Let's write the necessary files:
a) `Dockerfile`:
ARG DOCKER_IMAGE_VERSION
ENV DOCKER_IMAGE_VERSION=${DOCKER_IMAGE_VERSION}
FROM node:18-alpine
WORKDIR /app
COPY . .
RUN npm ci
CMD ["sh", "-c", "nx run-many --target=build --all"]
But note: we are copying the entire source code in the Docker build. That means the Docker image includes the source code? We don't want that because we want to mount the source code at runtime (for development and CI to have the latest source). So we should not copy the source code in the Dockerfile? Then how do we run the build? We copy the package.json and package-lock.json first to install dependencies, then copy the rest? But then the source code is in the image.
Actually, we want to build the Docker image with the dependencies, but not the source code? Because the source code changes and we don't want to rebuild the image every time.
So we change the Dockerfile:
ARG DOCKER_IMAGE_VERSION
ENV DOCKER_IMAGE_VERSION=${DOCKER_IMAGE_VERSION}
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
We don't copy the source code here.
CMD ["sh", "-c", "nx run-many --target=build --all"]
Then, when we run the container, we mount the source code:
docker run -v $(pwd):/app my-monorepo:latest
But then the node_modules is inside the container and we are overwriting the /app with the host source code? That's okay because we installed the dependencies in the image, and the source code is mounted on top. The node_modules is still there because it's in the image and not overwritten by the mount (unless the host has a node_modules? We should make sure the host doesn't have a node_modules, or we can ignore it).
But note: the build might write to node_modules? No, it shouldn't. So it's safe.
However, the Docker image must be built with the same package-lock.json as the host. So we must copy the package-lock.json in the Docker build. Then when we run the container, the host package-lock.json is mounted and it should be the same? Actually, we are mounting the entire host directory, so the package-lock.json from the host will be used? But we already installed with the package-lock.json that was in the image. If the host package-lock.json is different, then we have a problem.
So we must ensure that the host package-lock.json is the same as the one in the image. We do that by building the Docker image from the same source code that we are going to mount? But then we are copying the package-lock.json at build time, and then at run time we are mounting the host's package-lock.json. They must be the same.
How to enforce that? We can build the Docker image from the same commit that we are going to run? Then the package-lock.json in the image and the mounted one are the same.
But in CI, we build the Docker image from the current commit and then run the build in the container with the same source code (the same commit). So it's the same.
In local development, we build the Docker image from the current code and then run the container with the current code. So it's the same.
So it should be okay.
But note: if we change the package.json and package-lock.json, we must rebuild the Docker image. So we should include the package.json and package-lock.json in the Docker build context and copy them. Then when they change, the Docker image rebuilds.
Alternatively, we can rebuild the Docker image every time we run the build? That would be slow.
So we want to rebuild the Docker image only when the package.json or package-lock.json changes? But also when the base image changes? The base image is in the Dockerfile.
We can use multi-stage builds? Not necessary.
We'll stick to:
- Build the Docker image when the package.json, package-lock.json, or Dockerfile changes.
Then, when we run the container, we mount the source code (which includes the same package.json and package-lock.json) and run the build.
But note: the node_modules in the image was built from the package-lock.json that was in the image at build time. If the host package-lock.json is different (but we said it's the same because we built from the same commit) then it's okay.
However, if we rebuild the Docker image with a new package-lock.json, then the node_modules in the image is updated, and then we run the build with the same package-lock.json (mounted) and it matches.
So it's consistent.
Step 9: CI/CD pipeline.
In CI, we:
- Checkout the code.
- Build the Docker image with the current commit's package-lock.json and Dockerfile, and set the DOCKER_IMAGE_VERSION to the commit SHA or the Docker image tag.
- Run the container, mounting the current source code, and run the build.
The build will use the remote cache (Nx Cloud) and the cache key will include the DOCKER_IMAGE_VERSION (the commit SHA) and the source code (which is the same commit) and the environment (Node version, etc. from the Docker image).
Step 10: Local development.
We can build the Docker image locally and run the container. But for speed, we might want to run the build without the container locally? Then we break hermeticity.
Alternatively, we can use the same Docker image locally and run the build in the container. Then we have the same environment.
But for development, we might want to run the build in the container and then also run the app in the container? That's a different topic.
Given the requirement for hermeticity, we should run the build in the container even locally.
However, we can also set up a script that builds the Docker image if needed (when package.json or Dockerfile changes) and then runs the build in the container.
We can use `docker-compose` or just a shell script.
Let's create a `build.sh`:
#!/bin/bash
Build the Docker image if needed? We can always build with the same tag, which will reuse the cache if nothing changed.
docker build -t my-monorepo:latest --build-arg DOCKER_IMAGE_VERSION=$(git rev-parse HEAD) .
Run the build in the container
docker run -v $(pwd):/app my-monorepo:latest
But note: the Docker image tag is `latest`, but we are setting the DOCKER_IMAGE_VERSION to the current commit. That's okay because the environment variable is set inside the image.
However, if we build the same Dockerfile with the same build arg, we get the same image? Not necessarily because the source code in the image (the package.json and package-lock.json) are from the build context at build time. But we are building from the current commit, so the package.json and package-lock.json are the same as the mounted ones? Yes, because we are in the same commit.
But what if we build the Docker image from a different commit? Then the package.json and package-lock.json might be different, and then the node_modules in the image is different. Then when we run the container with the current source code (which might be a different commit) we have a mismatch.
So we must build the Docker image from the same commit that we are going to run.
Therefore, in the script above, we are building from the current commit and then running with the current commit. That's consistent.
But note: the Docker image is built with the package.json and package-lock.json from the current commit, and then we run the build in the container with the same commit (mounted). So it's consistent.
However, if we change the source code (but not package.json) and then run the build without rebuilding the Docker image, then the node_modules in the image is still the same (because it was built with the same package.json) and the source code is updated. That's okay.
But if we change the package.json, we must rebuild the Docker image. Our script always rebuilds the Docker image? It does, but Docker will use the cache if the Dockerfile and the package.json haven't changed. But note: the build arg DOCKER_IMAGE_VERSION changes with every commit (because it's the git commit). So the Docker image will be different for every commit? That's not what we want. We want the Docker image to be the same if the package.json and Dockerfile are the same, regardless of the commit? Actually, the DOCKER_IMAGE_VERSION is set to the commit, so even if the package.json is the same, the image will be different because the build arg is different.
That's a problem because we want to reuse the Docker image if the package.json and Dockerfile are the same.
So we should set the DOCKER_IMAGE_VERSION to something that represents the package.json and Dockerfile? Or we can set it to the Docker image tag that we use (like a version number) and then use that same tag for the same package.json and Dockerfile.
Alternatively, we can not set the DOCKER_IMAGE_VERSION from the git commit, but from a hash of the package.json and Dockerfile? But then we have to compute that hash.
Let's change:
We want the DOCKER_IMAGE_VERSION to be the same for the same package.json and Dockerfile? But then if we change the source code (but not package.json) we want the same Docker image? Yes, because the tools are the same.
So we should set the DOCKER_IMAGE_VERSION to a hash of the package.json and package-lock.json and Dockerfile? That would be ideal.
But then we have to compute that hash and pass it as a build arg.
Alternatively, we can use the Docker image tag as the version, and we tag the Docker image with a hash of the package.json and Dockerfile? Then we set the DOCKER_IMAGE_VERSION to that tag.
But then we have to compute the tag and pass it as a build arg.
This is getting complex.
Alternatively, we can not use the DOCKER_IMAGE_VERSION at all and instead include the Dockerfile and the package.json in the Nx hash? We already have the Dockerfile in the `production` namedInput? But note: the Dockerfile is not used when running the build inside the container. The build inside the container uses the Node version and tools from the image, but the Dockerfile itself is not used.
So we want to include the versions of the tools (Node, npm, etc.) in the hash. We can get the Node version from the image? But the image is built from the Dockerfile, so the Dockerfile determines the Node version.
So we can include the Dockerfile in the hash. Then if the Dockerfile changes, the hash changes.
But what about the base image? The base image is in the Dockerfile. So if we change the base image tag (e.g., node:18-alpine to node:20-alpine) then the Dockerfile changes, so it's included.
So maybe we don't need the DOCKER_IMAGE_VERSION? We can just include the Dockerfile in the hash.
But wait: the Dockerfile is not used in the build step inside the container. The build step uses the Node version from the image. The image was built from the Dockerfile. So if we change the Dockerfile and rebuild the image, then the Node version in the image changes. But the Dockerfile is not present in the container at build time? We are not mounting the Dockerfile. So the build step inside the container does not see the Dockerfile.
Therefore, we must include the Dockerfile in the hash by making it part of the source code that is mounted? Or by setting an environment variable that represents the Dockerfile content.
We can copy the Dockerfile into the container and then include it in the Nx hash? But then we are changing the source code (by copying the Dockerfile) and that would be part of the `default` namedInput? Not necessarily, because the `default` namedInput by default includes all files in the repo? We can adjust.
Alternatively, we can set an environment variable in the container that is the hash of the Dockerfile and the base image? But we don't have the base image tag inside the container? We can set it at build time.
Given the complexity, let's simplify:
We want to include the toolchain (Node version, npm version, etc.) in the hash. We can get the Node version by running `node --version` and the npm version by `npm --version`. We can set these as environment variables and include them in the Nx hash.
But then we have to set these environment variables in the container and include them in the Nx configuration.
Alternatively, we can use the Nx feature to include the output of a command in the hash? Not directly.
Another idea: we can create a file in the container that contains the toolchain versions and include that file in the hash.
Steps:
- In the Dockerfile, after installing Node, create a file `toolchain.json` with:
{
"node": "$(node --version)",
"npm": "$(npm --version)"
}
- Then include this file in the Nx hash by adding it to the `production` namedInput.
But note: the `toolchain.json` is created at image build time and is inside the image. We are not mounting it from the host. So when we run the container, the `toolchain.json` is there and Nx will see it and include it in the hash.
Then, if the Node version changes (by changing the base image in the Dockerfile) then the `toolchain.json` changes, so the hash changes.
Also, if we change the Dockerfile and rebuild the image, then the `toolchain.json` might change (if the base image changes) and also the node_modules might change (if the package.json changes). But we are already including the package.json and package-lock.json in the `default` namedInput.
So we can remove the DOCKER_IMAGE_VERSION and instead include the `toolchain.json` in the `production` namedInput.
Let's change:
Dockerfile:
FROM node:18-alpine
WORKDIR /app
Create toolchain.json
RUN node --version > toolchain.json && npm --version >> toolchain.json
COPY package*.json ./
RUN npm ci
CMD ["sh", "-c", "nx run-many --target=build --all"]
Then, in `nx.json`:
"namedInputs": {
"production": [
"default",
"{workspaceRoot}/toolchain.json",
"{workspaceRoot}/Dockerfile",
"{workspaceRoot}/.dockerignore"
]
}
But note: the `toolchain.json` is in the container at `/app/toolchain.json`. But the Nx workspace root is also `/app`. So the path is correct.
However, the `toolchain.json` is generated in the Docker image and then we run the container with the source code mounted. The `toolchain.json` in the image will be overwritten by the host's `toolchain.json` if the host has one? We don't want that.
We don't have a `toolchain.json` in the host source code. So when we mount the host source code, the `toolchain.json` from the host (if exists) will overwrite the one in the image? We don't want that.
So we should not generate the `toolchain.json` in the working directory? We can generate it in a different directory and then set Nx to look for it there? Or we can generate it and then copy it to a safe location? But then we have to adjust the path in `nx.json`.
Alternatively, we can generate the `toolchain.json` and then not copy the source code until after? Actually, we are copying package.json and then running npm ci, then we generate toolchain.json? But then when we mount the source code, the toolchain.json from the host (if any) will overwrite.
So we must not mount over the toolchain.json. We can generate it in a different directory and then set the Nx namedInput to that path.
Let's change:
Dockerfile:
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
Generate toolchain.json in a directory that won't be overwritten by the mount?
We are going to mount the entire /app from the host. So any file in the image in /app will be overwritten by the host's file if it exists.
So we should generate the toolchain.json in a directory that is not mounted? But we are mounting the entire /app.
Alternatively, we can generate the toolchain.json and then copy it to a safe location? But then we have to adjust the Nx configuration to read from that safe location.
Or we can generate the toolchain.json and then when we run the container, we don't mount over it? We can mount the source code but exclude toolchain.json? But that's complex.
Another idea: we can set an environment variable with the toolchain versions and include that environment variable in the Nx hash.
Let's go back to the environment variable approach.
We set an environment variable in the Dockerfile with the toolchain versions, and then include that environment variable in the Nx hash.
Dockerfile:
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
ENV TOOLCHAIN_VERSION="node:$(node --version) npm:$(npm --version)"
CMD ["sh", "-c", "nx run-many --target=build --all"]
Then in nx.json:
"namedInputs": {
"production": [
"default",
"{workspaceRoot}/Dockerfile",
"{workspaceRoot}/.dockerignore"
],
"environment": [
"TOOLCHAIN_VERSION"
]
}
And then set the target to use both production and environment:
"targetDefaults": {
"build": {
"cache": true,
"inputs": [
"production",
"environment"
]
}
}
Now, the hash will include the TOOLCHAIN_VERSION environment variable.
But note: the environment variable is set in the Docker image and will be present when we run the container.
However, if we run the build locally (without the container) we don't have the TOOLCHAIN_VERSION set? Then it will be undefined. So the hash will be different.
We want to set the TOOLCHAIN_VERSION even when building locally? We can set it in our shell profile? Or we can have a script that sets it.
But for hermeticity, we should use the same environment everywhere. So we should set the TOOLCHAIN_VERSION to the same value as in the Docker image.
How to get the same value locally? We can run the same command to get the Node and npm versions and set TOOLCHAIN_VERSION.
But then we are not using the Docker image locally? We are using the host's Node and npm. So the versions might be different.
So we should use the Docker container for all builds.
Therefore, we don't need to worry about local without container.
Step 11: Final configuration.
We have:
-
Dockerfile:
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
ENV TOOLCHAIN_VERSION="node:$(node --version) npm:$(npm --version)"
CMD ["sh", "-c", "nx run-many --target=build --all"]
-
nx.json:
{
...,
"namedInputs": {
"production": [
"default",
"{workspaceRoot}/Dockerfile",
"{workspaceRoot}/.dockerignore"
],
"environment": [
"TOOLCHAIN_VERSION"
]
},
"targetDefaults": {
"build": {
"cache": true,
"inputs": [
"production",
"environment"
]
}
}
}
-
We also need to make sure that the default namedInput includes everything we need for the build. By default, default includes all source files, but we might want to exclude some (like node_modules, dist, etc.). We can adjust the default namedInput if needed.
Step 12: Remote caching with Nx Cloud.
We already ran npx nx connect-to-nx-cloud which set up the nx.json with the cloud configuration and set the cache property for targets.
But note: the inputs we set in targetDefaults will be used for the cache hash. So we are good.
Step 13: CI/CD.
In CI, we:
- Checkout the code.
- Build the Docker image with the current commit's package.json and package-lock.json, and set the TOOLCHAIN_VERSION environment variable in the image (it's set in the Dockerfile automatically).
- Run the container with the source code mounted and run the build.
The build will use the remote cache and the cache key will include the TOOLCHAIN_VERSION and the source code (and Dockerfile, etc.).
Step 14: Local development with the container.
We can run:
docker build -t my-monorepo:latest .
docker run -v $(pwd):/app my-monorepo:latest
But note: the Docker image is built with the current package.json and package-lock.json, and then we run with the current source code. So it's consistent.
However, if we change the source code (but not package.json) we don't need to rebuild the Docker image? Actually, the Docker image includes the node_modules from the package.json at build time. So if we change the source code, the node_modules is still the same (unless we change the package.json). So we don't need to rebuild the Docker image.
But if we change the package.json, we must rebuild the Docker image because the node_modules must be updated.
So we can have a script that checks if the package.json or Dockerfile changed and rebuilds the Docker image, otherwise just run the container.
But for simplicity, we can rebuild every time? That might be slow.
Alternatively, we can use a volume for node_modules? But then we are not using the node_modules from the image? We want to use the node_modules from the image because it was built with the image's Node version.
So we don't want to use a volume for node_modules.
Therefore, we rebuild the Docker image only when package.json or Dockerfile changes.
We can use a script that checks the hash of package.json and Dockerfile and only rebuilds if they changed? Or we can rely on Docker's build cache? Docker will not re-run the npm ci if the package.json and package-lock.json haven't changed? Actually, Docker uses the build cache based on the instructions and the files that are copied. So if the package.json and package-lock.json are the same, then the RUN npm ci step will be cached.
So we can run docker build every time and it will be fast if the package.json and package-lock.json haven't changed.
But note: the TOOLCHAIN_VERSION is set in the Dockerfile and it changes with every build? No, it's set by the node --version and npm --version which are from the base image. So if the base image is the same, then the TOOLCHAIN_VERSION is the same. So the Docker image will be the same if the base image and the package.json are the same.
But we are setting the TOOLCHAIN_VERSION at build time, and it's the same every time for the same base image? Yes.
So we can run docker build every time and it will use the cache if nothing changed.
Then we run the container.
Step 15: Conclusion.
This setup gives us:
- Remote caching via Nx Cloud.
- Sandboxing via Docker.
- Hermeticity by including the toolchain versions (via TOOLCHAIN_VERSION) in the cache hash and using a fixed base image.
We can now write the files and document the process.
However, note that the default namedInput includes the Dockerfile and .dockerignore? We added them to production? Actually, we added them to production and then the build target uses production and environment. So the Dockerfile and .dockerignore are included in the hash.
But note: the Dockerfile is used to build the image, but once the image is built, the build inside the container does not use the Dockerfile. So why include it? Because if the Dockerfile changes, we want to rebuild the Docker image, and then the TOOLCHAIN_VERSION might change? Actually, the TOOLCHAIN_VERSION is set by the base image, so if we change the Dockerfile to use a different base image, then the TOOLCHAIN_VERSION changes. But we are already including TOOLCHAIN_VERSION in the hash. So we don't need to include the Dockerfile? But we want to rebuild the Docker image when the Dockerfile changes, even if the base image is the same? For example, if we change the working directory or the command? That shouldn't affect the build output. So maybe we don't need to include the Dockerfile.
But we want to rebuild the Docker image when the Dockerfile changes? Actually, the Docker image is built separately and then we run the container. The build inside the container does not depend on the Dockerfile. So we don't need to include the Dockerfile in the Nx hash.
However, we are building the Docker image and then running the container. The Docker image must be rebuilt when the Dockerfile changes. But that is a separate step.
So in the Nx hash, we don't need the Dockerfile. We only need the TOOLCHAIN_VERSION (which is set in the image) and the source code.
But wait: the TOOLCHAIN_VERSION is set in the Dockerfile and baked into the image. So if we change the Dockerfile but not the base image, the TOOLCHAIN_VERSION might be the same? Then the hash would be the same? But we changed the Dockerfile, so we want to rebuild the Docker image? But the build inside the container doesn't care about the Dockerfile. So we don't need to rebuild the container build? Actually, the Docker image is the environment. If we change the Dockerfile (for example, change the working directory) but the Node version and the installed dependencies are the same, then the build inside the container should be the same.
So we don't need to include the Dockerfile in the Nx hash.
Therefore, we can remove the Dockerfile and .dockerignore from the production namedInput.
Let's adjust:
"namedInputs": {
"production": [
"default"
],
"environment": [
"TOOLCHAIN_VERSION"
]
}
But then we are not including the Dockerfile in the hash, which is fine.
However, we are including the default which by default includes all files in the repo except those in .nxignore? We might want to exclude the Dockerfile and .dockerignore from the default because they are not used in the build? Actually, they are not used in the build inside the container. But they are in the source code that is mounted? They are in the host source code, but the build inside the container doesn't use them. So we can exclude them from the default namedInput.
We can adjust the default namedInput to exclude the Dockerfile and .dockerignore? But then if we change the Dockerfile, it won't affect the hash, which is what we want.
Alternatively, we can leave them in because they are part of the source code and if we change them, we might want to rebuild? Actually, the build inside the container doesn't use them, so changing them should not affect the build output. So we can exclude them.
But note: the default namedInput by default includes all files. We can change it to:
"default": [
"!{workspaceRoot}/Dockerfile",
"!{workspaceRoot}/.dockerignore"
]
But then we have to list all the files we want to include? That's not practical.
Alternatively, we can use the exclude option in the default namedInput? Actually, the default namedInput is a list of glob patterns. We can exclude by prefixing with !.
But by default, default is defined as:
"default": [
"**/*"
]
We can change it to:
"default": [
"**/*",
"!{workspaceRoot}/Dockerfile",
"!{workspaceRoot}/.dockerignore"
]
But then we are including everything except these two files.
However, we also might want to exclude node_modules, dist, etc. The default default namedInput already excludes node_modules and dist? Actually, the default default is:
"default": [
"/*",
"!/node_modules/",
"!/dist/**"
]
So we can add our exclusions.
But note: the default namedInput is used by all targets that don't specify their own inputs. We are setting build to use production which uses default. So we are good.
Let's change the default to exclude Dockerfile and .dockerignore.
Alternatively, we can create a new namedInput for the source code that excludes these files and use that in production.
But let's keep it simple and adjust the default:
"namedInputs": {
"default": [
"/*",
"!/node_modules/",
"!/dist/**",
"!{workspaceRoot}/Dockerfile",
"!{workspaceRoot}/.dockerignore"
],
"environment": [
"TOOLCHAIN_VERSION"
]
}
And then production uses default? Actually, we defined production as ["default", ...] but then we changed our mind. Let's remove production and just use default and environment.
We can set:
"targetDefaults": {
"build": {
"cache": true,
"inputs": [
"default",
"environment"
]
}
}
Then we don't need the production namedInput.
So the final nx.json:
{
...,
"namedInputs": {
"default": [
"/*",
"!/node_modules/",
"!/dist/**",
"!{workspaceRoot}/Dockerfile",
"!{workspaceRoot}/.dockerignore"
],
"environment": [
"TOOLCHAIN_VERSION"
]
},
"targetDefaults": {
"build": {
"cache": true,
"inputs": [
"default",
"environment"
]
}
}
}
Step 16: Test.
We should test that:
-
Changing the source code (but not package.json) invalidates the cache? Actually, the source code is in default, so yes.
-
Changing the package.json invalidates the cache? Yes, because package.json is in default.
-
Changing the Dockerfile (which is excluded from default) does not invalidate the cache? But note: the Dockerfile change requires rebuilding the Docker image, but the build inside the container will use the same TOOLCHAIN_VERSION (if the base image didn't change) and the same source code, so the cache should be hit? But we rebuilt the Docker image, so the node_modules might be the same? Yes, if the package.json didn't change, then the node_modules is the same. So the build inside the container should be the same and the cache should be hit.
-
Changing the base image in the Dockerfile: then the TOOLCHAIN_VERSION changes (because the Node and npm versions change) and the node_modules might change? Actually, the node_modules is built with the new Node version? Yes, because we run npm ci in the new image. So the TOOLCHAIN_VERSION changes and the node_modules changes? But the node_modules is not in the hash? It's not, because it's in the container. But the build output might be different because of the Node version. So we want the cache to be invalid. The TOOLCHAIN_VERSION is in the hash, so it will be invalid.
So it works.
Step 17: Summary of files to create/modify:
Dockerfile (in the root of the monorepo)
nx.json (modify the namedInputs and targetDefaults)
package.json (might need to set engines for Node version, but we are using a fixed base image so it's not necessary for the build, but for local development without Docker we might want to enforce the Node version. We can set engines and use nvm to enforce locally.)
We also set up Nx Cloud by running npx nx connect-to-nx-cloud.
That's it.
Let's write the files.
Note: The above assumes we are using Nx with the default configuration. If we have multiple apps and libraries, the build target for each might be different. We set the build target for all projects? Actually, the targetDefaults applies to all targets named build in any project.
If we have different targets (like build for apps and build for libraries) it's the same target name? Yes, but they might have different configurations. We set the inputs for the build target globally.
But if we want to have different inputs for different projects, we can set it per project in project.json.
However, for simplicity, we assume all builds should be hermetic and use the same environment.
If we have projects that don't need the same environment, we can adjust.
But given the requirement for the entire monorepo, we want all builds to be hermetic.
So we set the global targetDefaults for build.
If we have a project that doesn't require the environment variable, we can override its inputs.
But let's assume we want all builds to be hermetic.
Step 18: Additional considerations.
- We are using
npm ci in the Dockerfile. We should use the same package manager in the container and locally? We are using npm. But what if we use yarn? We should use the same package manager everywhere.
We can set the package manager in the nx.json? Nx uses the package manager from the workspace (package.json). We are using npm.
-
We are using node:18-alpine. We should fix the version to node:18.17.0-alpine or something to avoid minor updates? We can use a fixed version tag.
-
We are setting the TOOLCHAIN_VERSION to the output of node --version and npm --version. But note that the node --version outputs something like v18.17.0. That's fine.
-
We are including the TOOLCHAIN_VERSION in the hash. But what if we have multiple Node versions in the same monorepo? We don't. We have one Node version for the entire build.
-
We are building all projects in the monorepo with nx run-many --target=build --all. We might want to build only the changed projects? But for CI, we might want to build all. Or we can use nx affected:build. But then we need to have the remote cache for each project.
The remote cache is per project? Yes, Nx caches per target per project. So if we run nx build for a specific project, it uses the cache for that project.
The hash for each project includes the source code of that project and its dependencies (via the namedInputs). We have set the same default and environment for all projects.
So it should work.
Step 19: Let's write the Dockerfile and the nx.json changes.
Dockerfile:
# Use a fixed version of Node to avoid unexpected updates.
FROM node:18.17.0-alpine
WORKDIR /app
# Copy package.json and package-lock.json to install dependencies.
COPY package*.json ./
# Install dependencies.
RUN npm ci
# Set the toolchain version as an environment variable.
# This will be used by Nx to include in the cache hash.
ENV TOOLCHAIN_VERSION="node:$(node --version) npm:$(npm --version)"
# By default, run the build for all projects.
CMD ["sh", "-c", "nx run-many --target=build --all"]
nx.json:
We are going to modify the existing nx.json (after connecting to Nx Cloud) to add the namedInputs and adjust the targetDefaults.
Example of what the nx.json might look like:
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"targetDefaults": {
"build": {
"cache": true,
"inputs": [
"production",
"environment"
]
}
},
"namedInputs": {
"default": [
"/*",
"!/node_modules/",
"!/dist/**",
"!{workspaceRoot}/Dockerfile",
"!{workspaceRoot}/.dockerignore"
],
"environment": [
"TOOLCHAIN_VERSION"
]
},
"nxCloudAccessToken": "..."
}
But note: the build target might already have an inputs array? We are overriding it. We should check the existing nx.json and adjust accordingly.
Alternatively, we can set the inputs for the build target in each project's project.json? But we want a global setting.
The targetDefaults sets the default for all projects for that target. If a project has its own targets.build.inputs set, that will override the targetDefaults.
So we set the targetDefaults and then make sure that no project overrides the inputs for the build target? Or we set it globally and then if a project needs a different set, it can override.
Given the requirement for hermeticity, we want all projects to use the same inputs.
So we set the targetDefaults and then remove any inputs from individual project configurations? Or we rely on the targetDefaults.
But note: the default namedInput might be too broad? It includes all source files. That's what we want for hermeticity.
Step 20: Testing the setup.
We can test by:
-
Building the Docker image and running the container. It should run the build and use the remote cache.
-
Then change a source file and run again. It should rebuild and update the remote cache.
-
Then change the Dockerfile (or the base image) and rebuild the Docker image and run. It should rebuild because the TOOLCHAIN_VERSION changed.
-
Then change the package.json and rebuild the Docker image (because the Dockerfile copies package.json) and run. It should rebuild because the package.json is in the default namedInput and the node_modules in the image changed, but the hash includes the package.json, so it will rebuild.
Step 21: CI/CD example.
In GitHub Actions:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build Docker image
run: |
docker build -t my-monorepo:latest --build-arg DOCKER_IMAGE_VERSION=${{ github.sha }} .
- name: Run build in container
run: |
docker run -v $(pwd):/app my-monorepo:latest
But note: we are not setting the DOCKER_IMAGE_VERSION in the Dockerfile anymore? We removed it and use TOOLCHAIN_VERSION.
So we don't need the build-arg.
We can remove the ARG and ENV from the Dockerfile? Actually, we set the TOOLCHAIN_VERSION in the Dockerfile without an ARG. So it's set at build time and baked into the image.
So we don't need to pass any build arg.
Therefore, the CI step becomes:
- name: Build Docker image
run: docker build -t my-monorepo:latest .
And then run the container.
But note: the TOOLCHAIN_VERSION is set in the Dockerfile and will be the same for every build of the same Dockerfile? Yes, because it's set by the base image's node and npm versions.
So if we build the same Dockerfile (with the same base image) we get the same TOOLCHAIN_VERSION.
But if we change the base image, the TOOLCHAIN_VERSION changes.
That's what we want.
Step 22: Final note.
This setup ensures that:
- The build runs in a sandbox (Docker container) with fixed toolchain.
- The remote cache key includes the toolchain version and the source code (excluding Dockerfile and .dockerignore).
- The build is hermetic because the environment is fixed and the same inputs produce the same outputs.
We are using Nx Cloud for remote caching, which is configured to use the inputs we defined.
We are done.
I'll design a comprehensive monorepo build system with remote caching, sandboxing, and hermeticity. Here's a production-ready approach:
Architecture Overview
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Developer │ │ CI/CD Pipeline │ │ Remote Cache │
│ Machine │───▶│ (Sandboxed) │───▶│ (S3/GCS/Azure) │
│ (Optional │ │ │ │ │
│ Sandbox) │◀───┤ │◀───┤ │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Local Cache │ │ Build Executor │ │ Artifact Store │
│ (disk/memory) │ │ (RBE/OpenTele) │ │ (Optional) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
1. Tool Selection & Configuration
Build System: Bazel + Rules Node.js/Go/Rust
# WORKSPACE
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# Node.js toolchain
http_archive(
name = "build_bazel_rules_nodejs",
sha256 = "...",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/x.y.z/rules_nodejs-x.y.z.tar.gz"],
)
# Google Remote Execution (RBE) for remote caching/execution
http_archive(
name = "io_bazel_rules_remote_exec",
sha256 = "...",
urls = ["https://github.com/bazelbuild/rules_remote_exec/releases/download/v0.0.0/rules_remote_exec-v0.0.0.tar.gz"],
)
Alternative: Nx with Docker + Remote Cache
// nx.json
{
"namedInputs": {
"production": ["default", "{workspaceRoot}/Dockerfile"],
"environment": ["CI", "PATH", "HOME"]
},
"targetDefaults": {
"build": {
"cache": true,
"inputs": ["production", "environment"]
}
}
}
2. Hermetic Build Configuration
Docker-based Sandbox (for non-Bazel setups)
# Dockerfile.build
FROM --platform=$BUILDPLATFORM node:18-alpine AS builder
# Install build dependencies
RUN apk add --no-cache \
build-base \
python3 \
make \
g++ \
&& npm install -g yarn@1.22.19
# Copy only dependency files first for better caching
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile --production=false
# Copy source and build
COPY . .
RUN yarn build:prod
# Runtime image (smaller)
FROM node:18-alpine
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/index.js"]
Platform-specific Build Args
# .bazelrc
build --host_platform=//:linux-x86_64
build --platforms=//:linux-x86_64
build --action_env=BAZEL_CXXOPTS="-std=c++14"
build --action_env=BAZEL_CFLAGS="-O2 -g"
3. Remote Caching Setup
Bazel Remote Cache (Recommended)
# Start remote cache server (using bazel-remote)
docker run -d \
-p 8080:8080 \
-v /data:/data \
ghcr.io/buchgr/bazel-remote:latest \
--max_size 100GB \
--dir /data
# Configure .bazelrc
build --remote_cache=https://remote.cache.company.com:443
build --remote_timeout=3600
build --remote_max_connections=100
build --remote_upload_local_results
S3/GCS Remote Cache Backend
# Using bazel-remote with S3
bazel-remote \
--s3.bucket=my-bazel-cache \
--s3.region=us-west-2 \
--s3.endpoint=s3.us-west-2.amazonaws.com \
--max_size 500GB
Nx Cloud Configuration
# Set up Nx Cloud with custom cache
nx connect-to-nx-cloud --cloudUrl=https://nx.app.company.com
# Configure in nx.json
{
"nxCloudId": "your-cloud-id",
"nxCloudAccessToken": "your-token",
"nxCloudOptions": {
"cacheableOperations": ["build", "test", "lint"],
"parallel": 3,
"daemon": false
}
}
4. Sandboxing Implementation
Bazel Sandboxing (Default)
# BUILD.bazel
load("@rules_nodejs//nodejs:defs.bzl", "nodejs_binary")
nodejs_binary(
name = "app",
entry_point = "src/index.js",
# Automatically sandboxed by Bazel
# Dependencies are fetched from remote cache
# Build runs in isolated filesystem
data = [
"@npm//:node_modules",
],
# Ensure hermeticity
templated_args = [
"--no-deprecation",
"--max-old-space-size=4096",
],
)
Docker Sandbox with Custom Entrypoint
#!/bin/bash
# scripts/sandboxed-build.sh
set -euo pipefail
# 1. Validate environment
node --version
npm --version
yarn --version
# 2. Clean previous builds
rm -rf node_modules/.cache dist .next
# 3. Install exact dependencies
yarn install --frozen-lockfile --network-timeout 600000
# 4. Build with environment variables
NODE_ENV=production \
NEXT_TELEMETRY_DISABLED=1 \
yarn build
# 5. Verify output
test -d dist || test -d .next
5. Hermeticity Enforcement
Lock All Dependencies
{
"packageManager": "yarn@1.22.19",
"engines": {
"node": ">=18.17.0 <19",
"npm": ">=9.0.0",
"yarn": "1.22.19"
}
}
Reproducible Build Config
// .babelrc.js
module.exports = function (api) {
api.cache(true);
return {
presets: [
[
'@babel/preset-env',
{
targets: {
node: '18',
},
modules: false,
useBuiltIns: false,
},
],
],
// Deterministic output
compact: true,
sourceMaps: 'both',
};
};
Version Pinning Script
# scripts/pin_versions.py
import json
import subprocess
def pin_versions():
# Pin Node version in package.json
with open('package.json', 'r+') as f:
pkg = json.load(f)
pkg['engines']['node'] = '18.17.0'
f.seek(0)
json.dump(pkg, f, indent=2)
# Generate lockfile with exact versions
subprocess.run(['yarn', 'install', '--frozen-lockfile', '--mode=production'])
# Generate SBOM for audit trail
subprocess.run(['yarn', 'sbom', '--output', 'sbom.spdx.json'])
if __name__ == '__main__':
pin_versions()
6. CI/CD Pipeline Example
GitHub Actions with Remote Cache
# .github/workflows/build.yml
name: Monorepo Build
on:
push:
branches: [main]
pull_request:
jobs:
build:
runs-on: ubuntu-latest
container:
image: docker.io/company/build-image:2024.01.15
options: --cpus=4 --memory=8g
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # Required for Nx affected
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: '18.17.0'
cache: 'yarn'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Run build with remote cache
run: |
# Bazel example
bazel build //... --config=remote-cache
# Nx example
npx nx affected --target=build --base=origin/main --head=HEAD
- name: Upload artifacts
uses: actions/upload-artifact@v3
with:
name: build-outputs
path: |
dist/
.nx/
7. Security & Validation
Supply Chain Security
# .syft/config.yaml
exclude:
- "@babel/*"
- "eslint-*"
attest:
- type: spdx
output: sbom.spdx.json
- type: cyclonedx
output: sbom.cdx.json
Cache Validation
# scripts/validate_cache.py
import hashlib
import json
def validate_cache_integrity(cache_key, build_output):
"""Verify cache hasn't been tampered with"""
expected_hash = get_remote_cache_hash(cache_key)
actual_hash = hashlib.sha256(build_output).hexdigest()
if expected_hash != actual_hash:
raise SecurityError(f"Cache mismatch for {cache_key}")
# Verify all dependencies in lockfile
verify_lockfile_digest()
return True
8. Monitoring & Observability
Build Metrics Export
// tools/build-metrics.js
const { performance } = require('perf_hooks');
const prometheus = require('prom-client');
const buildDuration = new prometheus.Histogram({
name: 'build_duration_seconds',
help: 'Build duration in seconds',
labelNames: ['project', 'target'],
});
// Wrap build functions
function instrumentedBuild(project, target, buildFn) {
const start = performance.now();
try {
return buildFn();
} finally {
const duration = (performance.now() - start) / 1000;
buildDuration
.labels(project, target)
.observe(duration);
}
}
9. Troubleshooting Guide
Common Issues & Solutions
- Cache Misses
# Debug Bazel cache
bazel aquery --include_aspects=@bazel_tools//tools/cache:cache_aspect \
--output=proto //:target
# Check Nx cache
npx nx show-cache --projects=my-app
- Non-Hermetic Builds
# Find non-hermetic operations
bazel build //... --sandbox_tmpfs_path=/tmp --verbose_failures
# Check for host file access
strace -f -e trace=openat bazel build //:target 2>&1 | grep -v '/dev\|/proc'
- Sandbox Failures
# Increase sandbox resources
bazel build //... --sandbox_cpu_limit_soft=100 \
--sandbox_memory_limit_soft=8192 \
--sandbox_writable_path=/tmp
10. Best Practices
Do's:
- ✅ Pin all versions in lockfiles and container images
- ✅ Use remote execution for truly isolated builds
- ✅ Include all env vars in cache key via
namedInputs
- ✅ Sign cache entries with cryptographic hashes
- ✅ Monitor cache hit rates (>80% target)
Don'ts:
- ❌ Don't rely on global/npm-installed tools
- ❌ Don't use timestamps in build outputs
- ❌ Don't write outside designated output dirs
- ❌ Don't access network during build (unless explicitly allowed)
- ❌ Don't use
--no-sandbox in production
Quick Start Script
#!/bin/bash
# setup-monorepo-build.sh
set -euo pipefail
# 1. Initialize monorepo
npx create-nx-workspace@latest my-monorepo --preset=ts
# 2. Install remote cache
docker run -d \
-p 8080:8080 \
-v $(pwd)/.cache:/data \
ghcr.io/buchgr/bazel-remote:latest
# 3. Configure hermetic build
cat > Dockerfile.build <<'EOF'
# (Use Dockerfile from above)
EOF
# 4. Set up CI
mkdir -p .github/workflows
cp build.yml .github/workflows/
# 5. Validate setup
yarn nx build my-app --dry-run
echo "✅ Setup complete!"
Key Metrics to Monitor
- Cache Hit Rate: Target >80%
- Build Time: Track P50/P95/P99
- Sandbox Failures: Should be <1%
- Artifact Size: Monitor for bloat
- Reproducibility:
bazel build --check_up_to_date success rate
This architecture provides:
- Remote caching: Bazel-remote/Nx Cloud/S3
- Sandboxing: Docker/Bazel sandboxfs/remote execution
- Hermeticity: Lockfiles, pinned toolchains, isolated filesystems
- Scalability: Parallel builds with resource limits
- Security: Supply chain validation, cache signing
Choose Bazel for maximum hermeticity and performance or Nx + Docker for simpler JavaScript/TypeScript monorepos with similar guarantees.