iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐢

Performance degradation due to Next.js Automatic Webfont Optimization

に公開
2024/01/22

TL;DR

  • A website built with Next.js was experiencing performance issues under certain circumstances.
  • The cause of the problem was that the HTML size had significantly bloated due to the Automatic Webfont Optimization feature.
  • As a solution, we switched to using next/font to optimize the web font loading method and reduce the HTML size.

Project-Specific Context

  • The Next.js application is deployed on ECS for test operations.
  • It supports multiple languages (Japanese, Korean, Chinese (Traditional and Simplified)).
  • Development originally started with Next.js v12, and the update to v13 was finally completed last month.

Issues Encountered

Our team had the opportunity to perform performance measurements on a specific website built with Next.js. We unexpectedly noticed that IPC (Inter-Process Communication) related errors were occurring on the server side, even though the request count was not particularly high.

(Part of the errors that occurred)
TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11457:11)
    at async invokeRequest (/home/snaka/xxxxx/node_modules/next/dist/server/lib/server-ipc/invoke-request.js:17:12)
    at async invokeRender (/home/snaka/xxxxx/node_modules/next/dist/server/lib/router-server.js:254:29)
    at async handleRequest (/home/snaka/xxxxx/node_modules/next/dist/server/lib/router-server.js:447:24)
    at async requestHandler (/home/snaka/xxxxx/node_modules/next/dist/server/lib/router-server.js:464:13)
    at async Server.<anonymous> (/home/snaka/xxxxx/node_modules/next/dist/server/lib/start-server.js:117:13) {
  cause: Error: read ECONNRESET
      at TCP.onStreamRead (node:internal/stream_base_commons:217:20) {
    errno: -104,
    code: 'ECONNRESET',
    syscall: 'read'
  }
}

Another error different from the one above:

cause: SocketError: other side closed
at Socket.onSocketEnd (/app/node_modules/next/dist/compiled/undici/index.js:1:63301)
at Socket.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1359:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  code: 'UND_ERR_SOCKET',
  socket: {
    localAddress: '127.0.0.1',
    localPort: 45850,
    remoteAddress: undefined,
    remotePort: undefined,
    remoteFamily: undefined,
    timeout: undefined,
    bytesWritten: 2937,
    bytesRead: 87753
  }
}

Further investigation revealed that the HTML built by Next.js was abnormally large. Specifically, the size was about 2MB, which was significantly larger compared to the HTML size of a typical web page.

Cause of the Problem

To solve the performance issues occurring on our website, we first started a series of investigations to pinpoint the cause. During load testing, it became clear that network bandwidth was a bottleneck, and we were particularly concerned about the fact that the download of a single HTML file was significantly consuming bandwidth.

Further investigation into the HTML revealed that it contained a massive amount of font definitions (@font-face rules). These definitions did not exist in the original source code and were being inserted automatically by some mechanism. Further research revealed that these font definitions originated from the Automatic Webfont Optimization feature introduced in Next.js v10.2.

Reference: Next.js 10.2 Release Notes

The problematic part was the following description in _document.tsx:

// _document.tsx
<Head>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100;300;400;500;700;900&display=swap" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@100;300;400;500;700;900&display=swap" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@100;300;400;500;700;900&display=swap" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100;300;400;500;700;900&display=swap" />
</Head>

Sample code is available here:

https://github.com/snaka/code-pocket/tree/master/framework/nextjs/webfont/legacy-optimization

HTML size of the build result (approx. 2MB)
-rw-r--r--@ 1 snaka  staff  2359534 Sep 29 09:48 ja.html
-rw-r--r--@ 1 snaka  staff  2359533 Sep 29 09:48 ko.html
-rw-r--r--@ 1 snaka  staff  2359540 Sep 29 09:48 zh-CN.html
-rw-r--r--@ 1 snaka  staff  2359540 Sep 29 09:48 zh-TW.html

Solution

