With the database connected, every read has a real cost. A 30-millisecond query goes unnoticed; five of them, one after another, don't. And usually nobody chained them on purpose: an await below another one, a component that waits before rendering its child, a card that requests its venue. That unintended chain is called a waterfall.

In 01-01 the waterfall was a flaw of the SPA, with a network round trip at every step. On the server the steps are shorter, but they still add up. In this lesson you'll learn to recognize them and remove them with four tools: starting things at the same time, joining in the query, sharing with React.cache and preloading. You'll also see when the sequence is correct and is best left alone.

  1. Seeing the waterfall

A performance flaw is measured before it's fixed. Raise the delay so the steps are visible and turn on Drizzle's query logging:

# .env.local
QUERY_DELAY_MS=800
// lib/db/client.ts, in createDb (temporary)
return drizzle({ client: pool, logger: true })

Restart and open /events/river-tales with the weather API running. The terminal shows the queries as they're sent, and the page fills in step by step:

0 ms      800 ms     1600 ms   2000 ms
|---------|----------|---------|
 event
           venue
                      forecast

None of them waits for another on a whim. EventLocation needs event.venueId, and DayForecast only exists if the venue is outdoors. The total is the sum, even though thanks to the <Suspense> boundaries the visitor sees something sooner. Compare that with what happens on /events: the form queries the districts and the list queries the events, and both queries show up together.

Source of the waterfall Where to look
Two unrelated consecutive awaits Inside a function
A component waits and then renders another one that waits Between parent and child
One component per row requesting its own data In a list: it's the N+1 problem
One piece of data depends on another In the model: sometimes a join solves it

The first column is the list of cases for this lesson.

  1. Inside a function: starting and waiting are different things

Calling an asynchronous function starts the work; await only waits for the result. Written on the same line, they look like a single thing:

// In series: the second doesn't start until the first finishes
const venues = await listVenues()
const districts = await listDistricts()

// In parallel: both start right away
const [venues, districts] = await Promise.all([listVenues(), listDistricts()])

Promise.all returns the results in the order of the array, not in the order they arrive, and TypeScript keeps the type of each position. It takes as long as the slowest one.

2.1. The count and the page

listEvents counts and then reads, because the page number is clamped using the total. But in the vast majority of visits the requested page exists. You can start both at once and correct only if the page wasn't valid:

// lib/data/events.ts (end of listEvents)
function queryPage(page: number) {
  return db
    .select()
    .from(events)
    .where(condition)
    .orderBy(...byDate)
    .limit(EVENTS_PER_PAGE)
    .offset((page - 1) * EVENTS_PER_PAGE)
}

const requested = Math.max(1, filters.page ?? 1)
const [total, rows] = await Promise.all([
  db.$count(events, condition),
  queryPage(requested),
])

const totalPages = Math.max(1, Math.ceil(total / EVENTS_PER_PAGE))
const page = Math.min(requested, totalPages)
const matches = page === requested ? rows : await queryPage(page)

return { events: matches, total, page, totalPages }

The normal case goes from two waits to one; the rare case still does the right thing, with one extra query. It's a useful pattern: get ahead of the likely case and repair the unlikely one.

There's a Drizzle detail worth knowing. A query isn't sent when you write it, but when you await it: queryPage(1) returns a builder, and it's Promise.all that sets it in motion by subscribing to it. That's why this other version does not run them in parallel:

const queryA = db.select().from(venues) // Not sent yet
const queryB = db.select().from(events) // Neither is this one
const a = await queryA                  // Sent now…
const b = await queryB                  // …and this one, afterwards

An async function like listVenues(), on the other hand, starts running as soon as you call it. With the functions in lib/data/ you won't get this surprise.

And another one about PostgreSQL: each simultaneous query takes up a connection from the pool. Starting twenty at once with a maximum of ten doesn't make them parallel; it just queues them and leaves other visits without a connection.

2.2. When one fails

Promise.all rejects as soon as one rejects, and the others are lost. That's appropriate if there's nothing to show without any one of them. If the data is independent and expendable, Promise.allSettled waits for all of them and describes how each one ended:

const [occupancy, notices] = await Promise.allSettled([
  getOccupancy(organizerId),
  listNotices(organizerId),
])

if (occupancy.status === 'fulfilled') {
  console.log(occupancy.value.booked)
} else {
  console.error(occupancy.reason)
}

