Sub topic 13
Pitfalls: Startup Cost, Cycles, and Deadlocks
This chapter assumes you already know how top-level await pauses a module's evaluation, and how that pause carries over to every module that imports it, as covered in the previous two chapters. Top-level await is simple to write, but it moves waiting into the module graph, where it is harder to see. The three problems below come up most often in real code.
Pitfall 1: Slow Startup Spreads to Importers
A module that awaits at the top level holds back every module that depends on it, directly or indirectly. If a shared utility module awaits a slow network call, your whole app waits for that call before its entry point runs.
// db.js — every importer waits for this connection
import { connect } from './driver.js';
export const db = await connect(process.env.DB_URL); // may take secondsModules that do not depend on db.js can still evaluate. Anything that imports it, even only for a helper function, cannot.
The fix is to export a promise or a lazy getter, so each caller decides when to wait:
// db.js — no top-level await; connect once, on first use
import { connect } from './driver.js';
let dbPromise;
export function getDb() {
dbPromise ??= connect(process.env.DB_URL);
return dbPromise;
}Pitfall 2: Cycles and Uninitialized Bindings
Circular imports already exist without top-level await. When module A imports B and B imports A, one of them runs before the other has finished. If B reads a let or const export from A before A has initialized it, you get a ReferenceError. This happens because the binding is still in its temporal dead zone, the period before a declaration has run. Top-level await widens the gap, because a module can now stop partway through evaluation while other code runs and reads its half-finished exports.
Pitfall 3: Deadlock Through Dynamic Import
The worst case combines a static cycle with a dynamic import inside top-level await:
// a.js
import './b.js';
export const value = 1;
// b.js
const { value } = await import('./a.js'); // waits for a.js to finish
console.log(value);a.js cannot finish until its dependency b.js finishes. b.js is waiting for a.js to finish. Neither promise ever settles. Browsers simply hang. Node.js notices that the event loop is empty and exits with code 13 and a warning about an unsettled top-level await.
To break the loop, move the shared value into a third module that both import, or replace the top-level await with a function the caller runs after startup.
The Same Hang from a Promise That Never Settles
A top-level await on a promise that never settles has the same effect as a deadlock. A server that never responds is the usual cause. Put a timeout on network waits:
// config.js
const response = await fetch('/config.json', {
signal: AbortSignal.timeout(5000),
});
export const config = await response.json();If the request takes longer than five seconds, it rejects. The module then fails loudly instead of hanging.
Summary
| Pitfall | Symptom | Fix |
|---|---|---|
| Slow shared module | Late first render or slow server start | Export a promise or lazy getter |
| Cycle with partial evaluation | `ReferenceError` on an import | Remove the cycle or defer access |
| Cycle with `await import()` | Hang, or Node.js exit code 13 | Extract shared code into a third module |
| Promise that never settles | Hang | Add a timeout or abort signal |
Exercise
A logging module log.js is imported by 40 other modules and starts with const transport = await openRemoteTransport();. What problem does this cause, and how would you restructure it?
Show answer
Every module that imports log.js, and every module above those in the graph, waits for the remote transport before evaluating, so startup is only as fast as that connection. Export a function such as getTransport() that creates the connection promise on first call and caches it, or buffer log calls until the transport is ready. That way importers no longer block on it.
Exercise
Why does b.js hang forever when a.js statically imports b.js and b.js runs await import('./a.js') at the top level?
Show answer
The promise from import('./a.js') resolves only after a.js finishes evaluating. a.js cannot finish until its dependency b.js finishes, and b.js is paused waiting on that promise. Each waits on the other, so neither settles.