The solution was simple. We stopped loading web fonts in _document.tsx and switched to using the next/font method introduced in Next.js v13.

https://nextjs.org/docs/pages/building-your-application/optimizing/fonts

This change significantly reduced the HTML size and resolved the IPC errors when the server was under load. Additionally, using next/font allowed us to self-host the web fonts, giving us independent control over cache durations and other settings through the CDN.

The code using the web fonts looks like this:

// index.tsx
import { Noto_Sans_JP, Noto_Sans_KR, Noto_Sans_SC, Noto_Sans_TC } from 'next/font/google'

const notoSansJP = Noto_Sans_JP({
  weight: ['100', '300', '400', '500', '700', '900'],
  preload: false
})
const notoSansSC = Noto_Sans_SC({
  weight: ['100', '300', '400', '500', '700', '900'],
  preload: false
})
const notoSansTC = Noto_Sans_TC({
  weight: ['100', '300', '400', '500', '700', '900'],
  preload: false
})
const notoSansKR = Noto_Sans_KR({
  weight: ['100', '300', '400', '500', '700', '900'],
  preload: false
})
// Use the web fonts loaded above like className={notoSansJP.className}

Sample code is available here:

https://github.com/snaka/code-pocket/tree/master/framework/nextjs/webfont/next-font

HTML size of the build result (approx. 5KB)
-rw-r--r--@ 1 snaka  staff   5176 Sep 29 14:19 ja.html
-rw-r--r--@ 1 snaka  staff   5175 Sep 29 14:19 ko.html
-rw-r--r--@ 1 snaka  staff   5182 Sep 29 14:19 zh-CN.html
-rw-r--r--@ 1 snaka  staff   5182 Sep 29 14:19 zh-TW.html

As a result of this fix, the Lighthouse Performance score, which was 52, improved slightly to 59. (There is still room for improvement.)

Choosing the Implementation Method

In this case, we adopted the method of changing the web font loading method and using next/font without preloading. This decision was based on an evaluation of the following technical trade-offs.

  • Challenges before the fix
    • Inter-process communication within the container became unstable due to increased traffic.
    • CPU and memory performance allocated to the container could not be fully utilized, necessitating the concurrent operation of many containers.
  • Negative impact of switching to next/font
    • Using next/font without preloading → A slight time lag occurred until the web font was applied.
  • Consideration of alternatives
    • Changing the deployment target to a FaaS platform? → Judged as high risk as technical verification time before service launch could not be secured.
    • Personally, I was very interested, but...
  • Final choice
    • Using next/font to resolve the communication bottleneck and gain the benefits of effective container resource utilization.
    • Prioritized cost-performance over slight UX degradation.
    • Anticipated that by splitting file loading, server load would be distributed using a CDN, enabling stable service operation in a cost-efficient manner.

With this choice, although client-side overhead increased due to the higher number of files to load, the final performance evaluation (Lighthouse) showed a slight improvement (approx. 13% improvement).

Conclusion

In this article, I presented an example of performance issues and their solutions for a website built with Next.js. We confirmed that the Automatic Webfont Optimization feature could lead to significant HTML size bloat in specific cases, potentially inducing server-side IPC errors.

As a solution, we reduced the HTML size by switching to next/font and optimizing the web font loading method, thereby resolving the server-side bottleneck. This also allowed us to self-host the web fonts and control cache durations.

The evolution of frontend technology is incredibly rapid, with new technologies and optimization techniques being introduced daily. While using these appropriately can enhance website performance, they are not universal and may cause unexpected issues in some cases. Thus, thorough testing is indispensable when adopting new features.

I hope this article proves useful to someone.

Note: This article was proofread by ChatGPT.

References

https://nextjs.org/docs/pages/building-your-application/optimizing/fonts

https://nextjs.org/blog/next-10-2#automatic-webfont-optimization

https://zenn.dev/catnose99/articles/bb943c3dc99d89

Discussion