In AgendaViva's UI it isn't needed: each area has its own component, its own <Suspense> and its own ErrorBoundary, which is the same result spread across the tree. allSettled fits things that aren't UI, like a report that gathers several sources.

There's one risk left when you separate starting from waiting:

const eventsPromise = listEventsByVenue(venueId) // If this fails…
const venue = await getVenueBySlug(slug)          // …and here we exit with an error or a notFound
const events = await eventsPromise                // …nobody ever handles that failure

A rejected promise that nobody handles produces an unhandledRejection in the process. With Promise.all that doesn't happen, because it handles all of them from the start. If you start a promise and there are paths where you don't await it, attach an empty catch to it; you'll see this in section 6.

2.3. Waits that cost nothing

Not every await is a step. FilterForm does await searchParams and then await listDistricts(). During a request, the search params are already known and their promise resolves immediately; reordering that code wouldn't gain anything. Measure before adding complexity: the target is network waits, not awaits.

  1. Between components

React walks the Server Component tree and, when it finds one that's waiting, moves on to its siblings. Two rules follow from that:

  • Siblings load in parallel, without Promise.all. Nor does a layout block its page: Next.js renders them at the same time.
  • A child doesn't start until its parent has returned the JSX that contains it. If the parent waits before returning it, there's a step, with <Suspense> or without it.
// In parallel: neither contains the other
<>
  <Suspense fallback={<ListSkeleton />}><TodaysEvents /></Suspense>
  <Suspense fallback={<ListSkeleton />}><FeaturedVenues /></Suspense>
</>

// In series: FeaturedVenues doesn't exist until TodaysEvents has waited
async function TodaysEvents() {
  const events = await listUpcomingEvents()
  return (
    <>
      <EventList events={events} />
      <Suspense fallback={<ListSkeleton />}><FeaturedVenues /></Suspense>
    </>
  )
}

<Suspense> changes when each part is seen, not when it starts. It's the most common confusion: wrapping the steps in boundaries gives you a page that fills in sooner, and the last piece still arrives just as late.

The preferred fix is structural: take the child out and place it as a sibling. That's possible whenever it doesn't need anything from the parent. In the dashboard overview, the @upcoming and @occupancy slots are siblings, and that's why they load at the same time.

  1. Between data: joining in the query

The venue needs the event's venueId, so they can't be siblings. But that dependency belongs to the database, and the database can resolve it without going back to the server: a join returns both things in one trip. Add the types and the query:

// lib/types.ts (addition)
export interface EventDetailsData {
  event: AgendaEvent
  venue: Venue
}
// lib/data/events.ts (addition; imports EventDetailsData)
export async function getEventDetails(slug: string): Promise<EventDetailsData | null> {
  const db = await getDb()
  const [details] = await db
    .select({ event: events, venue: venues })
    .from(events)
    .innerJoin(venues, eq(events.venueId, venues.id))
    .where(and(eq(events.slug, slug), inArray(events.status, ['published', 'canceled'])))
    .limit(1)
  return details ?? null
}

When you select whole tables, Drizzle groups the columns into event and venue. With innerJoin, neither can be missing, and the foreign key guarantees it. EventLocation is no longer asynchronous, and the forecast, which does have its own wait, moves up to the event page:

// app/(public)/events/_components/event-details.tsx (changes)
export function EventDetails({ event, venue }: EventDetailsData) {
  return (
    <article>
      {/* … heading and date, unchanged … */}
      <EventLocation venue={venue} />
      {venue.outdoor && (
        <Suspense fallback={<p className="text-sm">Checking the forecast…</p>}>
          <DayForecast date={event.startsAt} />
        </Suspense>
      )}
      {/* … description, spots and practical information, unchanged … */}
    </article>
  )
}

function EventLocation({ venue }: { venue: Venue }) {
  return (
    <p>
      <Link href={`/venues/${venue.slug}`} className="underline">
        {venue.name}
      </Link>
      , {venue.address} ({venue.district})
    </p>
  )
}
// app/(public)/events/[slug]/page.tsx (EventContent)
async function EventContent({ params }: Pick<Props, 'params'>) {
  const { slug } = await params
  const details = await getEventDetails(slug)
  if (!details) notFound()

  return <EventDetails {...details} />
}

The ErrorBoundary that protected the location goes away along with its wait: it can no longer fail separately. We've traded two queries for one slightly larger one, and in return the title waits for the venue to be read as well. With a primary key involved, it's a good deal. It wouldn't be if the second part were slow or bulky: then it's better for the title to come out first.

