日本語

Breaking Down Core Web Vitals TTFB with Server-Timing

​​Core Web Vitals​Chrome,Node.js,Playwright,Server-Timing,web-vitals

If you add a Server-Timing header to the HTML response that records how long the database query and template rendering took, you can read those values from serverTiming on the browser's PerformanceNavigationTiming entry. Comparing them with the TTFB measured by onTTFB from web-vitals shows how much of the TTFB is server processing and how much is everything else. On the page I tested, 301 ms of the 384 ms TTFB was the database step (db).

This is useful when PageSpeed Insights or Lighthouse's "Reduce server response times (TTFB)" audit reports a slow server response. You can record which server step is slow, alongside the TTFB measured in the user's browser.

Note

My test environment was Ubuntu 24.04, Node.js 22.23.4, Playwright 1.63.0, and web-vitals 6.2.3. I used Chrome for Testing 153, which ships with Playwright. The server was written with Node.js's http module, and the database and other steps were simulated with setTimeout waits. The server and browser ran on the same VM. I did not test with a real database or framework, a CDN, Firefox or Safari, the Chrome DevTools UI, or real user data (field data).

What TTFB includes, and what Server-Timing covers

According to web.dev's TTFB explanation, TTFB is the sum of redirects, Service Worker startup, DNS lookup, connection and TLS negotiation, and the time from sending the request until the first byte of the response arrives. A good score is 0.8 seconds or less, and anything over 1.8 seconds is considered poor. TTFB is not a Core Web Vital itself, but FCP and LCP come after TTFB, so a slow TTFB delays them too.

The last part, from request to first byte, combines server processing and network time. From the browser side, you cannot separate the two. So the server reports the time it measured itself in the Server-Timing header.

Measuring each server step and writing it to the header

As described in MDN's Server-Timing reference, each value consists of a name, an optional dur (in milliseconds), and an optional desc (description), and the values are separated by commas.

In my test server, I wrapped each step in a timed function and used the elapsed time as the header value. The database step waits 300 ms and the template step waits 60 ms, as simulations.

js
async function timed(list, name, desc, fn) {
  const t = performance.now();
  const v = await fn();
  list.push(`${name};dur=${(performance.now() - t).toFixed(1)}${desc ? `;desc="${desc}"` : ''}`);
  return v;
}

const st = [];
const start = performance.now();
await timed(st, 'auth', 'session', () => sleep(20));
await timed(st, 'db', 'article query', () => sleep(300));
const html = await timed(st, 'render', 'html', async () => { await sleep(60); return page('記事ページ'); });
st.push(`total;dur=${(performance.now() - start).toFixed(1)}`);
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'server-timing': st.join(', ') });
res.end(html);

When I checked the response headers with curl, I got the following (lines such as date are omitted).

text
$ curl -s -D - -o /dev/null http://localhost:8080/
HTTP/1.1 200 OK
content-type: text/html; charset=utf-8
cache-control: no-store
server-timing: auth;dur=20.4;desc="session", db;dur=301.3;desc="article query", render;dur=60.9;desc="html", total;dur=382.7
Transfer-Encoding: chunked

At first I put Japanese text such as "session check" in desc, but Node.js stopped with TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["server-timing"]. Node.js's http module does not accept Japanese characters in header values, so write desc using only ASCII characters (letters, digits, spaces, and so on).

Comparing serverTiming and TTFB in the browser

In the browser, performance.getEntriesByType('navigation')[0].serverTiming returns the header values as an array of objects with name, duration, and description. In the attribution build of web-vitals, onTTFB puts the navigation entry for the current page in attribution.navigationEntry, so you can also read it from navigationEntry?.serverTiming, as the type definitions describe.

I opened the page five times each with Playwright, recording the onTTFB value and serverTiming. requestDuration is the part of the web-vitals TTFB breakdown from sending the request until the first byte arrives.

Page TTFB requestDuration total auth db render
Normal (db is 300 ms) 384.4 ms 382.9 ms 381.6 ms 20.4 ms 300.8 ms 60.4 ms
db set to 1200 ms 1283.3 ms 1282.4 ms 1281.3 ms 20.2 ms 1200.6 ms 60.3 ms
Cache hit, db skipped 82.0 ms 81.1 ms 80.6 ms 20.2 ms none 60.3 ms

