Caching Processed Images Between Builds
Build-time image optimization is one of the best things a static generator does: every image becomes a set of right-sized AVIF and WebP files with srcset, with no runtime service. It is also, on image-heavy sites, the slowest part of the build by a wide margin. AVIF encoding is expensive — several hundred milliseconds of CPU per variant at sensible quality settings — and a site with a couple of thousand photographs can ask for more than ten thousand variants. Locally, generators cache the results, so the second build is fast. In CI, every run starts from an empty workspace and encodes everything again.
This guide persists image caches between CI runs for Astro and Eleventy, designs cache keys that stay valid without growing forever, and measures the effect on a travel blog and a documentation site. It is part of Image Optimization Pipelines in Astro; the Hugo equivalent is Hugo Image Processing Cache in CI.
Prerequisites
- An Astro site using
astro:assetsor an Eleventy site using@11ty/eleventy-img. - GitHub Actions (or any CI with a directory cache).
- Images stored in the repository or fetched from a stable source at build time.
Where the Time Goes
The travel blog: 410 pages, 1,900 source photographs, each rendered at four widths in AVIF and WebP plus a JPEG fallback, about 11,000 variants.
| Build step | Cold build | Share |
|---|---|---|
| Image processing (sharp) | 5 min 31 s | 87% |
| Markdown and rendering | 31 s | 8% |
| Everything else | 18 s | 5% |
| Total | 6 min 20 s |
Measured on a GitHub Actions ubuntu-latest runner (4 vCPU) with hyperfine, three runs. With a warm local cache, the same build took 58 s.
Astro: Persist the Assets Cache
Astro stores optimized images in node_modules/.astro/assets (configurable with cacheDir) and checks it before encoding. Each cached file is keyed by the source content and the transform options, so it is safe to reuse across builds as long as the Astro and sharp versions do not change the output.
- uses: actions/cache@v4
with:
path: node_modules/.astro
key: astro-assets-${{ runner.os }}-${{ hashFiles('package-lock.json') }}-${{ hashFiles('src/assets/**', 'src/content/**/*.{jpg,jpeg,png,webp}', 'astro.config.mjs') }}
restore-keys: |
astro-assets-${{ runner.os }}-${{ hashFiles('package-lock.json') }}-
- run: npm run build
The key has three parts. The lockfile hash invalidates the cache when Astro or sharp are upgraded, since encoder changes can change output. The image and config hash identifies the exact set of inputs. The restore-keys prefix restores the most recent cache for the same dependencies even when images changed, so a pull request that adds three photos processes only those three and saves a new cache under the new key.
The node_modules/.astro directory also holds the content layer data store, so this one cache speeds up content parsing too, as covered in Incremental Builds in Astro with the Content Layer.
Eleventy: Persist the Image Output
eleventy-img skips processing when an output file for the same source and options already exists in outputDir, identified by a hash in the filename. Persist that directory — but not the whole _site, which would carry stale pages between builds:
// eleventy.config.js — write processed images to a cacheable directory, then copy
const IMG_CACHE = '.cache/img';
eleventyConfig.addShortcode('image', async (src, alt, sizes) => {
const meta = await Image(src, { widths: [480, 960, 1440, 1920], formats: ['avif', 'webp', 'jpeg'],
outputDir: IMG_CACHE, urlPath: '/img/', useCache: true });
return Image.generateHTML(meta, { alt, sizes, loading: 'lazy', decoding: 'async' });
});
eleventyConfig.addPassthroughCopy({ [IMG_CACHE]: 'img' });
- uses: actions/cache@v4
with:
path: .cache
key: eleventy-img-${{ hashFiles('package-lock.json') }}-${{ hashFiles('src/images/**') }}
restore-keys: eleventy-img-${{ hashFiles('package-lock.json') }}-
.cache also holds eleventy-fetch responses, so remote data and images cached with it benefit as well. On the documentation site (1,300 pages, 900 images), the cold build dropped from 4 min 5 s to 41 s warm.
Keeping the Cache From Growing Forever
Every deleted or replaced image leaves variants behind in a restored cache, and every change in widths or quality adds a new set. Over six months without pruning, the Astro assets cache on the travel blog grew from 740 MB to 2.1 GB, and restoring it took longer than the saving it provided on text-only builds.
Two measures kept it in check. First, a prune step after the build deletes cached files that the build did not use. Astro does not track this itself, so a small script compares the files referenced in dist/_astro with the cache directory by content hash and removes the rest; for Eleventy, anything in .cache/img not copied into _site/img is unused. Second, a weekly scheduled job builds from a cold cache and saves it, which resets accumulated cruft and verifies that cold builds still work. GitHub also evicts caches not accessed for seven days and caps each repository at 10 GB, which is a backstop rather than a strategy.
Remote Images
Images fetched from a CMS or an external URL at build time need two caches: the download and the processed variants. Astro caches remote image transforms in the same assets cache, keyed by URL; if the CMS can change an image without changing its URL, include a version or updatedAt in the URL, or the cache will serve an old variant. Eleventy's eleventy-fetch caches downloads with a duration (duration: '1d'), and eleventy-img then caches the processing. For CMS-heavy marketing sites, setting the fetch duration to match the publish rebuild frequency avoids re-downloading every image on every webhook build, as discussed in Choosing an SSG for a Marketing Site with Non-Technical Editors.
Verifying the Cache Is Doing Its Job
A cache that silently stops hitting is worse than no cache, because everyone assumes builds are fast for a reason. Both sites log a one-line summary at the end of the build — variants requested, variants served from cache, variants encoded — and write it to the job summary. A build that encodes thousands of variants after a text-only change is an immediate signal that the key or the restore step broke. The same numbers feed the build-time trend described in Measuring Build Time Regressions in CI, which is how the team noticed, months later, that a dependency upgrade had invalidated the cache on every build by changing a default quality setting.
Measured Impact
| Measure | No image cache in CI | Cached (warm) |
|---|---|---|
| Astro travel blog build, text-only change | 6 min 20 s | 58 s |
| Astro build, 3 photos added | 6 min 20 s | 1 min 06 s |
| Eleventy docs build, text-only change | 4 min 05 s | 41 s |
| Monthly CI minutes (both sites) | 3,900 | 820 |
| Cache size after 6 months (Astro, pruned) | — | 780 MB |
| Preview deploy wait for writers, median | 7 min 10 s | 1 min 50 s |
Pitfalls & Rollback
- Commit SHA in the cache key. Creates a new multi-gigabyte cache per commit; key on inputs.
- No dependency hash in the key. A sharp or Astro upgrade can change output; include the lockfile hash.
- Caching the whole output directory. Stale pages survive between builds; cache only image output.
- Never pruning. The cache grows until restoring costs more than encoding.
- Rollback: remove the cache step; builds are slower but produce identical output, because generators always process missing variants.
Conclusion
Image processing dominates cold builds on image-heavy static sites, and generators already know how to reuse their own work. Persist Astro's node_modules/.astro or Eleventy's image output between CI runs, key the cache on image inputs, configuration and dependency versions with a prefix fallback, prune unused variants, and reset weekly. On these sites that turned six-minute builds into one-minute builds and cut monthly CI time by nearly 80%.
FAQ
Where does Astro cache optimized images?
In node_modules/.astro/assets by default for local builds, keyed by the source image and the transform options. Persisting that directory between CI runs lets the build copy existing variants instead of encoding them again.
Where does Eleventy Image cache output?
eleventy-img writes processed files to its outputDir and skips work when an output file for the same source hash and options already exists. With useCache and a persisted output or cache directory, repeat builds reuse previous results.
What should the CI cache key be?
A hash of the image sources and the image configuration, such as widths, formats and quality, plus the tool version, with a prefix restore key so a partial match still restores most variants. Keys that include the commit SHA create a new cache on every build.
How much time does image caching save?
On a 410-page Astro site with 1,900 images producing about 11,000 variants, a cold build took 6 minutes 20 seconds and a warm build 58 seconds. Eleventy on a similar site went from 4 minutes 5 seconds to 41 seconds.
Related
- Parent: Image Optimization Pipelines in Astro — the full image pipeline.
- Hugo Image Processing Cache in CI — the same approach in Hugo.
- Sharing Build Cache Across CI Runners — cache strategy in general.
- Blur-Up Placeholders with LQIP — placeholders generated in the same cached step.
- Build Caching on Netlify and Vercel — when the host runs the build.