# Incremental Xcode Builds via Derived Data Cache

Canonical: https://figment.so/blog/mac-derived-data-cache-incremental-build

Cache DerivedData keyed on runner OS, Xcode version and a hash of Package.resolved and Podfile.lock, skip Index.noindex, and save only after a successful build on the default branch.

**Cache the `DerivedData` directory between CI runs, keyed on `{runner-os}-xcode-{version}-{hash(Package.resolved + Podfile.lock)}`, exclude `Index.noindex`, and save the cache only after a successful build on the default branch.** On a persistent self-hosted Mac, restore and save are local disk copies instead of network transfers, which makes this cheap.

When an ephemeral CI runner starts fresh, Xcode recompiles every source file from scratch. A Swift build that took 8 minutes locally, where Xcode reused the previous session's modules, can take 18 minutes in CI. Persisting DerivedData with a correct key fixes that.

## Why does CI ignore Xcode's incremental build cache?

Because there is no previous DerivedData to compare against. Xcode's incremental build system checks file content hashes against the module dependency graph recorded in DerivedData. On an ephemeral runner every module is rebuilt. Even on a persistent runner, `git checkout` rewrites the working tree each run. Combined with a missing module cache, Xcode cannot prove modules are up to date and recompiles them.

Restoring DerivedData helps in two ways:

1. Previously compiled artifacts (`.swiftmodule`, `.o`, static archives) are present, so only files whose content hash changed recompile.
2. The Clang module cache is warm, so system and framework headers parse faster.

A cache produced by a different Xcode version is not safe to restore. The module binary format changes between major versions and can produce module-load errors, so the Xcode version must be part of the cache key.

## What is safe to cache in DerivedData?

`Build/Intermediates.noindex/` and `Build/Products/`. DerivedData lives at `~/Library/Developer/Xcode/DerivedData/` by default. For a project `MyApp`:

```
DerivedData/
  MyApp-<hash>/
    Build/
      Intermediates.noindex/   # .o files, .d dependency files, .swiftmodule
      Products/                # built .app, .framework, .xctest
    Index.noindex/             # SourceKit index (skip; large, unused by xcodebuild)
    Logs/
    info.plist
```

Skip `Index.noindex/`. It can reach several gigabytes on a large app, and `xcodebuild` does not consume it.

Pin DerivedData to a project-relative path so the cache is predictable:

```bash
xcodebuild build \
  -scheme MyApp \
  -destination 'generic/platform=iOS' \
  -derivedDataPath ./DerivedData \
  -showBuildTimingSummary
```

`-showBuildTimingSummary` prints the slowest build phases at the end of the log, which tells you whether DerivedData caching or linker tuning will help more.

## How do I design the cache key?

Invalidate exactly when cached products stop being valid:

```
{runner-os}-xcode-{xcode-version}-{hash(Package.resolved + Podfile.lock)}
```

| Component | Why |
|-----------|-----|
| `runner-os` | macOS version affects SDK headers and linker behavior |
| `xcode-version` | Module binary format differs between Xcode versions |
| `hash(Package.resolved)` | SwiftPM dependency tree changed |
| `hash(Podfile.lock)` | CocoaPods dependency tree changed |

Do not put `github.sha` in the primary key, because that creates a new cache per commit and defeats the purpose. Use `github.sha` only as a restore-key suffix fallback.

## How do I restore and save DerivedData in GitHub Actions?

