Sub topic 13
Reusing build state in CI
A fresh CI job starts with an empty workspace. No .tsbuildinfo file, no dist folder, and none of the state that makes incremental fast on your laptop. Every run then pays for a full parse, bind, check, and emit. This chapter shows how to carry that state from one CI run to the next.
This chapter assumes you have read the earlier chapters on incremental, .tsbuildinfo, composite projects, and tsc --build. You should also know how your CI system's cache step works, and the examples use GitHub Actions.
What there is to reuse
Two kinds of files carry build state between runs:
- The
.tsbuildinfofiles. These record the file list, a hash of each file's text, the dependency graph between files, and cached results such as diagnostics and the shape of each file's exports. tsc uses them to decide which files can be skipped. - The emitted outputs. These are the
.js,.d.ts, and.mapfiles inoutDir. For a composite project, the.d.tsfiles are also what downstream projects read instead of re-checking your source.
The two must travel together. A .tsbuildinfo file is a claim that "the outputs for this state already exist." If you restore the claim but not the outputs, tsc may believe the work is done when it isn't.
Why a cache can work on a fresh checkout
A fresh git clone gives every source file a new modification time. A cache based on timestamps would be useless there. TypeScript's incremental state avoids this problem by storing a hash of each file's content, so a restored .tsbuildinfo file still matches files whose text is unchanged.
Paths inside the file are stored relative to its own location. That lets the cache survive a move between runners whose checkout directories differ, such as /home/runner/work/app on one machine and /builds/app on another.
Build mode (tsc --build) also compares timestamps of inputs and outputs when it decides if a project is up to date. After a restore, your sources may look newer than the restored outputs. In that case tsc loads the .tsbuildinfo file, finds that the hashes still match, and does little work, often only updating output timestamps. Run --verbose to see which path each project took.
Choosing where the files live
Caching is easiest when all state sits in a few known directories. Set tsBuildInfoFile so the cache location is explicit instead of scattered next to each outDir:
{
"compilerOptions": {
"composite": true,
"rootDir": "src",
"outDir": "dist",
"tsBuildInfoFile": "./.cache/app.tsbuildinfo"
},
"include": ["src"]
}With this layout, each package has two directories to cache: dist and .cache. A single glob per package covers both. If you leave the default, the .tsbuildinfo file lands in outDir (or next to the tsconfig when there is no outDir), and you need to know that rule to cache it.
Add .cache and dist to .gitignore. They are build products, not source.
A cache step for GitHub Actions
The example below caches the state of a monorepo with packages under packages/. It restores the most recent cache, runs the build, and saves a new cache.
name: build
on:
push:
pull_request:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- name: Restore TypeScript build state
uses: actions/cache@v4
with:
path: |
packages/*/dist
packages/*/.cache
key: tsc-${{ runner.os }}-${{ hashFiles('package-lock.json', 'tsconfig*.json', 'packages/*/tsconfig*.json') }}-${{ github.sha }}
restore-keys: |
tsc-${{ runner.os }}-${{ hashFiles('package-lock.json', 'tsconfig*.json', 'packages/*/tsconfig*.json') }}-
tsc-${{ runner.os }}-
- name: Build
run: npx tsc --build packages/app --verbose
- name: Type check
run: npx tsc --noEmit -p packages/appThe key has three parts, and each has a reason.
runner.os. Outputs and paths can differ by platform. Do not share a cache between Linux and Windows jobs.- A hash of the lockfile and tsconfig files. The lockfile pins the TypeScript version and the
@typespackages. The tsconfig files hold the compiler options. A change to either one can change every result. github.sha. GitHub's cache entries are immutable, so a key that already exists is never overwritten. Putting the commit SHA in the key gives every run a new entry to save.
The restore-keys list is what makes the cache useful. No earlier run has the exact key of a new commit, so the cache would always miss without a fallback. The first restore-keys entry matches any earlier cache with the same lockfile and config hash, and GitHub picks the most recent one. The second entry is a broader fallback, used after a dependency or config change.
The flow in one picture
When a restored cache is wrong
Most failures come from a stale or mismatched cache. They look like one of three things.
| Symptom | Likely cause | Fix |
|---|---|---|
| Build is as slow as a cold build | The key never matches, or `restore-keys` is missing | Print the cache step's log. Check that the fallback prefix matches an earlier key |
| `dist` is missing or incomplete after the build | `.tsbuildinfo` was restored without its outputs | Cache `dist` and `.cache` together in one step |
| Results differ from a local clean build | A change not covered by the key, such as a generated file or environment-dependent option | Add the input to the hash, or build clean on the main branch |
| Cache grows without limit | A new entry is saved on every run | Restrict saving to the main branch, and rely on the host's eviction policy |
If you change the TypeScript version, tsc sees that the .tsbuildinfo file was written by a different compiler version and discards the state. The cache then costs you a restore but gives no speedup. Because the lockfile is in the key, a version bump moves you to a new hash prefix, so this only happens on the first run after the bump.
Protecting correctness
A cache is an optimization. It must never be able to hide an error. Two habits keep it safe.
First, treat the cache as disposable. Any run should give the same result with the cache deleted, only slower. If you have ever had to say "clear the CI cache to fix it," the key is missing an input.
Second, run a clean build somewhere. On the main branch, or nightly, build without restoring the cache. This catches problems the incremental state may be masking. A job like this also refreshes the cache from a known-good state:
# Clean build for the main branch or a nightly job
rm -rf packages/*/dist packages/*/.cache
npx tsc --build packages/app --force --verboseThe --force flag makes build mode treat every project as out of date, so nothing is skipped even if stale state is present.
Splitting checking from emit in CI
Chapter material on --noCheck and isolatedDeclarations combines well with caching. Because declaration emit can run without a full check, you can run two jobs in parallel:
- A declarations job that produces
.d.tsfiles withtsc --noCheck --declaration --emitDeclarationOnly --outDir dist. Downstream packages and publish steps depend on it. - A check job that runs
tsc --noEmitand reports type errors.
Only one of them needs to be on the critical path for downstream work. The check job can run beside the tests, and both jobs can use their own cache entries. Give them different cache key prefixes (tsc-emit- and tsc-check-), because they write different state.
Measuring the result
Do not assume the cache helps. Compare a cold run and a warm run with the diagnostics flag from earlier in the tutorial:
npx tsc -p packages/app --noEmit --extendedDiagnostics | grep -E "Check time|Total time|Files"In a warm run, check time should fall sharply when few files changed. If total time is unchanged, look at the restore step. A cache that is saved but never restored is the most common failure. Record cold and warm times in your CI logs for a few weeks so you can spot a regression in the cache hit rate.
Summary of the working model
- Cache
.tsbuildinfofiles and outputs together, in known directories set withtsBuildInfoFileandoutDir. - Key on the OS, the lockfile, and the tsconfig files, then add the commit SHA so each run can save.
- Use
restore-keysto restore the nearest earlier state. Never hash the sources into the key. - Keep the cache disposable, and run a periodic clean build with
--force. - Measure cold and warm runs with
--extendedDiagnostics.
Exercise
Your CI cache key is tsc-${{ hashFiles('src/**/*.ts') }} with no restore-keys. Builds are always slow even though the cache step reports a save on every run. Explain why, and give a corrected key and fallback.
Show answer
The key includes a hash of every source file, so any source change gives a new key that matches no earlier cache. With no restore-keys, the step has no fallback and restores nothing, so every build starts cold and then saves a cache nobody reuses. Use a key built from the OS, the lockfile, and the tsconfig files plus the commit SHA, for example tsc-${{ runner.os }}-${{ hashFiles('package-lock.json', 'tsconfig*.json') }}-${{ github.sha }}. Add restore-keys with the prefix tsc-${{ runner.os }}-${{ hashFiles('package-lock.json', 'tsconfig*.json') }}- so a run restores the most recent earlier state, and tsc compares file hashes to rebuild only what changed.
Exercise
A teammate caches only the .cache/app.tsbuildinfo file, not dist, to save space. After a restore, tsc -p . with incremental finishes in two seconds but dist is empty. Why did this happen, and what are two ways to fix it?
Show answer
The restored .tsbuildinfo file says the sources are unchanged and their outputs are already built, so plain tsc -p finds nothing to emit and writes no files. The outputs it believes exist were never restored. Fix it by caching dist together with the .tsbuildinfo file, or by building with tsc --build, which checks that outputs exist and rebuilds a project whose outputs are missing.