Suspense, streaming, and waterfalls
Expose useful content while independent work continues, and distinguish streamed UI from a streamed application protocol.
What you will be able to do
- Draw dependencies before parallelizing requests.
- Place Suspense around useful independent boundaries.
- Explain response commitment, fallback design and streaming verification.
A waterfall is a dependency graph problem
Imagine the catalogue needs a product, its reviews and global categories. Reviews depend on the product ID, but categories do not. If code awaits product, then reviews, then categories, the category request waits for no useful reason. Start independent work early, preserve genuine dependencies and await results where they are needed. A Promise.all call only helps work that has actually been started independently.
Parallelism reduces the critical path only when the work can overlap and resources can support it. Launching hundreds of database operations at once can exhaust a connection pool. In a small interview example, explain the dependency graph first, then the concurrency bound and failure policy. The kata computes earliest completion from an explicitly supplied acyclic graph. It does not measure network performance or model server scheduling overhead.
Suspense defines where waiting becomes visible
A Suspense boundary can show fallback UI while supported work below it is pending. Place the boundary around content whose independent arrival is useful: a stable product summary may appear before reviews. Wrapping the entire page in one boundary can hide fast content behind the slowest dependency. Wrapping every tiny label creates unnecessary visual fragmentation. Choose boundaries from meaningful sections of the user task.
The fallback should preserve orientation, explain what is loading and avoid disruptive layout changes. If the component above the boundary awaits all data first, the boundary has no opportunity to reveal independent content earlier. Start or read the slow work inside the appropriate async child or pass promises through the supported React pattern. Remember that Suspense is not an automatic listener for arbitrary requests started inside useEffect.
Server execution
import { Suspense } from 'react';
async function Reviews() {
await new Promise(resolve => setTimeout(resolve, 900));
return <ul><li>Quiet keys and a comfortable layout.</li></ul>;
}
export default function Page() {
return <main>
<h1>Mechanical keyboard</h1>
<p>This summary is available without waiting for reviews.</p>
<Suspense fallback={<p role="status">Loading reviews</p>}>
<Reviews />
</Suspense>
</main>;
}Do not confuse UI streaming with SSE
App Router streaming delivers parts of the rendered interface as they become ready. A chat endpoint can instead stream an application protocol, such as text chunks or Server-Sent Events, that client code parses into state. Both involve incremental delivery, but their framing, consumers and lifecycle are different. A Suspense fallback is not an SSE parser, and an EventSource connection does not automatically create React Suspense behavior.
Once a response has started, status and headers cannot be changed as if no bytes had left. This matters for late failures, redirects and missing data. Perform required access checks before exposing protected content, and design recovery for errors that occur after a shell is visible. A stream should have a completion or cancellation policy, and the server should stop unnecessary upstream work when the client disconnects where the runtime supports it.
Verify arrival timing through the whole infrastructure
Observe the fallback and the later content with controlled latency, then repeat in production mode. A proxy or platform can buffer bytes and remove the visible benefit even though the component code is correct. Inspect response timing and actual browser painting rather than assume that an async function proves streaming. Development behavior and local loopback speed can hide both waterfall and buffering problems.
Accessibility also needs deliberate attention. A stable heading should identify the page while a region is pending. A small status announcement can explain loading, but repeatedly announcing every chunk of a large chat response can overwhelm a screen reader. Distinguish the informational status from the final readable content. In an interview, discuss failure and cancellation alongside the happy-path latency improvement.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGESuspense automatically tracks every request started inside useEffect.
- A more accurate model
Arbitrary Effect-based fetching does not automatically become Suspense-aware. Use a supported data mechanism and put waiting at the intended boundary.
- How to check it
N09 and the streaming lesson distinguish supported pending work from ordinary Effect requests.
- CLAIM TO CHALLENGEA streamed response can change its status and headers at any later moment.
- A more accurate model
After the response is committed, headers cannot be replaced as though no bytes were sent. Check access before exposing data and design later failure recovery.
- How to check it
N19, N21 and N27 support access, response and recovery boundaries discussed in the streaming lesson.
Mistakes to catch in your own code
- A boundary cannot reveal work early if its parent already awaited everything.
- Suspense does not automatically track arbitrary fetches launched inside Effects.
- Visible streaming can be lost through infrastructure buffering.
Write it by hand
JavaScript logic playground
Calculate a dependency graph’s critical path
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Implement solve({tasks}). Tasks are supplied in topological order and contain unique id, nonnegative duration and dependsOn IDs already listed earlier.
- A task can start when every dependency has finished. Independent tasks start at zero. Return {finishById,total}, where total is the latest finish or zero for no tasks.
- This is an unlimited-concurrency scheduling model with no network overhead. It does not benchmark Next.js streaming.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 4 test cases
- Independent reads overlap
Input
{ "tasks": [ { "id": "product", "duration": 100, "dependsOn": [] }, { "id": "categories", "duration": 80, "dependsOn": [] } ] }Expected
{ "finishById": { "product": 100, "categories": 80 }, "total": 100 } - Reviews need product
Input
{ "tasks": [ { "id": "product", "duration": 100, "dependsOn": [] }, { "id": "categories", "duration": 80, "dependsOn": [] }, { "id": "reviews", "duration": 200, "dependsOn": [ "product" ] } ] }Expected
{ "finishById": { "product": 100, "categories": 80, "reviews": 300 }, "total": 300 } - Join waits for slowest dependency
Input
{ "tasks": [ { "id": "a", "duration": 30, "dependsOn": [] }, { "id": "b", "duration": 70, "dependsOn": [] }, { "id": "join", "duration": 10, "dependsOn": [ "a", "b" ] } ] }Expected
{ "finishById": { "a": 30, "b": 70, "join": 80 }, "total": 80 } - Empty schedule
Input
{ "tasks": [] }Expected
{ "finishById": {}, "total": 0 }
Reveal the worked solution and reasoning
function solve(input) {
const finish = new Map();
let total = 0;
for (const task of input.tasks) {
const start = task.dependsOn.reduce((latest, id) => Math.max(latest, finish.get(id)), 0);
const end = start + task.duration;
finish.set(task.id, end);
total = Math.max(total, end);
}
return { finishById: Object.fromEntries(finish), total };
}The earliest start is the maximum dependency finish, not their sum, because independent predecessors overlap.
Real systems add concurrency bounds, contention and failures. The model isolates dependency reasoning before those factors are introduced.
Verify it in a real Next.js application
Next.js application lab
Observe the two shipped streaming mechanisms
Open the local application route /stream after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Inspect app/stream/page.tsx. The shipped SlowPanel calls connection(), waits 600 ms and sits beneath Suspense; the heading and client stream controls remain outside that delayed panel.
- Run a production build, reload /stream and inspect early shell and later panel arrival. Record any buffering from the actual browser or hosting path rather than inferring arrival only from JSX order.
- Start the independent EventSource stream and inspect /api/stream. Identify data events, the explicit done event and the server timer cleanup; then stop and restart before completion.
- As an extension, add a second delayed server section or adapt the Reviews example. Keep request-time delays inside an async child that calls connection() in this Cache Components project. Compare useful boundaries with a deliberately grouped slow boundary, then restore the intended layout.
Check the behavior
- The production observation distinguishes the useful shell from the delayed server panel.
- The application stream emits framed SSE events and reaches its explicit completion state.
- Stopping or replacing a stream does not append stale events to the current output.
- If the additional section is implemented, its placement and delay are verified with a build and a timing observation.
Review the application reasoning
Both UI streaming and application-data streaming already run in the shipped project. They have different protocols and should have separate evidence.
Artificial waits are controlled teaching tools. The dependency-graph kata models ideal overlap; it does not measure production infrastructure, browser scheduling or connection limits.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01How do you remove a server data waterfall?
I identify which operations truly depend on others, start independent operations early and await them at appropriate boundaries. I keep required authorization and dependent IDs sequential. I also consider concurrency limits and whether one failed operation should fail the whole view or only its section.
Follow-up questions
- What if the database pool has only a few connections?
- When is Promise.all the wrong failure policy?
- Fetching dataOfficial documentation
02Where should Suspense go?
Around a meaningful independently useful section whose pending work can be handled by that boundary. The parent must not block on all of that work first. I choose a fallback that preserves layout and orientation, then verify that fast content actually appears before the slow section in a production run.
Follow-up questions
- What does loading.tsx wrap?
- Why not put a boundary around every label?
- Fetching dataOfficial documentation
- Layouts and pagesOfficial documentation
03Is Next.js UI streaming the same as SSE?
No. UI streaming incrementally delivers rendered React output, while SSE is an application event protocol consumed by client code. They can coexist but require different parsing and lifecycle handling. I would name which layer is being streamed before discussing cancellation, errors or tests.
Follow-up questions
- Where are event boundaries parsed?
- What happens when a UTF-8 character crosses chunks?
- Fetching dataOfficial documentation
- Route HandlersOfficial documentation
- HTML server-sent events standardOfficial documentation
- CallMissed Next.js engineering assignmentEmployer assignment
04What changes when an error happens after streaming begins?
The response may already have committed its headers and initial content, so ordinary status changes are no longer available in the same way. I protect data before revealing it and provide a recovery boundary for later failures. I test what the browser sees instead of assuming every late error becomes a fresh HTTP 500 document.
Follow-up questions
- Where should auth checks run?
- How would a reverse proxy affect observation?
- Data securityOfficial documentation
- Error handlingOfficial documentation
- Self-hosting Next.jsOfficial documentation
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- Layouts and pagesOfficial documentation
- Fetching dataOfficial documentation
- Data securityOfficial documentation
- Route HandlersOfficial documentation
- Self-hosting Next.jsOfficial documentation
- Error handlingOfficial documentation
- HTML server-sent events standardOfficial documentation
- CallMissed Next.js engineering assignmentEmployer assignment
- DejaBlue software interview exerciseEmployer assignment