What does GitHub merge queue actually test in an Nx monorepo?

When a PR enters the merge queue, GitHub does not retest the PR branch. It creates a temporary merge group commit on a branch named gh-readonly-queue/<base-branch>/.... That commit contains three things: the current tip of the base branch, every PR ahead of it in the queue, and the candidate PR. Required status checks must pass on this commit before GitHub fast-forwards the base branch to it.

This changes what your CI has to target. A workflow that checks out the PR head, or computes nx affected against the PR's original merge base, validates a state that will never exist on main. The code that will actually land is the merge group commit, so CI must check out that commit. Nx must also diff it against the queue's real base, which is the base branch commit the group was built on top of. If you use a stale base, the affected set can miss projects that changed in PRs ahead in the queue. It can also pull in projects that already passed.

The queue exists to catch semantic merge conflicts. For example, PR A renames an exported function in a shared library. PR B, opened earlier, adds a new caller of the old name in a different app. Each PR passes its own CI, and Git merges them without a textual conflict. Together, they break the build. A merge queue catches this because it builds and tests the combination.

The teams that benefit most have high PR volume landing on one shared branch. In a busy Nx workspace, many PRs touch the same libraries, and PR-only CI regularly approves changes that are no longer valid by the time they merge.

+------------------+   +------------------+   +------------------+
| main @ base SHA  |   | PRs ahead in the |   | candidate PR     |
| (queue base)     |   | queue (A, B, ..) |   | (C)              |
+--------+---------+   +--------+---------+   +--------+---------+
         |                      |                      |
         +----------------------+----------------------+
                                |
                                v
          +-------------------------------------------+
          | merge group commit (temporary)            |
          | branch: gh-readonly-queue/main/...        |
          | = base tip + PRs ahead + candidate        |
          +---------------------+---------------------+
                                | merge_group event
                                v
          +-------------------------------------------+
          | CI: check out the merge group commit      |
          | nx affected --base=<queue base SHA>       |
          |             --head=<merge group SHA>      |
          +---------------------+---------------------+
                                |
                 +--------------+--------------+
                 |                             |
                 v                             v
        +-------------------+        +-------------------+
        | checks pass:      |        | checks fail:      |
        | main fast-        |        | PR leaves queue,  |
        | forwards to group |        | group is rebuilt  |
        +-------------------+        +-------------------+

GitHub merge queue builds a temporary merge group commit from the base tip, the PRs ahead in the queue, and the candidate PR. CI runs on that commit, and Nx affected diffs it against the queue's real base SHA instead of the PR head.

How do you trigger Nx CI on the merge_group event?

Start with the workflow trigger. GitHub creates a temporary branch for each merge group and fires a merge_group event against it. Your existing pull_request trigger never sees that branch. Add merge_group to the on: block next to pull_request, typically with types: [checks_requested], and keep both triggers in the same workflow file. That way one set of job definitions serves both paths.

Keeping one file matters because of how required status checks work. Branch protection matches checks by job name, and the merge queue waits for every required check to report on the merge group's commit. If a required job only runs on pull_request, it never starts for the merge group. The queue then sits until it times out, and the entry gets removed. Every job you mark as required must run, or at least report, on both events.

Be careful with if: conditions that skip jobs per event. A job that starts and is skipped by an if: reports a status, while a job that never starts reports nothing. Branch protection can treat these two cases differently. Before you make such a check required, open a test PR, push it through the queue, and confirm the check resolves the way you expect.

Finally, set fetch-depth: 0 on actions/checkout. The default checkout is a single-commit shallow clone. Without the history, Nx cannot find the base commit, so nx affected either fails outright or computes a merge base from incomplete history. The second case is worse because CI stays green while it tests the wrong set of projects.

name: CI

on:
  pull_request:
  # The merge queue fires this event against its temporary merge-group branch
  merge_group:
    types: [checks_requested]

jobs:
  # Branch protection matches on this job name. It runs on both events,
  # so the queue always gets a status for the merge group's commit.
  ci:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          # Full history so Nx can find the base commit.
          # A shallow clone can fail or produce a wrong affected set.
          fetch-depth: 0

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm

      - run: npm ci

      # Pick the base SHA from whichever event triggered the run.
      # github.sha is the commit under test in both cases.
      - name: Run affected targets
        env:
          NX_BASE: ${{ github.event_name == 'merge_group' && github.event.merge_group.base_sha || github.event.pull_request.base.sha }}
          NX_HEAD: ${{ github.sha }}
        run: npx nx affected -t lint test build --base="$NX_BASE" --head="$NX_HEAD"

A single workflow that runs the same required ci job on both pull_request and merge_group, checks out the full history, and passes the correct base and head SHAs to nx affected for each event.

How do you compute nx affected base and head for a merge group?

Each event type has its own correct comparison range, so the step that sets --base and --head has to check github.event_name before choosing values.

