| 1 | --- |
| 2 | title: Prevent Waterfall Chains in API Routes |
| 3 | impact: CRITICAL |
| 4 | impactDescription: 2-10× improvement |
| 5 | tags: api-routes, server-actions, waterfalls, parallelization |
| 6 | --- |
| 7 | |
| 8 | ## Prevent Waterfall Chains in API Routes |
| 9 | |
| 10 | In API routes and Server Actions, start independent operations immediately, even if you don't await them yet. |
| 11 | |
| 12 | **Incorrect (config waits for auth, data waits for both):** |
| 13 | |
| 14 | ```typescript |
| 15 | export async function GET(request: Request) { |
| 16 | const session = await auth() |
| 17 | const config = await fetchConfig() |
| 18 | const data = await fetchData(session.user.id) |
| 19 | return Response.json({ data, config }) |
| 20 | } |
| 21 | ``` |
| 22 | |
| 23 | **Correct (auth and config start immediately):** |
| 24 | |
| 25 | ```typescript |
| 26 | export async function GET(request: Request) { |
| 27 | const sessionPromise = auth() |
| 28 | const configPromise = fetchConfig() |
| 29 | const session = await sessionPromise |
| 30 | const [config, data] = await Promise.all([ |
| 31 | configPromise, |
| 32 | fetchData(session.user.id) |
| 33 | ]) |
| 34 | return Response.json({ data, config }) |
| 35 | } |
| 36 | ``` |
| 37 | |
| 38 | For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization). |
| 39 |