Skip to content

API 라우트에서 워터폴 체인 방지

Overview

In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.

Impact

  • Priority: CRITICAL
  • Performance: 2-10× improvement

Problem

When you sequentially await independent operations in API routes, unnecessary wait time occurs.

Incorrect (config waits for auth, data waits for both)

typescript
export async function GET(request: Request) {
  const session = await auth()
  const config = await fetchConfig()
  const data = await fetchData(session.user.id)
  return Response.json({ data, config })
}

config is independent of auth but executes sequentially.

Correct (auth and config start immediately)

typescript
export async function GET(request: Request) {
  const sessionPromise = auth()
  const configPromise = fetchConfig()
  const session = await sessionPromise
  const [config, data] = await Promise.all([configPromise, fetchData(session.user.id)])
  return Response.json({ data, config })
}

Key Points

  • Create Promises immediately, await later
  • Start independent operations first
  • Await dependent operations when needed
  • Collect final results with Promise.all()

Advanced Pattern

For complex dependency chains, consider using the better-all library. (See Dependency-Based Parallelization)


Tags: api-routes, server-actions, waterfalls, parallelization