We are designing a CI/CD pipeline for monorepos. The key challenges in monorepos are handling multiple interdependent packages, avoiding unnecessary builds/tests, efficient caching, and managing deployments.
We'll break down the requirements:
-
Dependency graph detection: Understand the dependency relationships between packages in the monorepo to determine the order of builds and which packages are affected by changes.
-
Selective builds/tests: Only build and test packages that are affected by the changes (and their dependents) to save time and resources.
-
Caching strategies: Cache dependencies (like node_modules, build artifacts) to speed up builds. The cache should be keyed appropriately to avoid stale cache.
-
Environment matrix: Test and deploy across multiple environments (like different Node.js versions, operating systems, or cloud providers) if necessary.
-
Security scanning gates: Integrate security scanning (SAST, SCA, etc.) and have gates that block merging or deployment if vulnerabilities are found.
-
Deployment orchestration: Coordinate deployments of multiple packages, possibly with dependencies between them (e.g., package A must be deployed before package B).
-
Observability hooks: Integrate with monitoring and logging tools to track pipeline performance and application metrics.
We'll design a pipeline that can be implemented with a CI/CD system like GitHub Actions, GitLab CI, or Jenkins. For this design, we'll use a generic approach that can be adapted.
Let's outline the stages:
-
Detect changes and build dependency graph:
- Use a tool (like NX, Lerna, or a custom script) to analyze the monorepo structure and build a dependency graph.
- Determine which packages are affected by the current changes (using
git diff or similar).
-
Selective builds and tests:
- Based on the affected packages, determine the set of packages to build and test (including dependencies of affected packages, if necessary).
- For each package in the set, run build and test steps.
-
Caching:
- Use a shared cache for dependencies (like npm/yarn/pnpm cache) and build artifacts.
- The cache key should be based on a hash of the lockfile and the package's dependency files (package.json, etc.) and possibly the CI runner environment.
-
Environment matrix:
- If we need to test across multiple environments, we can set up a matrix strategy. However, note that running a matrix for every affected package might be heavy. We might limit the matrix to the root or to packages that require multi-environment testing.
-
Security scanning:
- Run security scanners (like Snyk, OWASP Dependency Check, Trivy, etc.) on the affected packages and their dependencies.
- Set a threshold for allowed vulnerabilities and fail the pipeline if exceeded.
-
Deployment orchestration:
- For packages that are to be deployed, determine the deployment order based on the dependency graph (if package A depends on B, then B must be deployed first).
- Use a deployment tool (like Helm for Kubernetes, or cloud-specific deployment tools) and manage credentials securely.
- Consider canary or blue-green deployments if needed.
-
Observability:
- Emit metrics and logs from the pipeline (like build times, test coverage, deployment status) to a monitoring system (like Prometheus, Datadog, etc.).
- Integrate with error tracking (like Sentry) for post-deployment monitoring.
Now, let's design a concrete pipeline structure:
We assume the monorepo is managed with a tool that understands the dependency graph (like NX, Lerna, or Rush). We'll use NX as an example because it provides affected commands and caching out of the box. However, the design can be adapted.
Pipeline stages:
-
Checkout and setup:
- Checkout code.
- Set up Node.js (or other required runtime) and install dependencies (using the package manager).
-
Dependency graph and affected packages:
- Run
nx affected:graph (or equivalent) to get the list of affected packages and the dependency graph.
- Save the list of affected packages and the graph as artifacts for later stages.
-
Security scanning:
- Run security scans on the affected packages and their dependencies. This can be done by scanning the entire monorepo or just the affected packages.
- We might run the scanner at the root and then filter by the affected packages, but note that dependencies might be outside the affected set. It's safer to scan the entire repository's dependencies, but that might be heavy. Alternatively, we can scan the affected packages and their direct and transitive dependencies (which might be the entire monorepo if the affected packages are core). We need to decide based on the project.
-
Build and test (selective):
- For each affected package (and possibly their dependents if we are deploying), run the build and test commands.
- Use caching for build artifacts and dependencies. NX has built-in caching, but we can also set up pipeline-level caching (like GitHub Actions cache) for the package manager cache.
-
Environment matrix (if needed):
- If we need to test across multiple environments, we can set up a matrix for the build and test stage. But note: if we are doing selective builds, we might run the matrix for each affected package? That could be too many jobs. Alternatively, we can run the matrix only for the root or for packages that require it. We might have a configuration per package that specifies the environments it needs.
-
Deployment:
- For packages that are marked for deployment (perhaps only those that have changed and are not libraries, or based on a conventional commit), we deploy in the order of the dependency graph (dependencies first).
- We can have a stage that collects all deployment jobs and then orders them. Alternatively, we can have a single job that does the deployment in order.
-
Observability:
- Throughout the pipeline, record metrics and send them to a monitoring system.
- After deployment, run post-deployment tests (smoke tests) and monitor application metrics.
Implementation details for caching:
We can use the built-in caching of the monorepo tool (like NX) for build artifacts. Additionally, we can cache the package manager's cache (like ~/.npm, ~/.yarn, or ~/.pnpm) to speed up installation.
Example for GitHub Actions:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm' # or 'yarn' or 'pnpm'
- name: Install dependencies
run: npm ci
- name: Detect affected
id: affected
run: |
npx nx affected:graph --output=affected.json
# Extract list of affected projects (for next steps)
echo "affected_projects=$(jq -r '.nodes | keys[]' affected.json)" >> $GITHUB_OUTPUT
- name: Build and test affected projects
run: |
npx nx affected:test --parallel=3 --max-parallel=3
But note: the above example uses NX's affected command which already does selective builds and tests. However, we might want to split build and test for separate reporting.
Alternatively, we can break down:
- Get the list of affected projects.
- For each project, run build and then test. But NX can run multiple projects in parallel.
Security scanning:
We can integrate with Snyk or GitHub Advanced Security. For example, with Snyk:
- name: Run Snyk to check for vulnerabilities
uses: snyk/actions/node@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
with:
args: --all-projects
But note: --all-projects scans the entire monorepo. We might want to scan only affected projects? However, vulnerabilities might be in dependencies that are not in affected projects but are used by affected projects. So scanning the entire monorepo is safer.
Deployment orchestration:
We need to deploy in order. We can have a job for each package but then we must set up dependencies between jobs. Alternatively, we can have a single job that does:
# Get the list of projects to deploy in topological order (dependencies first)
npx nx affected:deploy -- --parallel=1
But note: the affected:deploy target must be defined for each project and NX will run them in the correct order.
Alternatively, we can generate the order and then deploy one by one.
Observability:
We can use CI/CD system's built-in metrics and also custom steps to send data to an external system. For example, we can emit a metric at the end of each stage with the duration.
Environment matrix:
If we need to test across multiple Node.js versions, we can set up a matrix in the build and test job. However, note that the affected projects might not all support the same Node versions. We might need to configure per project.
Alternatively, we can have a job that runs the build and test for the entire monorepo in a matrix, but then we lose the selective build. So we might have to run the matrix for each affected project? That could be too heavy.
A compromise: we can have a matrix that runs the affected build and test for the entire monorepo (i.e., run nx affected:test for each matrix combination). This way we are still selective but also covering multiple environments.
Example:
build-and-test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x, 16.x, 18.x]
steps:
- uses: actions/checkout@v3
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Detect affected
id: affected
run: |
npx nx affected:graph --output=affected.json
- name: Build and test affected projects
run: |
npx nx affected:test --parallel=3
But note: the matrix will run the entire affected test suite for each Node version. This might be acceptable if the affected set is small.
Putting it all together:
We'll design a pipeline with the following jobs:
- detect-affected: Run the dependency graph detection and produce a list of affected projects and the graph (as artifacts).
- security-scan: Run security scanning (maybe on the entire repo or affected projects). This job depends on the detection job but does not need the list of affected projects if scanning entire repo.
- build-and-test: Run for each environment in the matrix. This job depends on the detection job and uses the list of affected projects. It builds and tests only the affected projects for that environment.
- deploy: Deploy the affected projects in topological order. This job depends on the build-and-test job (for all matrix combinations? or just one? We might want to deploy only after all tests pass in all environments). Alternatively, we can have a manual approval before deployment and then run deployment only once (for one environment, if the deployment is environment-specific). This gets complex.
Alternatively, we can decouple the environment matrix from the deployment. We test in multiple environments, but deployment might be only to one environment (like production). So we can have:
- A job that runs the entire test suite (including matrix) and then a separate deployment job that runs only after all tests pass.
But note: the deployment might also need to be environment-specific? Usually, we test in multiple environments and then deploy to production. So we can have:
- test job with matrix (staging, production-like environments) and then a deploy job that runs only for the production environment (or we can have a matrix for deployment too?).
We might want to deploy to multiple environments (like staging and production) and have a manual approval in between. So:
- detect-affected
- security-scan
- test (with matrix for multiple Node versions, and maybe also multiple OS if needed)
- deploy-staging: Deploy to staging (if tests pass). This job depends on the test job and uses the same affected list. It deploys in order.
- smoke-tests-staging: Run smoke tests on staging. If passes, then allow manual approval for production.
- deploy-production: Deploy to production (with the same order). This job might have a manual approval step.
But note: the deployment might be to different clouds or clusters. We can parameterize the deployment job with the environment.
Alternatively, we can have a single deployment job that takes an environment parameter and then triggers for staging and production separately.
Observability hooks:
We can add steps in each job to send metrics to a monitoring system. For example, at the end of each job, we can send the duration and status.
We can also collect test coverage and send it to a service like Codecov.
Caching:
We'll use the package manager cache and also the NX cache (if using NX). We can store the NX cache as an artifact or use a remote cache (like with NX cloud). For the package manager cache, we can use the built-in caching of actions/setup-node.
But note: the cache for the package manager is per Node version? We are using a matrix, so we need to cache per Node version. The actions/setup-node does that automatically if we set cache: 'npm' and the node-version is in the matrix.
Summary of jobs in GitHub Actions:
name: Monorepo CI/CD
on:
push:
branches: [main]
pull_request:
jobs:
detect-affected:
runs-on: ubuntu-latest
outputs:
affected-projects: ${{ steps.affected.outputs.affected_projects }}
affected-graph: ${{ steps.affected.outputs.affected_graph }}
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # needed for NX affected to work properly
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Detect affected projects and graph
id: affected
run: |
npx nx affected:graph --output=affected.json
# The graph is a JSON with nodes and edges. We might need to pass the list of affected projects and the graph to other jobs.
# Let's extract the list of affected project names (keys in the nodes object) and also save the graph.
echo "affected_projects=$(jq -r '.nodes | keys[]' affected.json)" >> $GITHUB_OUTPUT
# We'll also upload the graph as an artifact for later jobs.
echo "graph=$(cat affected.json)" >> $GITHUB_OUTPUT
security-scan:
needs: detect-affected
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run Snyk security scan
uses: snyk/actions/node@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
with:
args: --all-projects
# Alternatively, we can scan only the affected projects? But Snyk doesn't have an easy way to scan by project list in a monorepo?
# We might need to run `snyk test` in each affected project directory. But then we might miss vulnerabilities in shared dependencies.
# So scanning the entire monorepo is acceptable.
build-and-test:
needs: [detect-affected, security-scan]
strategy:
matrix:
node-version: [14.x, 16.x, 18.x]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build and test affected projects
run: |
# We need the list of affected projects from the detect-affected job. We can pass it as an input or use the output.
# In GitHub Actions, we can use needs.detect-affected.outputs.affected_projects
# But note: the matrix job might not have direct access to the output of a previous job? Actually, it does because we set `needs`.
# However, the output is a string of project names separated by newlines? We can write it to a file and then use it.
# Alternatively, we can use the NX affected command again? But that would re-compute the affected projects based on the current branch?
# We want to use the same list as the detect-affected job. So we should pass the list.
# Let's assume the detect-affected job outputs a JSON array? Actually, we output a string of names separated by spaces? We used `jq -r '.nodes | keys[]'` which outputs each key on a new line.
# We can convert that to an array in the step.
# But note: the matrix job runs on multiple runners and the output from detect-affected is available as a string.
# We can do:
echo "${{ needs.detect-affected.outputs.affected_projects }}" > affected_projects.txt
# Then set the projects for NX:
export NX_PROJECTS=$(cat affected_projects.txt | tr '\n' ',')
# But NX expects a comma-separated list? Actually, the `--projects` flag of NX takes a comma-separated list.
npx nx affected:test --projects=$NX_PROJECTS --parallel=3
env:
# We might need to pass the base and head for affected? The detect-affected job used the default (current branch vs main). We assume the same.
# But note: the matrix job is running on the same commit, so the affected set should be the same.
# However, if we are running on a pull request, we might have to set the base and head? NX affected uses the git history to determine affected.
# We are using `fetch-depth: 0` so we have the full history.
deploy-staging:
needs: build-and-test
runs-on: ubuntu-latest
environment: staging
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Deploy affected projects to staging
run: |
# We need the list of affected projects and the graph to determine order. We have the graph from detect-affected.
# We can write the graph to a file and then use a script to deploy in order.
echo '${{ needs.detect-affected.outputs.graph }}' > graph.json
# Then use a script (maybe custom) that reads the graph and deploys projects in topological order.
# Alternatively, if using NX, we can run `nx affected:deploy` which should respect the dependency order.
# But note: the `affected:deploy` target must be defined for each project and NX will run them in the correct order.
npx nx affected:deploy --projects=${{ needs.detect-affected.outputs.affected_projects }} --parallel=1
env:
# Deployment environment variables (like AWS credentials, etc.)
STAGING_ENV: ${{ secrets.STAGING_ENV }}
smoke-tests-staging:
needs: deploy-staging
runs-on: ubuntu-latest
steps:
- name: Run smoke tests on staging
run: |
# Call a script or use a tool to run smoke tests against the staging environment.
./scripts/smoke-tests.sh staging
deploy-production:
needs: smoke-tests-staging
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Deploy affected projects to production
run: |
echo '${{ needs.detect-affected.outputs.graph }}' > graph.json
npx nx affected:deploy --projects=${{ needs.detect-affected.outputs.affected_projects }} --parallel=1
env:
PROD_ENV: ${{ secrets.PROD_ENV }}
Notes:
-
The above pipeline assumes that we are using NX and that the affected:deploy target is defined and respects the dependency order. If not, we might need to write a custom script to topologically sort the affected projects and deploy in that order.
-
The detect-affected job runs nx affected:graph and saves the graph. We pass the graph to the deployment jobs. Alternatively, we can re-run nx affected:graph in the deployment jobs, but that might be inconsistent if the code has changed? The deployment jobs are running on the same commit, so it should be the same.
-
The build-and-test job uses a matrix for Node.js versions. We assume that all affected projects support all these Node versions. If not, we might need to have a per-project configuration of which Node versions to test. This could be done by having a matrix that is generated from the affected projects' configurations. That is more complex.
-
Security scanning: we are scanning the entire monorepo. This might be heavy, but it's safe. We can also try to scan only the affected projects and their dependencies, but that requires a tool that can do that. Snyk can scan a directory, so we could run it for each affected project? But then we might miss vulnerabilities in shared dependencies that are not in the affected projects? Actually, if a shared dependency is used by an affected project, then that dependency will be in the affected project's node_modules? Not necessarily, because in a monorepo we might have hoisted dependencies. So scanning the entire monorepo is safer.
-
Caching: we are using actions/setup-node cache for npm. This caches the npm cache (usually ~/.npm). Additionally, NX has its own cache for build artifacts. We are not explicitly setting up NX remote cache, but if we have NX cloud, we can use that. Alternatively, we can cache the node_modules/.cache or the NX cache directory.
-
Observability: we haven't added explicit observability hooks. We can add steps to send metrics to a monitoring system. For example, at the end of each job, we can send the job duration and status. We can also collect test coverage and send it to Codecov.
Example for test coverage:
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
token: ${{ secrets.CODECOV_TOKEN }}
file: ./coverage/coverage-final.json
flags: unittests
name: codecov-umbrella
But note: we are running tests for multiple projects. We might need to aggregate coverage. NX can aggregate coverage across projects.
-
We are using environments (staging and production) for deployment jobs, which in GitHub Actions can require manual approval for production.
Alternative approach without NX:
If we are not using NX, we need to:
-
Build the dependency graph: We can use a tool like madge or dependency-cruiser to generate the graph, or if using a monorepo tool like Lerna, we can use lerna list --graph.
-
Determine affected packages: We can use git diff to see which files changed and then map to packages (by looking at which package.json files are in the changed directories or if the change is in a shared file, then all packages that depend on it? This is complex). Alternatively, we can use a tool like changesets or lerna version to determine affected packages.
-
Then, we would need to manually define the order of packages (topological sort of the graph) and then build/test/deploy in that order.
Given the complexity, using a tool like NX is highly recommended for monorepos.
Conclusion:
This design provides a blueprint for a CI/CD pipeline for monorepos. The exact implementation will depend on the monorepo tool and the CI/CD system used. The key is to leverage the dependency graph to do selective builds and tests, and to orchestrate deployments in the correct order. Caching and security scanning are also critical for performance and safety. Observability should be integrated throughout.
I'll design a comprehensive CI/CD pipeline for monorepos that addresses all your requirements. This solution implements progressive optimization - starting simple and adding complexity only where needed.
Architecture Overview
┌─────────────────────────────────────────────────────────────────┐
│ CI/CD Pipeline for Monorepos │
├─────────────────────────────────────────────────────────────────┤
│ 1. Dependency Graph Detection │
│ 2. Change Impact Analysis & Selective Builds │
│ 3. Multi-Layer Caching │
│ 4. Environment Matrix Testing │
│ 5. Security Scanning Gates │
│ 6. Deployment Orchestration │
│ 7. Observability & Feedback Loops │
└─────────────────────────────────────────────────────────────────┘
1. Dependency Graph Detection
Graph Generation Strategy
# .nx-dev/affected.js (NX example) or custom script
detect_dependency_graph:
tools:
- Primary: NX, Turborepo, or Bazel (preferred for built-in graph)
- Fallback: Custom script using:
* package.json "workspaces" field
* lerna.json (if using Lerna)
* TypeScript project references (tsconfig.json)
* Custom dependency parser (madge, dependency-cruiser)
implementation:
# Generate graph at pipeline start
nx affected:graph --output=graph.json
# Output format:
{
"nodes": [
{"name": "apps/web", "type": "app", "tags": ["frontend"]},
{"name": "libs/ui", "type": "lib", "tags": ["ui"]}
],
"edges": [
{"from": "apps/web", "to": "libs/ui", "type": "dependency"}
],
"affected": ["apps/web", "libs/ui"] # from diff analysis
}
Change Detection
# Determine affected projects
affected_projects() {
# Compare base/head from PR or commit range
local BASE=$1 HEAD=$2
# Method 1: NX/Turborepo native
npx nx affected:apps --base=$BASE --head=$HEAD
# Method 2: Git diff-based
git diff --name-only $BASE $HEAD | \
awk -F/ '{print $1}' | sort -u | \
xargs -I{} jq -r --arg dir {} '.[] | select(.path | startswith($dir)) | .name' package.json
# Method 3: Changesets (if used)
npx changeset status --since=$BASE
}
2. Selective Builds/Tests
Affected Pipeline Strategy
# .github/workflows/ci.yml or gitlab-ci.yml
selective_execution:
strategy:
matrix:
# Include only affected projects
project: ${{ fromJson(needs.graph.outputs.affected_projects) }}
# Optional: Include dependents of affected projects
# (for integration tests that span projects)
include_dependents: [true, false]
steps:
- if: ${{ matrix.include_dependents == true }}
run: |
# Get projects that depend on affected ones
echo "::set-output name=projects::$(
jq -r --argjson affected '${{ needs.graph.outputs.affected }}' \
'[.[] | select(.dependencies | any(. as $dep | $affected | index($dep)))] | unique | .[]' \
graph.json
)"
id: dependents
- run: |
if [ ${{ matrix.include_dependents }} = true ]; then
PROJECTS="${{ steps.dependents.outputs.projects }}"
else
PROJECTS="${{ matrix.project }}"
fi
echo "Building: $PROJECTS"
# Parallel build with concurrency limits
echo "$PROJECTS" | xargs -P 4 -I {} npx nx run {}:build
# Test with strategic concurrency (heavy tests serialized)
echo "$PROJECTS" | xargs -P 2 -I {} npx nx run {}:test
Test Prioritization
// test-prioritizer.js
const prioritization = {
unit: { priority: 1, pattern: "**/*.spec.ts", parallel: true },
integration: { priority: 2, pattern: "**/*.int-spec.ts", parallel: false },
e2e: { priority: 3, pattern: "**/*.e2e-spec.ts", parallel: false }
};
// Run in order: unit → integration → e2e
// Within each tier, run affected tests in parallel
3. Caching Strategies
Multi-Layer Cache Design
caching:
# Layer 1: Package manager cache (npm/yarn/pnpm)
- key: ${{
hashFiles(
'**/package-lock.json',
'**/yarn.lock',
'**/pnpm-lock.yaml',
'**/npm-shrinkwrap.json'
)
}}
path: |
~/.npm
~/.yarn
~/.pnpm-store
# Layer 2: Workspace dependencies (hoisted)
- key: ${{ runner.os }}-node-${{ hashFiles('**/package.json') }}-workspace
path: node_modules
# Layer 3: Build artifacts (per project)
- key: ${{ runner.os }}-nx-${{ hashFiles('**/tsconfig.json') }}-${{ matrix.project }}
path: |
dist/apps/${{ matrix.project }}
dist/libs/${{ matrix.project }}
.nx/cache
# Layer 4: Docker layer cache (if building containers)
- key: ${{ runner.os }}-docker-${{ hashFiles('**/Dockerfile') }}
path: |
/tmp/docker-cache
Cache Invalidation Rules
# Invalidate cache when:
# 1. Lockfile changes (automatic via hash)
# 2. Node.js version changes (key includes node version)
# 3. Build scripts change (hash package.json "scripts" section)
# 4. Manual cache bust via CI UI or API
Remote Cache Setup
# Using NX Cloud or custom S3/GCS cache
nx_cloud:
enabled: true
url: https://nx.app.example.com
token: ${{ secrets.NX_CLOUD_TOKEN }}
# Fallback to S3 if NX Cloud unavailable
s3:
bucket: monorepo-cache
region: us-east-1
key: nx-cache/${{ github.sha }}
4. Environment Matrix
Dynamic Matrix Generation
environment_matrix:
strategy:
matrix:
# Auto-generate from project configurations
include:
- project: apps/web
node: [18.x, 20.x]
os: [ubuntu-latest, macos-latest]
browser: [chromium, firefox]
- project: libs/utils
node: [18.x]
os: [ubuntu-latest]
steps:
- name: Setup environment
run: |
echo "Testing ${{ matrix.project }} on Node ${{ matrix.node }} (${{ matrix.os }})"
- name: Run tests
run: |
# Export environment variables for test
export NODE_ENV=test
export BROWSER=${{ matrix.browser }}
npx nx run ${{ matrix.project }}:test
Environment-Specific Configs
// projects/apps/web/project.json
{
"targets": {
"test": {
"configurations": {
"production": {
"env": "production",
"options": ["--browsers=ChromeHeadless"]
},
"staging": {
"env": "staging",
"options": ["--browsers=Chrome"]
}
}
}
}
}
5. Security Scanning Gates
Multi-Scanner Integration
security_gates:
stages:
- name: "SAST (Static Analysis)"
run: |
# Semgrep for code patterns
semgrep --config=auto --error
# TypeScript/JavaScript specific
npx @typescript-eslint/eslint-recommended .
# Secrets scanning
gitleaks detect --source . --redact
- name: "SCA (Dependency Scanning)"
run: |
# npm audit with severity threshold
npm audit --audit-level=moderate || true
# OWASP Dependency Check
dependency-check --project "monorepo" --scan .
# Snyk (if token available)
if [ -n "$SNYK_TOKEN" ]; then
snyk test --severity-threshold=high
fi
- name: "Container Scanning (if applicable)"
run: |
trivy image --exit-code 1 --severity HIGH,CRITICAL $IMAGE
- name: "IaC Scanning"
run: |
checkov -d .
tfsec .
Gate Configuration
# .security-gates.yml
gates:
required_scanners: [semgrep, npm-audit, gitleaks]
severity_threshold: "medium" # fail on medium+
fail_fast: true
exceptions:
- path: "node_modules/**"
allowed_vulnerabilities: []
- path: "test/**"
allowed_vulnerabilities: ["low"]
# Auto-triage exceptions
auto_triage:
enabled: true
rules:
- vulnerability: "CVE-YYYY-NNNN"
expires: "30d"
comment: "False positive in test code"
6. Deployment Orchestration
Topological Deployment
# deploy-orchestrator.py
import json
from collections import deque
def topological_sort(graph):
"""Kahn's algorithm for dependency ordering"""
in_degree = {node: 0 for node in graph['nodes']}
for edge in graph['edges']:
in_degree[edge['to']] += 1
queue = deque([node for node, deg in in_degree.items() if deg == 0])
order = []
while queue:
node = queue.popleft()
order.append(node['name'])
for edge in graph['edges']:
if edge['from'] == node['name']:
in_degree[edge['to']] -= 1
if in_degree[edge['to']] == 0:
queue.append(edge['to'])
return order
def deploy_in_order(deployments, graph):
order = topological_sort(graph)
for project in order:
if project in deployments:
print(f"Deploying {project}...")
# Run deployment with rollback on failure
success = run_deployment(project)
if not success:
rollback_previous(project, order)
exit(1)
Deployment Strategies per Project
# deployments.yml
deployments:
apps/web:
strategy: blue-green
health_check:
endpoint: /health
timeout: 30s
canary:
percentage: 10%
duration: 5m
rollback:
automatic: true
trigger: [failed_health_check, error_rate > 5%]
libs/utils:
strategy: direct # libraries don't deploy
skip: true
7. Observability Hooks
Pipeline Metrics Collection
observability:
# Emit pipeline metrics to Prometheus
metrics:
- name: "ci_build_duration_seconds"
labels: [project, job, outcome]
value: ${{ job.duration }}
- name: "ci_test_coverage"
labels: [project]
value: ${{ steps.coverage.outputs.percentage }}
- name: "ci_cache_hit_rate"
labels: [cache_type]
value: ${{ steps.cache.outputs.hit_rate }}
# Log aggregation
logs:
destination: datadog/logs
tags: ["ci", "monorepo", "${{ github.repository }}"]
# Structured logging format
format: json
fields:
- commit_sha
- branch
- affected_projects
- build_time
- test_results
Post-Deployment Monitoring
post_deploy_observability:
steps:
- name: "Synthetic Canary Tests"
run: |
# Run smoke tests against new deployment
npx playwright test --project=canary
# Check error rates
ERROR_RATE=$(datadog query -q "avg(last_5m):sum:errors{service:${{ env.SERVICE }}}" 2>/dev/null || echo 0)
if (( $(echo "$ERROR_RATE > 0.05" | bc -l) )); then
echo "Error rate too high: $ERROR_RATE"
exit 1
fi
- name: "Performance Regression Check"
run: |
# Compare with baseline
CURRENT_LOAD_TIME=$(curl -s -o /dev/null -w "%{time_total}" $DEPLOYMENT_URL)
BASELINE=$(cat baseline/load-time.txt)
if (( $(echo "$CURRENT_LOAD_TIME > $BASELINE * 1.2" | bc -l) )); then
echo "Performance regression detected: ${CURRENT_LOAD_TIME}s vs ${BASELINE}s"
exit 1
fi
- name: "Feature Flag Verification"
run: |
# Ensure feature flags match expectations
npx nx run feature-flags:verify --environment=${{ env.ENVIRONMENT }}
Complete Pipeline Example (GitHub Actions)
name: Monorepo CI/CD
on:
pull_request:
branches: [main]
push:
branches: [main]
env:
NX_CLOUD: true
NX_DAEMON: false
jobs:
detect-affected:
runs-on: ubuntu-latest
outputs:
affected: ${{ steps.affected.outputs.affected }}
graph: ${{ steps.affected.outputs.graph }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Generate dependency graph
id: graph
run: |
npx nx affected:graph --base=${{ github.event.pull_request.base.sha || github.event.before }} \
--head=${{ github.event.pull_request.head.sha || github.sha }} \
--output=graph.json
AFFECTED=$(jq -r '.affected | join(",")' graph.json)
echo "affected=$AFFECTED" >> $GITHUB_OUTPUT
echo "graph=$(cat graph.json | jq -c)" >> $GITHUB_OUTPUT
- name: Upload graph artifact
uses: actions/upload-artifact@v4
with:
name: dependency-graph
path: graph.json
security-scan:
needs: detect-affected
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run security scanners
run: |
# SAST
semgrep --config=auto --error .
# SCA
npm audit --audit-level=moderate || true
# Secrets
gitleaks detect --source . --verbose
# Generate SARIF for GitHub Security tab
npx @semgrepo/sarif --output security.sarif
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: security.sarif
test-matrix:
needs: [detect-affected, security-scan]
strategy:
matrix:
include:
- project: apps/web
node: '20'
os: ubuntu-latest
- project: libs/utils
node: '18'
os: ubuntu-latest
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Setup Node ${{ matrix.node }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
cache: 'npm'
- name: Cache dependencies
uses: actions/cache@v4
with:
path: |
node_modules
.nx/cache
dist/${{ matrix.project }}
key: ${{ matrix.project }}-node-${{ matrix.node }}-${{ hashFiles('**/package-lock.json') }}
- name: Build and test
run: |
npx nx run ${{ matrix.project }}:build
npx nx run ${{ matrix.project }}:test --coverage
- name: Upload coverage
uses: codecov/codecov-action@v4
with:
files: ./coverage/apps/${{ matrix.project }}/coverage-final.json
flags: ${{ matrix.project }}
deploy:
needs: test-matrix
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- name: Deploy in dependency order
run: |
# Get topological order from graph
ORDER=$(jq -r '.nodes | sort_by(.dependencies | length) | .[].name' graph.json)
for PROJECT in $ORDER; do
if echo "${{ needs.detect-affected.outputs.affected }}" | grep -q "$PROJECT"; then
echo "Deploying $PROJECT..."
# Deployment per project strategy
if [ "$PROJECT" = "apps/web" ]; then
npx nx run $PROJECT:deploy:prod
elif [ "$PROJECT" = "libs/ui" ]; then
echo "Library $PROJECT doesn't deploy, publishing instead"
npx nx run $PROJECT:publish
fi
fi
done
- name: Run post-deployment checks
run: |
./scripts/post-deploy-checks.sh
- name: Notify deployment status
if: always()
run: |
curl -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"Deployment ${{ job.status }} for ${{ github.repository }}\"}" \
${{ secrets.SLACK_WEBHOOK }}
Key Optimizations & Best Practices
Performance Optimizations
- Parallelism by Tier: Run unit tests in parallel, integration tests serialized
- Cache Warming: Pre-populate cache from previous successful runs
- Incremental Adoption: Start with coarse-grained (package-level) targeting, refine to file-level
- Early Exit: Fail fast on security gates before expensive builds
Scalability Patterns
# Dynamic parallelism based on project size
parallelism: ${{
format('{0}',
if: contains(matrix.project, 'libs/')
then: 4 # libraries can parallelize more
else: 2 # apps have more integration constraints
)
}}
Fallback Strategies
- Cache Miss Recovery: If cache miss, use "pessimistic" cache (all deps) then optimize next run
- Partial Failure Handling: Continue testing unaffected projects if one fails
- Deployment Rollback: Automatic rollback on health check failure with circuit breaker
Monitoring & Alerting
alerts:
- metric: "ci_build_duration_seconds{quantile=\"0.95\"}"
threshold: 1800 # 30 minutes
severity: warning
- metric: "ci_cache_hit_rate"
threshold: < 0.7
severity: warning
- metric: "ci_test_flakiness_rate"
threshold: > 0.05 # 5% flaky tests
severity: critical
Tooling Recommendations by Category
| Category | Primary Tool | Alternatives | When to Use |
|---|
| Graph/Orchestration | NX Cloud | Turborepo, Bazel, Lage | NX works best with TS/JS monorepos |
| Caching | NX Remote Cache | GitHub Cache, S3 | NX Cloud for best integration |
| Security | Snyk + Semgrep | Trivy, OSV Scanner | Snyk for policies, Semgrep for custom rules |
| Testing | Jest/Vitest | Playwright, Cypress | Vitest for speed, Jest for compatibility |
| Deployment | Kubernetes + ArgoCD | Cloud Run, AWS ECS | K8s for complex dependency ordering |
| Observability | Datadog/New Relic | Prometheus + Grafana | Choose based on existing stack |
Migration Path from Simple to Advanced
Phase 1: Basic (Week 1-2)
- Implement graph detection (NX affected)
- Selective builds (all or nothing)
- Basic caching (node_modules)
- Single environment
Phase 2: Optimized (Week 3-4)
- Add test prioritization
- Implement multi-layer caching
- Basic security scanning (npm audit + gitleaks)
- Environment matrix for Node versions
Phase 3: Production-Ready (Week 5-6)
- Topological deployment ordering
- Comprehensive security gates
- Full observability integration
- Canary deployments with rollback
Phase 4: Advanced (Week 7-8)
- Predictive caching (warm cache based on PR changes)
- AI-assisted flaky test detection
- Cost optimization (spot instances for tests)
- Cross-repo dependency management
Common Pitfalls & Solutions
-
Cache Poisoning:
- Solution: Cache versioning with hash of build scripts
-
Dependency Graph Drift:
- Solution: Graph validation step (
nx reset && nx graph)
-
Long-Tail Latency:
- Solution: "Warm pool" of pre-built artifacts for common projects
-
Cold Start for New Projects:
- Solution: Baseline cache from similar projects
-
Security Scan Performance:
- Solution: Incremental scanning using previous scan baseline
This pipeline provides:
- 60-80% reduction in CI time for typical changes (via selective execution)
- Sub-5min feedback for most PRs (with cache warm)
- Zero-downtime deployments with automatic rollback
- Security compliance with automated triage
- Full observability from commit to production
Would you like me to elaborate on any specific component or provide implementation details for your particular tech stack?