On pull_request, Nx should compare the PR head against the point where the branch diverged from the target branch. Pass the target branch ref (for example origin/main) as --base, and Nx computes the merge base itself. Pass the PR's head commit as --head. Using the merge base keeps commits that landed on main after the branch was cut out of the affected set.

On merge_group, the event payload supplies both values directly. github.event.merge_group.base_sha is the tip of the target branch the group was built on. github.event.merge_group.head_sha is the commit on the temporary queue branch. That commit contains the target branch, every PR queued ahead, and the current PR. Because base_sha is an ancestor of head_sha, Nx has no merge base to work out, and the range is unambiguous.

A single step can branch on the event name, export NX_BASE and NX_HEAD, and let later steps pass them to nx affected.

pull_request merge_group
--base Merge base with target branch merge_group.base_sha
--head PR head commit merge_group.head_sha
Changes included This PR only Queued PRs ahead + this PR

The merge group's affected set is often larger than the PR's own set, and this is intended. The queue exists to test your change combined with the changes that will land just before it. If two PRs each pass alone but break a shared library together, only the wider range will catch the failure.

on:
  pull_request:
  merge_group:

jobs:
  affected:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # full history so Nx can resolve the merge base and both SHAs

      - name: Derive Nx base and head
        env:
          EVENT_NAME: ${{ github.event_name }}
          PR_BASE_REF: ${{ github.event.pull_request.base.ref }}
          PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
          MQ_BASE_SHA: ${{ github.event.merge_group.base_sha }}
          MQ_HEAD_SHA: ${{ github.event.merge_group.head_sha }}
        run: |
          if [ "$EVENT_NAME" = "merge_group" ]; then
            # Target branch tip the group was built on -> temp queue branch commit.
            # Includes every PR queued ahead plus this one.
            echo "NX_BASE=$MQ_BASE_SHA" >> "$GITHUB_ENV"
            echo "NX_HEAD=$MQ_HEAD_SHA" >> "$GITHUB_ENV"
          else
            # Pass the target branch ref; Nx computes the merge base itself,
            # so commits that landed on the target after branching are excluded.
            echo "NX_BASE=origin/$PR_BASE_REF" >> "$GITHUB_ENV"
            echo "NX_HEAD=$PR_HEAD_SHA" >> "$GITHUB_ENV"
          fi

      - run: npm ci

      - name: Run affected targets
        run: npx nx affected -t lint test build --base="$NX_BASE" --head="$NX_HEAD"

A single GitHub Actions step branches on github.event_name to export NX_BASE and NX_HEAD: on merge_group it uses merge_group.base_sha and merge_group.head_sha, and on pull_request it uses the target branch ref (so Nx computes the merge base) and the PR head commit.

How should you split work between PR CI and merge queue CI?

That wider range is also expensive, so don't run everything twice. The pull request run gives the author fast feedback. The merge queue run decides what lands on main.

Stage Trigger Runs Purpose
PR CI pull_request lint, unit tests, nx affected build Fast feedback while the author is still iterating
Queue CI merge_group nx affected build, test, e2e over the merge group range Authoritative gate before the commit reaches main

Gate the slow jobs, such as e2e suites and integration tests against real services, with if: github.event_name == 'merge_group'. Pull requests stay quick, and the queue still runs the full check.

The computation cache stops the queue from doubling your runner bill. Nx hashes each task's inputs: source files, dependency outputs, configuration, and declared environment inputs. When a project's inputs in the merge group commit match its inputs on the PR's head commit, the queue gets a cache hit and replays the stored output. This works only if the cache is shared between runs, either a remote cache or a persisted local cache directory. A miss happens only when the combined changes actually touched that project's inputs, which are exactly the tasks worth re-running.

That reuse carries a trust problem. If PR runs can write to the shared cache, a PR from a fork or a compromised branch could store a poisoned artifact. The queue would then accept it as a passing result. To prevent this, decide who can write to the cache. A common pattern is read-only access for PR contexts and read-write access only for queue and main runs. Then queue runs reuse only entries produced by trusted pipelines. You lose some hits, but a cached result can no longer be planted.

name: CI
on:
  pull_request:
  merge_group:
  push:
    branches: [main]
