Topic F7
Request waterfalls vs parallel requests
Requests that don't need to wait for each other, and how to run them together.
Watch: bars stepping down like stairs mean each request waits for the one before. Those that can run together should.
- moving now
- finished / the result
How it happens
await makes code read neatly top to bottom, and that's exactly the problem: each await holds the next line until it's done. Four awaits in a row means four round trips to the server, even if only one really needs the result before it.
Code, for programmersSerial, then parallel
// waterfall: 4 × 300 ms = 1200 ms
const user = await getUser();
const orders = await getOrders(user.id);
const products = await getProducts();
const alerts = await getAlerts();
// parallel where possible: 2 × 300 ms = 600 ms
const userP = getUser(); // start, don't wait yet
const [user, products, alerts] = await Promise.all([userP, getProducts(), getAlerts()]);
const orders = await getOrders(user.id); // the only real dependencyHidden waterfalls
- Nested components: a parent fetches in a useEffect, then its child only appears and fetches its own data, then the grandchild. Each level waits for the one above to finish rendering.
- Chained lazy loading: the page downloads, then its component downloads, then that component finally asks for data.
- Fonts and images the browser only discovers after the CSS has downloaded.
The fix is the same: start everything that can start as early as possible. Fetch at the route level (loaders in React Router or Remix, Server Components in Next.js), prefetch when the user hovers a link, and use <link rel="preload"> for important assets.
Quiz
Three independent 200 ms requests, written as awaits in a row. How long does it take?
With Promise.all, the same three requests take…
orders needs user.id. What's the minimum time to load user and orders (300 ms each)?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.