Use split `restore` and `save` steps. The [GitHub Actions caching documentation](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows) confirms a 512-character key limit and a default 10 GB cache quota per repository. The [actions/cache repository](https://github.com/actions/cache) documents the split steps and the `cache-hit` output used below.

```yaml
# .github/workflows/ios-build.yml
name: iOS Build

on: [push, pull_request]

env:
  XCODE_VERSION: '16.2'
  DERIVED_DATA_PATH: ./DerivedData

jobs:
  build:
    runs-on: [self-hosted, macOS]
    steps:
      - uses: actions/checkout@v4

      - name: Select Xcode
        run: sudo xcode-select -s /Applications/Xcode_${{ env.XCODE_VERSION }}.app

      - name: Restore DerivedData cache
        id: cache-dd
        uses: actions/cache/restore@v4
        with:
          path: ${{ env.DERIVED_DATA_PATH }}
          key: ${{ runner.os }}-xcode-${{ env.XCODE_VERSION }}-${{ hashFiles('**/Package.resolved', '**/Podfile.lock') }}
          restore-keys: |
            ${{ runner.os }}-xcode-${{ env.XCODE_VERSION }}-

      - name: Build
        run: |
          set -euo pipefail
          xcodebuild build \
            -scheme MyApp \
            -destination 'generic/platform=iOS' \
            -derivedDataPath "${{ env.DERIVED_DATA_PATH }}" \
            -showBuildTimingSummary \
            | tee build.log

      - name: Save DerivedData cache
        if: success() && github.ref == 'refs/heads/main' && steps.cache-dd.outputs.cache-hit != 'true'
        uses: actions/cache/save@v4
        with:
          path: ${{ env.DERIVED_DATA_PATH }}
          key: ${{ runner.os }}-xcode-${{ env.XCODE_VERSION }}-${{ hashFiles('**/Package.resolved', '**/Podfile.lock') }}
```

Why this shape:

- Splitting `restore` and `save` lets you gate `save` on `success()` and on `github.ref`, so a failed or PR build never overwrites a good cache.
- The `restore-keys` prefix warm-starts the next build after a minor lock-file change.
- `cache-hit != 'true'` avoids rewriting an identical cache.
- This is an untested example, not a benchmark. Measure before you quote a speedup.

## How do I do this in Buildkite and GitLab CI?

For Buildkite on a persistent Mac, keep the cache on local disk. Buildkite artifacts move files between steps in one build, not across builds, so key a local directory on the lockfiles and Xcode version:

```bash
#!/usr/bin/env bash
set -euo pipefail

XCODE_VERSION=$(xcodebuild -version | awk 'NR==1{print $2}')
LOCKFILES=$(ls Package.resolved Podfile.lock 2>/dev/null || true)
LOCKFILE_HASH=$(cat $LOCKFILES 2>/dev/null | shasum -a 256 | awk '{print $1}')
CACHE_DIR="$HOME/.xcode-cache/$XCODE_VERSION/$LOCKFILE_HASH"
DERIVED_DATA="./DerivedData"

mkdir -p "$DERIVED_DATA"
if [[ -d "$CACHE_DIR" ]]; then
  rsync -a "$CACHE_DIR/" "$DERIVED_DATA/"
fi

xcodebuild build \
  -scheme MyApp \
  -destination 'generic/platform=iOS' \
  -derivedDataPath "$DERIVED_DATA" \
  -showBuildTimingSummary

# Only refresh the cache if the build succeeded (set -e handles failure).
rsync -a --delete \
  --exclude 'Index.noindex' \
  "$DERIVED_DATA/" "$CACHE_DIR/"
```

Add a weekly cron that prunes `~/.xcode-cache` entries older than N days to keep disk usage bounded.

For GitLab CI:

```yaml
build:
  tags: [mac]
  variables:
    DERIVED_DATA: "$CI_PROJECT_DIR/DerivedData"
  cache:
    key:
      files:
        - Package.resolved
        - Podfile.lock
      prefix: "xcode-16.2"
    paths:
      - DerivedData/Build/Intermediates.noindex/
      - DerivedData/Build/Products/
    policy: pull-push
  script:
    - set -euo pipefail
    - xcodebuild build -scheme MyApp -destination 'generic/platform=iOS' -derivedDataPath "$DERIVED_DATA" -showBuildTimingSummary
```

## Is persistent caching worth it on my project?

Measure it. Fill this in with your own numbers; the code above is an example, not a benchmark.

| Measurement | How to capture | Your value |
|-------------|----------------|-----------|
| Cold build wall time (T_cold) | `time xcodebuild build ...` on a clean DerivedData | _fill in_ |
| Warm build wall time (T_warm) | Same command after one successful cache save | _fill in_ |
| Cache restore overhead (T_r) | CI step timestamp delta for the restore step | _fill in_ |
| Cache save overhead (T_s) | Same for the save step | _fill in_ |
| Builds per workday (N) | PR + main runs in a typical day | _fill in_ |
| Net daily time saved | `N * (T_cold - T_warm - T_r)` | _calculate_ |

Worked cost example: suppose caching saves one engineer 30 minutes per day, and a billing month has 10 workdays, so 10 × 0.5 = 5 hours saved. An Apple Silicon Mac VM at $39 a month costs $39 ÷ 5 = $7.80 in hosting per saved hour. A Dedicated M4 Pro at $349 a month costs $349 ÷ 5 = $69.80 per saved hour. Compare that with your blended engineering cost per hour.

## When should I clear the cache on purpose?

On any change that makes old modules invalid:

- **Xcode upgrade.** Bump `XCODE_VERSION`, and the old cache key becomes unreachable.
- **Compiler flag change.** `OTHER_SWIFT_FLAGS`, optimization level or `-enable-experimental-feature` changes invalidate modules. Encode the relevant flag in the key, or accept one stale-cache rebuild.
- **Module load errors after restore.** Delete the cache entry (GitHub: Settings → Actions → Caches) and let the next run repopulate.
- **Large refactor or rename.** Bump a prefix (`v2-xcode-...`) to drop orphaned `.swiftmodule` files that would otherwise sit in the cache forever.

## Should the runner be persistent or ephemeral?

Persistent gives the largest payoff.

| Runner type | Cache benefit | Notes |
|-------------|---------------|-------|
| Persistent self-hosted Mac | Highest. Restore and save are local disk copies | Prune policy required to bound disk use |
| Ephemeral hosted runner | Moderate. Cache is uploaded and downloaded over the network each run | Network throughput and the 10 GB per-repo quota become the limits |
| Shared pool of Macs | Lower. Hit rate depends on routing the same repo to the same host | Consider a shared remote cache keyed the same way |

On a rented Mac the cache and the toolchain live on the same disk, so the Buildkite-style local `rsync` pattern above has the largest payoff. A persistent disk is a cache, not a backup.

## How much disk does each plan give a DerivedData cache?

Choose by Xcode version and disk. The [Apple Silicon Mac VM](/mac-hosting#apple-silicon-vm) ($39 a month, 65GB SSD) runs current Xcode, and the Dedicated M4 Pro ([$349 a month](/mac-hosting#dedicated-m4-pro), 512GB SSD) gives room for several large DerivedData caches and parallel builds. The [Intel Mac VM](/mac-hosting#intel-vm) ($25 a month, 80GB SSD) fits Xcode 26.3 or earlier on macOS Sequoia. Storage includes the OS, so budget the cache size and your prune policy against it. You run your own CI runner.

See [Automate tvOS App Builds in a CI Pipeline](/blog/mac-tvos-ci-build-pipeline) and [Automate watchOS App Builds in a CI Pipeline](/blog/mac-watchos-ci-build-pipeline) for sibling platform notes, and [Remote Xcode from Windows](/blog/mac-xcode-on-windows-remote-setup) if you also need a desktop endpoint on the same Mac.