4.1. N+1: the waterfall of lists

The cards don't say where the event takes place. The natural thing in React seems to be a component that takes care of it:

// One query per card
async function VenueName({ venueId }: { venueId: string }) {
  const venue = await getVenueById(venueId)
  return <span>{venue?.name}</span>
}

A list of 6 events makes 1 query plus 6: the N+1 problem. The six run in parallel, so they barely lengthen the page, which is why it goes unnoticed; what multiplies is the work for the database and the connections in use. With a list of 50 it eats the entire pool.

The solution is the same join, with the columns that are needed:

// lib/types.ts
export interface EventWithVenue extends AgendaEvent {
  venue: VenueSummary
}

export interface EventPage {
  events: EventWithVenue[] // Previously AgendaEvent[]
  total: number
  page: number
  totalPages: number
}
// lib/data/events.ts
const withVenueColumns = {
  event: events,
  venue: {
    id: venues.id,
    slug: venues.slug,
    name: venues.name,
    district: venues.district,
  },
}

function attachVenue(row: { event: AgendaEvent; venue: VenueSummary }): EventWithVenue {
  return { ...row.event, venue: row.venue }
}

export async function listUpcomingEvents(limit = 6): Promise<EventWithVenue[]> {
  const db = await getDb()
  const rows = await db
    .select(withVenueColumns)
    .from(events)
    .innerJoin(venues, eq(events.venueId, venues.id))
    .where(isPublished)
    .orderBy(...byDate)
    .limit(limit)
  return rows.map(attachVenue)
}

Do the same in queryPage, inside listEvents, and return matches.map(attachVenue). The signatures are extended without breaking anyone: an EventWithVenue works wherever an AgendaEvent is expected. The card shows the venue if it receives one, because on a venue's page it would be redundant:

// components/event-card.tsx
type Props = { event: AgendaEvent & Partial<Pick<EventWithVenue, 'venue'>> }

// In the JSX, after the date
{event.venue && (
  <p className="text-sm text-slate-600">
    {event.venue.name} ({event.venue.district})
  </p>
)}

  1. React.cache in detail

Joining isn't always possible. Sometimes two distant components need the same data, and the sensible thing is for both to request it. React.cache, which we introduced in 03-04, makes the second request free. It's applied to the function, in the module:

// lib/data/events.ts
import { cache } from 'react'

export const getEventDetails = cache(
  async (slug: string): Promise<EventDetailsData | null> => {
    const db = await getDb()
    // … the same query
  },
)

Wrap getEventBySlug, getVenueBySlug, getVenueById and, in lib/data/weather.ts, getForecast in the same way. With the last one you get back what we lost in 04-01 by using signal: two components asking about the same day will make a single request. Here's precisely how it behaves:

Property Consequence
It stores the promise, not the value Two simultaneous calls share a query in progress
It lasts for one request The next visit starts from scratch; there's nothing to invalidate
It compares arguments one by one, by identity Strings and numbers match; a new object literal, never
It also stores errors Repeating the call within the same request throws the same error again
It returns the same reference Don't modify the result: everyone else would see it
It only works while Server Components are rendering In a script or a Route Handler it runs the function without remembering anything
It doesn't cross 'use cache' A function with that directive has its own scope (module 5)

The third row explains why we don't wrap listEvents: it receives a filters object that's created on every call. If it were needed, you'd pass it the fields separately. And the second row explains why this doesn't replace a cache: React.cache avoids repeating work within one page, not between visits.

Why not wrap everything? For clarity. It's used where there is, or will be, more than one consumer in the same request. With getEventDetails there will be: in 09-03, the page's metadata will need the title, and it will request it with the same function.

  1. Preloading

One case remains: the child could start earlier, because its input data is already known, but it can't be a sibling because the parent decides whether it exists. That happens on a venue's page. The list of events must not appear if the venue doesn't exist, and that's why it hangs from it. However, the slug is known from the start.

First, remove the dependency on the id by requesting the events by the venue's slug. Replace listEventsByVenue, which is no longer used, with this version:

// lib/data/events.ts
export const listVenueEvents = cache(
  async (venueSlug: string): Promise<AgendaEvent[]> => {
    const db = await getDb()
    const rows = await db
      .select({ event: events })
      .from(events)
      .innerJoin(venues, eq(events.venueId, venues.id))
      .where(and(isPublished, eq(venues.slug, venueSlug)))
      .orderBy(...byDate)
    return rows.map(({ event }) => event)
  },
)

