How can I profile which modules are slowing down Node.js startup?
Asked by
MellowPine42
Our API server became noticeably slower to start, even though request performance was fine. The problem only showed up when deployment health checks timed out on smaller instances, and the commit history didn't reveal when the regression began. I wrote a small preload script that wrapped Module._load, measured each require with process.hrtime.bigint(), and logged calls taking longer than 50 milliseconds. Cold startup averaged 1.9 seconds, with about 1.1 seconds coming from our own src/lib/index.js barrel file. One route needed only a date helper, but importing the barrel loaded all 34 modules in that directory, including two that read configuration files during import. Replacing the barrel import with a direct import of the helper reduced cold startup to about 0.8 seconds. Patching Module._load works, but it feels intrusive. Is there a runtime-supported way to get a per-module startup breakdown?
Answers
The direct import is the right fix here. A barrel file makes every consumer pay for all of its exports, and any work performed at import time makes that especially expensive. Moving the date helper into its own module, or otherwise importing it without loading the entire directory, should keep startup focused on what that route actually needs.
Reply to this answer
Try Nodeโs built-in CPU profiler with `node --cpu-prof`. The generated profile can be grouped by `callFrame.url`, which gives you a useful view of how much time each module spends executing its top-level code. Itโs a lot cleaner than replacing Module._load. Keep in mind that synchronous file reads during module initialization may show up under native frames, so the profile can understate the cost of configuration readers.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions