Frontend System Design · Lesson 34 of 86 · 5 min
Hydration and Time to First Byte (TTFB)
This is where you connect rendering theory to real-world performance bottlenecks and show you can diagnose why a "fast" page feels slow.
The "uncanny valley" of Server-Side Rendering
With Server-Side Rendering (SSR), the browser gets HTML quickly and paints pixels almost immediately. The page looks ready. But if the user clicks a button and nothing happens for two seconds, you've created a frustrating experience. This gap between a visually complete page and an interactive one is the "uncanny valley" of SSR.
Hydration is the process that closes this gap. It's the client-side JavaScript running, finding the server-rendered HTML, and "bringing it to life" by attaching event listeners, initializing state, and making the application interactive.
Until hydration is complete, your app is just a static painting.
The trap: Many candidates can define SSR but fail to articulate this core trade-off: SSR optimizes for a fast First Contentful Paint (FCP) but can delay Time to Interactive (TTI). Your ability to explain this tension and how to resolve it is what interviewers are listening for.
How hydration works in code
In an interview, you should be able to walk through the lifecycle of a component from server to interactive client. The key is that the same component code runs in both environments.
First, the server uses a library like react-dom/server to render the component to a string. It fetches any necessary data and injects it into the HTML.
// server/renderer.ts
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { App } from '../src/App';
// In an Express.js route handler
async function handleRequest(req, res) {
// 1. Fetch critical data on the server
const initialData = { user: 'Interview Candidate' };
// 2. Render the React tree to an HTML string
const appHtml = ReactDOMServer.renderToString(
<App initialData={initialData} />
);
// 3. Embed the HTML and initial data into a full document
const html = `
<!DOCTYPE html>
<html>
<head><title>SSR App</title></head>
<body>
<div id="root">${appHtml}</div>
<script>
window.__INITIAL_DATA__ = ${JSON.stringify(initialData)}
</script>
<script src="/client.bundle.js"></script>
</body>
</html>
`;
res.send(html);
}
Next, the client-side script executes. Instead of rendering into an empty DOM node, it hydrates the existing HTML.
// client/index.tsx
import React from 'react';
import { hydrateRoot } from 'react-dom/client';
import { App } from './App';
// 1. Grab the server-rendered HTML root
const rootElement = document.getElementById('root');
// 2. Read the initial data injected by the server
const initialData = window.__INITIAL_DATA__;
// 3. Hydrate: React takes over the existing HTML instead of creating it
if (rootElement) {
hydrateRoot(
rootElement,
<App initialData={initialData} />
);
}
React expects the client-rendered tree to be identical to the server-rendered HTML. If it's not (a "hydration mismatch"), React will discard the server's work and perform a full client-side render, losing most of the performance benefits of SSR.
Why your fast page still feels slow: TTFB
Before the browser can even start painting HTML, it has to receive the first byte of the response. The time it waits is the Time to First Byte (TTFB).
TTFB is the latency floor for your entire page load. If your TTFB is 800ms, your Largest Contentful Paint (LCP) can never be better than 800ms, even if your frontend code is perfect.
It measures the combined time of:
- Redirects, DNS lookups, and connection setup (TCP/SSL).
- The time your server spends processing the request (running business logic, querying databases, calling APIs).
- The time it takes for the first packet of the response to travel back to the client.
The trap: Focusing exclusively on frontend metrics like bundle size while ignoring the server. A candidate who says "we'll reduce our bundle size" to fix a slow initial load might be missing the real problem. A high TTFB points to a backend or infrastructure bottleneck, not a frontend one.
Diagnosing and fixing hydration bottlenecks
When a page has a high TTI despite a fast FCP, hydration is the likely culprit.
In an interview, you might be asked: "You've shipped an SSR feature and users are complaining the page feels frozen for a few seconds after loading. How do you investigate?"
Your answer should cover these common causes:
- The monolithic bundle: The browser can't hydrate until it has downloaded, parsed, and executed your JavaScript. If you ship a single 2MB
app.js, you're forcing the user to wait, blocking the main thread and delaying interactivity. The fix is aggressive code-splitting. Send only the code needed for the current page to become interactive. - Over-hydration: You're hydrating the entire page, including static parts like the header, footer, or a blog post's text content. This is wasted effort. The fix is partial or selective hydration. Modern frameworks are moving towards this model (e.g., Astro Islands, React Server Components), where you explicitly mark which components are interactive "islands" that need hydration.
- Heavy client-side logic: Your component's
useEffector top-level module code might be running expensive computations or fetching non-critical data synchronously upon load. This blocks the main thread and delays hydration. Defer this work until after hydration or until the user actually interacts with the component.
How to attack a high TTFB
A high TTFB is almost always a server-side or network problem. Your strategy should focus there.
- Cache aggressively. The fastest database query is the one you don't make. Use an in-memory cache like Redis or Memcached to store the results of expensive queries or API calls. For content that is the same for all users, you can even cache the fully-rendered HTML page itself.
- Use a Content Delivery Network (CDN). A CDN moves your server closer to the user. It terminates the TLS connection at an edge location near them, drastically reducing round-trip time for the initial request. It can also cache static assets and full-page responses, serving them directly from the edge without ever hitting your origin server.
- Optimize server-side logic. Profile your request handler. Are you making multiple database calls in series that could be parallelized? Is there a single slow query that needs an index? Any synchronous file I/O?
- Stream the response. Instead of waiting for the entire HTML document to be generated before sending it, streaming SSR sends it in chunks. The browser can receive the
<head>, start downloading CSS, and begin rendering the top of the page while the server is still busy fetching data for components further down. This directly improves TTFB for the initial chunk.
Try it
Take a key page from an application you've worked on (e.g., a product detail page, a dashboard). Whiteboard its component structure. Identify which components are purely static and which are interactive. For the interactive ones, what client-side state do they manage? To render the page on a server, what data would you need to fetch, and what's your caching strategy for that data to ensure a low TTFB?
Next: We'll look at how to avoid the server and hydration altogether for certain types of content with Static Site Generation (SSG) for Speed and SEO.
Lock it in — apply this lesson under interview conditions.