// Starts the query without awaiting it; whoever requests it later will reuse it
export function preloadVenueEvents(venueSlug: string): void {
  listVenueEvents(venueSlug).catch(() => {})
}

Then the parent starts it before its own wait:

// app/(public)/venues/[slug]/page.tsx
async function VenueContent({ params }: Pick<Props, 'params'>) {
  const { slug } = await params
  preloadVenueEvents(slug)

  const venue = await getVenueBySlug(slug)
  if (!venue) notFound()

  return (
    <>
      {/* … name, address and heading, unchanged … */}
      <Suspense fallback={<p>Loading events…</p>}>
        <VenueEvents slug={slug} />
      </Suspense>
    </>
  )
}

async function VenueEvents({ slug }: { slug: string }) {
  const events = await listVenueEvents(slug)
  // … the rest, unchanged
}
sequenceDiagram
    participant C as VenueContent
    participant M as React.cache
    participant B as PostgreSQL
    participant E as VenueEvents
    C->>M: preloadVenueEvents(slug)
    M->>B: events query
    C->>B: venue query
    B-->>C: venue
    C->>E: returns the JSX that contains it
    E->>M: listVenueEvents(slug)
    B-->>M: events
    M-->>E: the same promise

Both queries are sent at the same time and, when VenueEvents requests its own, it receives the one already in progress. Without React.cache it wouldn't work: it would make another query.

  • The promise isn't passed as a prop. It could be, but it would force every intermediate component to know about it. Here the child is independent: if someone removes the preload, everything keeps working, just more slowly.
  • The empty catch doesn't hide the error. It only prevents the unhandled promise warning if the venue doesn't exist and nobody ever requests it. Whoever consumes it will get the rejection, and its error boundary will deal with it.
  • You pay up front. With a venue that doesn't exist, you'll have queried for nothing. Preload what's almost always used.

Don't confuse this preloading, which brings a query forward within a request, with Link prefetching, which brings the entire request forward before the click (02-03 and 10-02).

  1. When the sequence is necessary

Parallelizing isn't a goal in itself. Some sequences should stay:

Sequence Why
Check the permission and then read Private data is never loaded before you know whether it's allowed (08-04)
Check that there are spots and then book The second depends on the first, and they go in a transaction
Find the event and then decide whether to request the forecast It avoids an external call on most event pages
Write and then read again What was written must be visible
A very expensive query that's almost never needed Waiting to find out costs less

The third one is what remains on our event page: with the join, the page has two steps, event with venue, then forecast. We could always request the forecast, but we don't know the day until we've read the event. It's a necessary waterfall, short and behind its <Suspense>.

flowchart TD
    A["B waits for A"] --> B{"Does B use A's result?"}
    B -- No --> C{"In the same function?"}
    C -- Yes --> D["Promise.all"]
    C -- "No: parent and child" --> E{"Can it be a sibling?"}
    E -- Yes --> F["Take it out of the parent"]
    E -- No --> G["React.cache and preloading"]
    B -- Yes --> H{"Are they in the same<br/>database?"}
    H -- Yes --> I["Join or subquery"]
    H -- No --> J["Necessary sequence:<br/>Suspense, and caching in module 5"]

When you're done, remove logger: true and set the delay back to 300.

Common Mistakes and Tips

  • Chaining independent awaits out of habit.
  • Believing that <Suspense> parallelizes. It changes what's shown, not when it starts.
  • Storing Drizzle builders and awaiting them later, thinking they've already been sent.
  • Using Promise.all with expendable data. One failure brings them all down.
  • Leaving started promises unhandled.
  • Requesting one piece of data per row in a list component.
  • Calling cache inside a component, or with objects as arguments.
  • Modifying what a cache function returns, for example with sort. Copy it first: [...events].sort(…).
  • Parallelizing authorization with the read. The data has already been read, even if it isn't rendered.

Exercises

Exercise 1: counting steps

With 800 ms per query, how long does this page take to complete? Rewrite it to reduce that without changing what's shown. Assume that getOccupancy and listVenues don't depend on anything.