jobs:
  ci:
    runs-on: ubuntu-latest
    env:
      # Compare against the queue's base, the PR base, or the previous main commit
      NX_BASE: ${{ github.event.merge_group.base_sha || github.event.pull_request.base.sha || github.event.before }}
      NX_HEAD: ${{ github.event.merge_group.head_sha || github.sha }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # nx affected needs history to diff base..head
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
      - run: npm ci
      # Every run may READ the Nx cache, so identical task inputs become cache hits
      - uses: actions/cache/restore@v4
        with:
          path: .nx/cache
          key: nx-${{ github.sha }}
          restore-keys: nx-
      # Fast checks run everywhere; unchanged projects replay from cache
      - run: npx nx affected -t lint test build --base=$NX_BASE --head=$NX_HEAD
      # Expensive suites run only in the authoritative queue run
      - if: github.event_name == 'merge_group'
        run: npx nx affected -t e2e --base=$NX_BASE --head=$NX_HEAD
      # Only trusted contexts WRITE the cache; PR runs (including forks) never save
      - if: github.event_name != 'pull_request'
        uses: actions/cache/save@v4
        with:
          path: .nx/cache
          key: nx-${{ github.sha }}

A single GitHub Actions workflow runs lint, test, and build for affected projects on pull_request, adds e2e only on merge_group, and persists the local Nx cache so every run can read it but only merge queue and main runs can write to it.

How much does a merge queue cost in CI runner time?

Every PR now runs CI at least twice: once on pull_request and once on merge_group. Whether that doubles your bill depends on how much of the queue run Nx can replay from cache and how often groups fail.

GitHub runs each group as a single merge_group build. Build concurrency sets how many groups can be built at the same time. Group size sets how many PRs ride in each group. If the group passes, one run lands several PRs. If it fails, every PR in that group, and in any group queued behind it, is invalidated and rebuilt. You also have to work out which PR caused the failure.

Setting Higher value when green Higher value when red
Group size Fewer runs per merged PR More PRs rebuilt; harder attribution
Build concurrency Shorter queue wait More speculative runs discarded

Illustrative estimate (assumed numbers, not a benchmark)

Formula: queue minutes/day = (PRs ÷ group size) × run minutes × (1 − cache hit rate) × (1 + group failure rate)

The assumed inputs are:

  • 40 PRs/day
  • Group size 4
  • 30 uncached minutes per group run
  • 50% cache hit rate
  • 20% group failure rate

Plugging those in: (40 ÷ 4) × 30 × 0.5 × 1.2 = 180 runner minutes/day, added to your existing PR CI.

With group size 1 and the same other inputs, the result is 40 × 30 × 0.5 × 1.2 = 720 minutes. With group size 1, though, a failure only rebuilds one PR, so in practice the failure multiplier is lower.

Don't plan around these numbers. Track queue wait time, runner minutes per merged PR, and group failure rate for a few weeks. Then tune group size and concurrency against your own data.

When should you avoid an affected-only merge queue?

Affected analysis is only as accurate as the project graph, and the merge queue is where an inaccurate graph causes the most damage. A PR that skips a broken project in the queue merges straight to main. Three gaps are common:

  • Undeclared dependencies. A service may read a shared schema at runtime, or call another project's generated client, without importing it. Nx never sees that edge.
  • Files outside any project. Scripts, fixtures, or deployment config at the repo root may not map to any project, so changing them affects nothing.
  • Dynamic imports. A computed import path can't be resolved statically, so the dependency is invisible.

Root configuration works the other way. Changes to the lockfile, nx.json, or the root tsconfig typically mark every project as affected, so a dependency bump turns the merge group into a full build. That is correct behavior, but you should expect it. To keep affected accurate rather than merely fast, audit namedInputs so that root files your builds depend on are included as inputs. Add implicitDependencies for any edge that the code doesn't show.

Flaky tests hurt more in a queue than on a PR. When a group fails, GitHub removes the PR it blames and rebuilds every group queued behind it. A single flaky failure can eject a correct PR and force several reruns, which stalls everyone's merges.

Skip the affected-only merge queue in these cases:

  • PR volume is low enough that main rarely goes red from semantic conflicts.
  • The repo is small enough that a full build is already quick.
  • The test suite is flaky enough that the queue would spend most of its time on reruns.

What are the alternatives to Nx affected in the merge queue?

Affected-only queue CI is one of four reasonable setups. The right choice depends on how expensive a full build is and how much breakage on main your team will tolerate.

Option What it catches Cost Fits when
Full suite in the queue Semantic conflicts, plus anything the project graph misses Every queue entry pays for a full build Small-to-medium repos with full builds of a few minutes
PR-only affected CI, no queue Problems inside each PR, checked against a possibly stale base Lowest Low PR volume where two PRs rarely touch related projects
Affected in queue + periodic full build on main Conflicts in queue; graph gaps within hours Queue stays cheap, plus one full run per interval Large repos with high PR volume
Require up-to-date branches Conflicts, by forcing a rebase and rerun before merge Developer time and repeated CI runs Few merges per day

Running the full suite in the queue is the simplest and safest choice. A missing implicit dependency or an undeclared input cannot hide, because nothing is skipped. The cost grows with repo size, and in a busy monorepo the queue becomes the bottleneck.

The periodic backstop accepts a trade-off: main can be red between full runs because of a graph mistake. It works when your team can tolerate that and has someone who will fix the graph promptly when it happens.

Requiring up-to-date branches gives the same correctness as a merge queue without parallelism. Each merge invalidates every other open PR, so it stops scaling once more than a handful of PRs merge each day.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

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

Applied to nx github merge queue, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

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

Want to try it? Start at oneenv.io.