All values are medians of five runs. Because everything ran on the same VM, DNS and connection times (dnsDuration, connectionDuration) were under 1 ms in every run for these three pages, and most of the TTFB was requestDuration. The difference between requestDuration and the Server-Timing total was 1.4 ms or less at the median. This table shows that db accounts for most of the TTFB.

On the cache-hit page, I sent cache;desc="hit" without a dur. The browser read its duration as 0.

Time spent outside the server appears as a difference

I placed a TCP relay between the server and the browser that delays responses by 150 ms, to stand in for a distant server. These are medians of five page loads each.

Route TTFB requestDuration total requestDuration − total
Direct to server 383.2 ms 381.9 ms 381.1 ms 0.8 ms
Through a relay that adds 150 ms 534.1 ms 532.3 ms 381.2 ms 151.3 ms

The total was 381 ms in both cases, but TTFB alone grew by 151 ms. When the Server-Timing values stay the same and TTFB increases, investigate outside the server's processing, such as the network or a relay in front of the server.

Stacked bar chart of the TTFB breakdown for four cases. Normally db accounts for most of it. With db at 1200 ms, db is almost all of it. With a cache hit, it is 82 ms. Through the relay, there is about 150 ms outside the total of 381 ms
TTFB breakdown (medians of five runs). The gray area is the time not covered by the Server-Timing values. The relay row shows the difference between the median TTFB and the median total.

I also tried setting latency to 150 with Network.emulateNetworkConditions in the Chrome DevTools Protocol, but TTFB did not change for this page on localhost, so I used the relay instead.

Sending values measured in the user's browser

As described in web.dev's TTFB optimization guide, if a page sends Server-Timing, the values appear in serverTiming on the Navigation Timing entry, so you can read them in the user's browser too. In my test, I collected those values inside onTTFB and sent them to my own server with navigator.sendBeacon.

html
<script src="/wv.js"></script>
<script>
webVitals.onTTFB(({ value, attribution }) => {
  const serverTiming = (attribution.navigationEntry?.serverTiming ?? [])
    .map(({ name, duration, description }) => ({ name, duration, description }));
  navigator.sendBeacon('/collect', JSON.stringify({
    ttfb: Math.round(value),
    requestDuration: Math.round(attribution.requestDuration),
    serverTiming,
  }));
});
</script>

/wv.js is the web-vitals dist/web-vitals.attribution.iife.js file. The /collect endpoint on my server received the following.

text
collect {"ttfb":5,"requestDuration":3,"serverTiming":[{"name":"db","duration":300.5,"description":"article query"},{"name":"render","duration":60.2,"description":""}]}

This page only had fixed values written in its header, so db was 300.5 ms even though the TTFB was 5 ms. I explain why in the next section.

Things to watch out for when reading the values

Server-Timing values are exactly what the server writes. On a page that always returns a fixed db;dur=120, I read db as 120 even though TTFB was 2.3 ms. If you include a value like total that measures the whole process, you can compare it with TTFB and notice odd values.

On a page with the same fixed values, I split the Server-Timing header across two header lines, but the browser read db, render, and cdn-cache as one array.

For resources read from a different origin than the page, such as images or APIs, serverTiming is empty unless the response includes Timing-Allow-Origin (see MDN's serverTiming reference). These results come from loading a script from 127.0.0.1:8081 on a page at localhost:8080.

Response from another origin serverTiming
No Timing-Allow-Origin empty array
Timing-Allow-Origin: http://localhost:8080 db at 42 ms (desc is api)
Timing-Allow-Origin: * db at 42 ms (desc is api)

MDN notes that some browsers only expose this data in a secure context such as HTTPS. In my test with Chrome 153, a page loaded over http from an address other than localhost (where isSecureContext is false) could still read serverTiming.

Warning

MDN warns that Server-Timing can expose internal information about your application or infrastructure. Do not put table names or internal server names in name or desc. Decide which values you will send and who can see them before you add the header.

​Posted by 86