async function Overview() {
  const events = await listDashboardEvents(PLACEHOLDER_ORGANIZER_ID)
  const occupancy = await getOccupancy(PLACEHOLDER_ORGANIZER_ID)

  return (
    <>
      <p>{events.length} events, {occupancy.booked} spots booked</p>
      <Suspense fallback={<ListSkeleton />}>
        <VenueCount />
      </Suspense>
    </>
  )
}

async function VenueCount() {
  const venues = await listVenues()
  return <p>{venues.length} venues</p>
}

Solution

2400 ms: two awaits in series and then the child. The <Suspense> makes the first paragraph visible at 1600, but it doesn't bring the second one forward.

export function Overview() {
  return (
    <>
      <Suspense fallback={<p>Calculating…</p>}>
        <Totals />
      </Suspense>
      <Suspense fallback={<ListSkeleton />}>
        <VenueCount />
      </Suspense>
    </>
  )
}

async function Totals() {
  const [events, occupancy] = await Promise.all([
    listDashboardEvents(PLACEHOLDER_ORGANIZER_ID),
    getOccupancy(PLACEHOLDER_ORGANIZER_ID),
  ])
  return <p>{events.length} events, {occupancy.booked} spots booked</p>
}

800 ms: everything starts at the same time. Overview is no longer async, and with that the two blocks are siblings. Besides, requesting every event just to count them is wasteful: a function with $count would do the work in the database.

Exercise 2: why it doesn't share

Two components on the same page call search({ district: 'Riverside' }) and the log shows two queries. Why? Suggest two fixes.

export const search = cache(async (filters: { district: string }) => {
  const { events } = await listEvents(filters)
  return events
})

Solution

Each call creates a different object, and cache compares by identity. Two fixes: pass primitive values, or create the object once and give both components the same reference. The first is more robust:

export const searchByDistrict = cache(async (district: string) => {
  const { events } = await listEvents({ district })
  return events
})

Add up to three published events from the same category to the event page. The query must not wait for the event's query. Hint: join the table with itself using alias, from drizzle-orm/pg-core, so that it depends only on the slug.

Solution

// lib/data/events.ts (imports ne from 'drizzle-orm' and alias from 'drizzle-orm/pg-core')
export async function listRelatedEvents(slug: string): Promise<AgendaEvent[]> {
  const db = await getDb()
  const current = alias(events, 'current')
  const rows = await db
    .select({ event: events })
    .from(events)
    .innerJoin(
      current,
      and(eq(events.category, current.category), ne(events.id, current.id)),
    )
    .where(and(isPublished, eq(current.slug, slug)))
    .orderBy(...byDate)
    .limit(3)
  return rows.map(({ event }) => event)
}
// app/(public)/events/_components/related-events.tsx
import { EventCard } from '@/components/event-card'
import { listRelatedEvents } from '@/lib/data/events'

interface Props {
  params: Promise<{ slug: string }>
}

export async function RelatedEvents({ params }: Props) {
  const { slug } = await params
  const events = await listRelatedEvents(slug)
  if (events.length === 0) return null

  return (
    <section className="mt-12" aria-labelledby="related-title">
      <h2 id="related-title" className="mb-4 text-xl font-semibold">
        You might also like
      </h2>
      <ul className="grid gap-4 sm:grid-cols-3">
        {events.map((event) => (
          <li key={event.id}>
            <EventCard event={event} />
          </li>
        ))}
      </ul>
    </section>
  )
}
// app/(public)/events/[slug]/page.tsx
export default function EventDetailPage({ params }: Props) {
  return (
    <>
      <Suspense fallback={<p>Loading the event…</p>}>
        <EventContent params={params} />
      </Suspense>
      <Suspense fallback={null}>
        <RelatedEvents params={params} />
      </Suspense>
    </>
  )
}

They're siblings and both depend only on params, so the queries go out together. If the slug doesn't exist, the list is empty and isn't rendered, while EventContent calls notFound(). The course keeps this block. Remember that links between event pages open the quick view (02-05).

Conclusion

A waterfall appears when something waits without needing to. It's fixed at the level where it originates: Promise.all inside a function, siblings instead of parent and child, joins when the dependency belongs to the database, and React.cache with preloading when the tree allows nothing else. What genuinely depends on something else, above all authorization, stays in sequence.

The event page has gone from three steps to two, and the lists show the venue without a single extra query. All that work reaches the browser in parts thanks to the <Suspense> boundaries we've been writing since 01-04. It's time to see what happens there: in Streaming with Suspense you'll open up a response in progress and decide where to split each page.

© Copyright 2026. All rights reserved