plaintext.brennan.day

Rolling the Boulder Up: Making Eleventy Build 2.6× Faster

| technical-tutorials | 1,719 words
TAGS: eleventy, javascript, netlify, technical, tutorial, IndieWeb, personal site
ORIGINAL: https://brennan.day/rolling-the-boulder-up-making-eleventy-build-2-6-faster/

It's been a while since my last technical post, and once again we're here trying to optimize and increase build times of my ever-increasingly bloated little blog.

Back in May, I wrote a post about making my Eleventy build five times faster by fixing an offensive git log implementation. In July, I wrote about cutting my Netlify build time in half by caching API responses, removing a dead Discord webhook, and moving post-deploy work out of the build window.

These fixes made significant improvements, as I rolled the boulder of optimization up the hill of self-created code debt. But since then, I kept writing and coding. Brennan.day continues to grow, with more images, tags, archive pages, templates, and clever features I felt were really, really needed.

As a result, we're back at the bottom of the hill and starting again. My local production build now at twenty seconds and Netlify builds at around two and a half minutes. You must choose to imagine me happy.

Let's begin.

Measure the Build Flags

It is a mistake to treat "the build" as a monolithic, singular blob. Somehow, over time, my npm run build command had become:

"build": "eleventy --incremental && npx pagefind --site _site && node scripts/generate-json-feed.js && node scripts/generate-science-feed.js && node scripts/generate-honeypot.js"

It builds Eleventy, then Pagefind search indexing, and then a few additional scripts I've hacked on. I realized it all adds up:

Stage Current Times
Full npm run build 20.67s
Eleventy 14.83s cold / 12.32s warm
Pagefind 2.80s
Passthrough copying 823 files, ~580ms

Let's see what we can do to improve those times!

Font Awesome Parsing Every HTML Document

To start, I use the official @11ty/font-awesome plugin. It works great. I write:

<i class="fa-solid fa-terminal"></i>

And the plugin turns it into an SVG reference while collecting the symbol into a per-page bundle. The problem is that the plugin's transform uses posthtml to parse and transform every HTML document. Not just documents with icons. Not just the icon tags. Every page in full! And this is after Eleventy had already rendered it.

There are over seven hundred HTML files that make up this site, and so there is a lot of code being parsed for no reason. I kept the plugin, but disabled the transform:

eleventyConfig.addPlugin(pluginFontAwesome, { transform: false });
eleventyConfig.addPlugin(require("./config/fontawesome-fast.js"));

I then wrote a narrower custom transform in config/fontawesome-fast.js. This uses the plugin's code for icon metadata and SVG generation, but now it only looks for <i> elements with Font Awesome classes:

eleventyConfig.addTransform("fontawesomeFast", function(content, outputPath) {
  if (!outputPath || !outputPath.endsWith(".html") || typeof content !== "string" || !content.includes("<i")) {
    return content;
  }

  // Replace <i class="fa-solid fa-terminal"></i> with:
  // <svg ...><use href="#fas-terminal" xlink:href="#fas-terminal"></use></svg>
  // and register the symbol with Eleventy's bundle manager.
});

Beyond this, the script also parses attributes, merges default accessibility attributes, caches icon metadata, caches generated SVG fragments, skips icons inside comments, scripts, and styles, etc.

While this works well for my small site, I would not blindly copy this idea if your site accepts arbitrary HTML from strangers.

slugify Needed a Fast Path, Not Just a Cache

In my first performance post, I memoized slugify[^1], but it didn't really help anything, since most calls were unique strings.

[^1]: Memoization is a caching technique where a function stores the result of an expensive computation the first time it runs, then returns the stored result when called again with the same input. It only helps when the same inputs repeat often; if every input is unique, you mostly only gain the overhead of maintaining a cache.

This time, I looked at how the slugify library itself was doing expensive transliteration work for no reason. Nearly all strings were already regular ASCII, so it was pretty silly to have a Unicode transliteration pipeline for each build. The new filter has a cache and a fast path:

