Sub topic 13
Pitfalls: Startup Cost, Cycles, and Deadlocks
Top-level await is easy to add and can be hard to debug once it causes trouble. This chapter covers the failure modes that show up in real applications: slow startup, waterfalls between modules, rejected modules that stay broken, deadlocks between import() and import cycles, and places where top-level await is not allowed at all.
This chapter assumes you already know how top-level await pauses a module and how it changes evaluation order. You should also be comfortable with import(), promises, and running .mjs files in Node.js. Every example runs on Node.js 20 or later.
Pitfall 1: One Await Delays Every Importer
A top-level await pauses its own module. It also pauses every module that depends on that module, directly or through other modules, all the way up to the entry point. Sibling modules that do not depend on the paused module still run. Their importers do not.
Save these three files and run node main.mjs:
// slow.mjs
console.log('slow: start');
await new Promise((resolve) => setTimeout(resolve, 2000));
console.log('slow: done');
export const value = 42;// fast.mjs
console.log('fast: evaluated');
export const x = 1;// main.mjs
import { value } from './slow.mjs';
import { x } from './fast.mjs';
console.log('main:', value, x);The output is:
slow: start
fast: evaluated
slow: done
main: 42 1fast.mjs runs as soon as slow.mjs pauses. main.mjs waits the full two seconds. In a browser, that delay means the page is not interactive yet. In a server, the HTTP listener is not bound and health checks fail. In a CLI, the user is left looking at a blank terminal.
The cost also grows when the pause sits deep in the graph. A utility module three levels down that awaits a network call blocks every module above it, and the code that imports it may not know it awaits anything.
Waterfalls Between Awaiting Modules
If module A awaits, and module B imports A and then awaits something of its own, B's wait cannot start until A's wait has finished. Chains like this run one after the other even when the two tasks are unrelated. The total startup time is the sum of every wait in the chain, not the longest one.
The fix is to put independent work in one place and start it all together:
// startup.mjs
const [config, translations] = await Promise.all([
fetch('https://example.com/config.json').then((r) => r.json()),
fetch('https://example.com/i18n/en.json').then((r) => r.json()),
]);
export { config, translations };Pitfall 2: A Rejected Module Stays Rejected
If a top-level await rejects, or the module throws after an await, the module ends up in an error state. The module map caches that state. Every later import() of the same specifier rejects with the same error, and the module body does not run again.
// flaky.mjs
globalThis.attempts = (globalThis.attempts ?? 0) + 1;
await new Promise((resolve) => setTimeout(resolve, 100));
if (globalThis.attempts === 1) {
throw new Error('first attempt failed');
}
export const ok = true;// retry.mjs
for (let i = 0; i < 2; i++) {
try {
await import('./flaky.mjs');
console.log('loaded');
} catch (err) {
console.log(`try ${i + 1}:`, err.message, '| attempts =', globalThis.attempts);
}
}Running node retry.mjs prints the same error twice, and attempts stays at 1:
try 1: first attempt failed | attempts = 1
try 2: first attempt failed | attempts = 1You can force a fresh evaluation by changing the URL, for example import('./flaky.mjs?retry=1'). That creates a second, separate module instance with its own state. The failed instance stays in memory. Any module that imported the original specifier statically still sees the error. Treat cache-busting as a last resort.
When initialization might fail and should be retried, do the work inside a function and export that function:
// db.mjs
let pending = null;
async function connect() {
await new Promise((resolve) => setTimeout(resolve, 100));
if (Math.random() < 0.5) throw new Error('connection refused');
return { query: (sql) => `result of ${sql}` };
}
export function getDb() {
pending ??= connect().catch((err) => {
pending = null; // allow the next caller to retry
throw err;
});
return pending;
}// use-db.mjs
import { getDb } from './db.mjs';
for (let i = 1; i <= 5; i++) {
try {
const db = await getDb();
console.log(db.query('SELECT 1'));
break;
} catch (err) {
console.log(`attempt ${i}:`, err.message);
}
}db.mjs itself never awaits, so it never blocks or poisons its importers. Concurrent callers share one in-flight promise, and a failure clears it so the next call tries again.
Pitfall 3: Deadlock Between import() and a Cycle
Static import cycles are allowed with top-level await. The engine evaluates the cycle as a group, and the usual risk is reading a binding before it has been initialized. A deadlock is a different problem. It happens when a module awaits a dynamic import of a module that statically depends on the waiting module.
// a.mjs
console.log('a: start');
const b = await import('./b.mjs');
console.log('a: got', b.name);
export const name = 'a';// b.mjs
import { name as aName } from './a.mjs';
console.log('b: evaluating, a is', aName);
export const name = 'b';Run node a.mjs:
a: start
Warning: Detected unsettled top-level await at file:///.../a.mjs:2
const b = await import('./b.mjs');
^The process exits with code 13. b: evaluating never prints. The sequence of events is:
a.mjsstarts evaluating and pauses onawait import('./b.mjs'). Its status is now "evaluating asynchronously".- The engine loads
b.mjsand finds its dependencya.mjsstill unfinished, sob.mjswaits fora.mjsto complete. a.mjsis waiting forb.mjs. Neither promise can settle.
Browsers have no such exit check. The promise stays pending forever, and the page looks half-loaded with no error in the console. Node reports the problem only when the event loop empties. A server with an open socket or timer keeps running with the module stuck, and you get no warning.
Ways to break the deadlock:
- Move what
b.mjsneeds froma.mjsinto a third module,shared.mjs, that both import. This removes the cycle. - Do not await the dynamic import at the top level. Call it later, inside a function, after
a.mjshas finished evaluating. - If
b.mjsonly needsa.mjsat call time, havea.mjspass the value into a function thatb.mjsexports, sob.mjsdoes not importa.mjsat all.
Pitfall 4: Awaits That Never Settle
A deadlock is one way to get a module that never finishes. A network call with no timeout is another. A fetch to a host that accepts the connection and then stalls can hang your whole module graph. Always put a limit on top-level waits:
// remote-config.mjs
const response = await fetch('https://example.com/config.json', {
signal: AbortSignal.timeout(3000),
});
if (!response.ok) {
throw new Error(`Config request failed: ${response.status}`);
}
export const config = await response.json();After three seconds the fetch rejects with a TimeoutError. Pitfall 2 still applies: this module is now permanently failed. That is the right outcome only when the app cannot run without the config.
Pitfall 5: Contexts That Reject Top-Level Await
Some environments refuse async module graphs:
require()of ES modules in Node.js. Recent Node versions (20.19+, 22.12+) let CommonJSrequire()a synchronous ES module. If any module in that graph uses top-level await,require()throwsERR_REQUIRE_ASYNC_MODULE. Useimport()instead.- Service workers. The HTML specification disallows top-level await in service worker module scripts, because install and activate events need synchronous registration of event listeners.
- Library entry points. A published package with top-level await forces that cost on every consumer and breaks consumers who use
require(). Prefer an exportedinit()function.
Choosing a Fix
| Pitfall | Symptom | Fix |
|---|---|---|
| Blocking importers | Slow first paint or late server start | Await only near the entry point, or export a promise-returning function |
| Waterfall | Startup time equals the sum of all waits | Combine independent work with `Promise.all` in one module |
| Cached rejection | Retrying `import()` fails instantly with the old error | Put the work in a function that resets on failure |
| Cycle deadlock | Pending forever, or Node exit code 13 | Extract shared code to a third module, or import later inside a function |
| Hung await | App never finishes loading | Add `AbortSignal.timeout` or `Promise.race` with a timer |
| Unsupported context | `ERR_REQUIRE_ASYNC_MODULE`, service worker error | Use `import()`, or remove top-level await from that graph |
Exercise
A module analytics.mjs contains await loadVendorScript() at the top level. The vendor's server is down, so the promise rejects. The app's main.mjs imports analytics.mjs statically. What happens to the app, and how would you restructure analytics so a vendor outage cannot break startup?
Show answer
The rejection puts analytics.mjs in a permanent error state, so main.mjs fails to evaluate and the app does not start. Remove the top-level await. Export a function such as initAnalytics() that calls loadVendorScript() and catches errors. Call it from main.mjs without awaiting it, or load analytics.mjs with a dynamic import() inside a try/catch after startup.
Exercise
router.mjs runs const page = await import('./pages/home.mjs') at the top level, and home.mjs contains import { navigate } from '../router.mjs'. Predict the result in Node and in a browser, and give one change that fixes it.
Show answer
This is a deadlock. router.mjs is paused waiting for home.mjs, and home.mjs waits for router.mjs to finish evaluating. Node prints "Detected unsettled top-level await" and exits with code 13 once nothing else keeps the event loop alive. A browser leaves the promise pending with no error. One fix is to move navigate into a separate navigation.mjs that both modules import. Another is to make the dynamic import inside a function that runs after router.mjs has finished evaluating.
Exercise
Three modules each await a 1-second fetch at the top level. c.mjs imports b.mjs, and b.mjs imports a.mjs. About how long does startup take, and how can you bring it close to 1 second?
Show answer
About 3 seconds, because each module's wait starts only after its dependency has finished. Start all three fetches together with Promise.all in one module that the others import. Or have each module export a promise without awaiting it, and await all three together at the entry point.