eleventyConfig.addFilter("slugify", (str, opts) => {
  str = "" + str;
  const key = str + "\0" + (opts ? JSON.stringify(opts) : "");
  if (_slugifyCache.has(key)) return _slugifyCache.get(key);

  let result;
  if (!opts && /^[\x00-\x7F]*$/.test(str)) {
    result = str
      .replace(/&/g, " and ")
      .replace(/[\^`]/g, "")
      .toLowerCase()
      .replace(/([a-zA-Z\d]+)'([ts])(\s|$)/g, "$1$2$3")
      .replace(/[^a-z\d]+/g, "-")
      .replace(/\\/g, "")
      .replace(/-{2,}/g, "-")
      .replace(/^-|-$/g, "");
  } else {
    result = _origSlugify(str, opts);
  }

  _slugifyCache.set(key, result);
  return result;
});

This preserves the behaviour URLs depend on (eg. possessive-apostrophes) while Unicode strings fall back to the original implementation.

Lots of Small Memoization

I admit, it was difficult to find any major, specific reasons for slow down, or opportunities to speed things up. Instead, I started looking at the dozens of small repeated calculations. A lot of performance work is like this, and it is a lot more annoying, since it means actually doing work.

I memoized date-formatting filters by their input timestamp or ISO string. I cached readingTime by content. I changed totalWords and filterByTag to use WeakMaps keyed by the collection arrays themselves. As a result, repeated lookups for the same collection no longer repeat the same scan:

const totalWordsCache = new WeakMap();
const filterByTagCache = new WeakMap();

The charts data file was also foolishly calculating per-post word counts separately for daily, weekly, monthly, yearly, tag, and reading-time statistics. Now, it calculates each post's template word count once, stores it in a Map and reuses it, hurray!

const postWordCounts = new Map();

posts.forEach(post => {
  const words = post.templateContent
    .replace(/<[^>]*>/g, "")
    .split(/\s+/)
    .filter(Boolean).length;

  postWordCounts.set(post, words);
});

Thumbnail Metadata Needed Correctness Before Speed

I already had a disk cache for thumbnail metadata from my July post, avoiding recomputing the eleventy-img metadata across builds, but there was a problem with this: the cache key was based on the source path and width, rather than the contents or modification time of the source image. In other words, if I replaced an image in place, the cache would have the metadata for the old version still.

Now, the cache entry stores both the file's modification time and size:

const sourceStats = fs.statSync(fullPath);
const sourceStamp = `${sourceStats.mtimeMs}:${sourceStats.size}`;

if (cachedData.sourceStamp === sourceStamp) {
  metadata = cachedData.metadata;
}

In addition, I also added an in-memory cache. This allows repeated references to the same image within a build to not use the disk cache repeatedly. After populating the new cache, the thumbnail shortcode cost dropped from hundreds of milliseconds to ~50ms.

Stop Copying Unchanged Images

Having a full-sized featured image for each of my posts has resulted in my src/assets/images directory becoming very large at this point. It would make a lot of sense at this point to use a CDN, but I am lazy and nothing is broken or anything, so it is still fine for the time being.

But Eleventy was copying hundreds of image files on every build, even if they hadn't actually changed. That's fine for local builds, but it's needless work when generating my site on Netlify. I added a passthrough-copy filter which compares the source and destination file sizes and modification times:

function unchangedCopyFilter(inputDir, outputDir) {
  const inputRoot = path.resolve(inputDir);
  const outputRoot = path.resolve(outputDir);
  return (relativePath) => {
    try {
      const sourcePath = path.join(inputRoot, relativePath);
      const outputPath = path.join(outputRoot, relativePath);
      const sourceStats = fs.lstatSync(sourcePath);
      if (sourceStats.isDirectory()) return true;
      const outputStats = fs.lstatSync(outputPath);
      return !(
        sourceStats.size === outputStats.size &&
        Math.abs(sourceStats.mtimeMs - outputStats.mtimeMs) < 2
      );
    } catch {
      return true;
    }
  };
}

Then:

eleventyConfig.addPassthroughCopy("src/assets/images", {
  filter: unchangedCopyFilter("src/assets/images", "_site/assets/images"),
});

This change resulted in over 800 images being processed down to just 40.

Set Pagefind to English

This is an actual useful tip: if it isn't explicitly set, Pagefind search spends time detecting the language of indexed pages. Nearly all of my website is in English, except my French posts, and so I added the flag:

npx pagefind --site _site --force-language en

As a result, Pagefind's processing time is cut in half! From 2.6-2.8 seconds down to 1.0-1.5 seconds. The tradeoff is that my small number of French posts will now be indexed with English language rules. I am accepting that for now, but it is a tradeoff rather than a free lunch.

Fixing Malformed HTML

While doing all this tinkering, I discovered my dropCapFirstWord filter would produce malformed HTML when the first word of a post was inside inline formatting, like <strong>.

The old output was being fixed by the later HTML parsing. Once I improved the transform pipeline, the malformed structure became visible to fix.

Making Improvements for Netlify Builds

Local timing is only half the story. Netlify builds were far slower, averaging around 2 minutes, 30 seconds. A recent production build looked like this:

build.command completed in 1m 34.2s
Eleventy wrote files in 88.7s
Pagefind finished in 3.3s
post-processing completed in 22.8s

My computer is faster than whatever processing power is being allocated from Netlify's servers to my site, but there were fixable issues.

For example, Netlify already restores dependency caches like node_modules. In fact, the dependency cache archive was nearly 1GB. But .cache/, .eleventy-cache/, and _site/ are gitignored, which meant every Netlify build started without:

Builds only minutes apart were printing lines like:

Fetching status.lol data...
Successfully fetched 108 statuses
Fetched 63 guestbook entries from Netlify

Even though those responses were configured to cache for 24 hours, they were caching only for one build container.

Writing a Tiny Netlify Cache Plugin

Netlify build plugins have access to cache utilities, so I added netlify/plugins/build-cache/index.js:

const CACHE_PATHS = [
  ".cache",
  ".eleventy-cache",
  "_site/assets/images/thumbnails",
];

module.exports = {
  async onPreBuild({ utils }) {
    await utils.cache.restore(CACHE_PATHS);
  },

  async onPostBuild({ utils }) {
    await utils.cache.save(CACHE_PATHS);
  },
};

And registered it in netlify.toml:

[[plugins]]
  package = "./netlify/plugins/build-cache"

There is a tradeoff here. _site/assets/images/thumbnails is currently around 109MB. Saving it should avoid a lot of repeated sharp image work, but it also makes the cache archive larger.

Updating Node

Since I hadn't updated this in a year, Netlify was pinned to Node 20.9.0. Node 20 is end-of-life now, and Node 24 is the active LTS line. I updated the build environment to:

NODE_VERSION = "24"

Solving the Blob Mystery From July

In the July post, I ended with a mystery. The Netlify logs contained:

git@gitlab.com: Permission denied (publickey).
fatal: Could not read from remote repository.
fatal: could not fetch ... from promisor remote

At the time I suspected Netlify's blobless clone. That suspicion turned out to be right, with one missing detail. My timestamp cache runs git log --name-only across the repository history. By default, Git may perform rename detection while generating those file lists. Rename detection can require comparing file contents.

In a blobless clone, some of those blobs are not local, so Git attempts to fetch them lazily from the promisor remote. On Netlify, that remote is an SSH GitLab URL which the build container cannot authenticate to. That's why there was this weird SSH failure in the middle of a build that otherwise had nothing to do with SSH. The fix:

const readGitLog = (range = "") => execSync(
  `git log --no-renames --format="%x01%at%x01%s" --name-only ${range}`,
  { encoding: "utf8", maxBuffer: 20 * 1024 * 1024 }
);

--no-renames fixes this. I also made the timestamp cache incremental. Instead of deleting the cache when HEAD changes, it now checks whether the cached commit is an ancestor of the current commit, and only parses the new range:

execSync(`git merge-base --is-ancestor ${cachedHead} ${currentHead}`);
parseGitLog(readGitLog(`${cachedHead}..${currentHead}`));

The Results?

After all of that:

Stage Before After
Full npm run build 20.67s ~8.0s
Eleventy 14.83s cold / 12.32s warm ~4.0-4.3s
Pagefind 2.80s ~1.0-1.3s
Passthrough copying 823 files, ~580ms 39 files, ~18ms

Not bad for a personal website whose primary production workload is me writing too many words and pressing save.

Final Thoughts

Be sure that caching is doing its job! Ensure any shortcuts or assumptions being made are validated (or invalidated).

There are still things I need to figure out. The half gigabyte of images, for example. And also how the dependency cache archive is nearly 1GB, with thousands of packages in node_modules. That makes cache restore and save inherently expensive.

The benchmarks will become slower again as I write more posts and add more functionality. New filters, new data sources, new complexity. I'm sure I'll be back here in another few months with part four. I must choose to imagine I am happy :)