Why TTFB matters

Time to First Byte (TTFB) is the earliest performance milestone in any page load. Every metric that follows—First Contentful Paint (FCP), Largest Contentful Paint (LCP), and beyond—inherits any delay introduced before the server sends its first byte. A slow TTFB therefore pushes every downstream measurement later.

A good target is a TTFB of 0.8 seconds or less for the 75th percentile of users, which generally keeps FCP within the "good" threshold.

Measuring TTFB in the field and the lab

Field data should be your primary source for TTFB, because real-world navigation can include redirects that lab tools often skip by measuring the final URL. PageSpeed Insights provides both field data from the Chrome User Experience Report and lab results for public pages. Real-user TTFB appears in the "Discover what your real users are experiencing" section, while lab issues surface under the Document request latency insight.

When field and lab values diverge, the cause matters:

  • Lab TTFB much higher than field TTFB usually means the lab environment is more constrained than typical user conditions. Recommendations remain valid, but the perceived impact may be overstated.
  • Field TTFB much higher than lab TTFB points to issues the lab cannot see: server-side caching, redirects, or network conditions. Test uncached content, such as less common pages or distinct URL parameters, to see whether caching is masking the problem in lab runs. Traffic analytics can help diagnose redirects and network-related causes.

Using Server-Timing to isolate backend latency

To pinpoint which backend processes contribute to high TTFB, instrument your server with the Server-Timing response header. Its value accepts a handle, an optional dur attribute for duration in milliseconds, and an optional desc description, with entries separated by commas:

// Two metrics with descriptions and values
Server-Timing: db;desc="Database";dur=121.3, ssr;desc="Server-side Rendering";dur=212.2

Typical processes to measure include database queries, server-side rendering time, disk seeks, and CDN cache hits or misses at the edge. For example, in PHP you might set the header like this:

<?php
// Get a high-resolution timestamp before
// the database query is performed:
$dbReadStartTime = hrtime(true);

// Perform a database query and get results...
// ...

// Get a high-resolution timestamp after
// the database query is performed:
$dbReadEndTime = hrtime(true);

// Get the total time, converting nanoseconds to
// milliseconds (or whatever granularity you need):
$dbReadTotalTime = ($dbReadEndTime - $dbReadStartTime) / 1e+6;

// Set the Server-Timing header:
header('Server-Timing: db;desc="Database";dur=' . $dbReadTotalTime);
?>

Once set, this header populates the serverTiming property in the Navigation Timing API for field observation:

// Get the serverTiming entry for the first navigation request:
performance.getEntries('navigation')[0].serverTiming.forEach(entry => {
  // Log the server timing data:
  console.log(entry.name, entry.description, entry.duration);
});

In Chrome DevTools, the same data appears in the Timings panel of the Network tab, showing, for instance, whether a resource hit the CDN cache and how long the request took to reach the edge and origin. Server timings are equally visible in the Network track of the Performance panel. Once you have pinpointed the latency source, you can begin addressing it.

Where to start: hosting, platforms, and infrastructure

The most challenging aspect of optimizing TTFB is that while the web's frontend stack is always HTML, CSS, and JavaScript, backend stacks can vary significantly. There are numerous backend stacks and database products, each with their own optimization techniques. This section covers what applies to most architectures rather than focusing strictly on stack-specific guidance.

Your platform can heavily impact TTFB. For example, WordPress performance is affected by the number and quality of plugins, or which themes are used. Similar impacts occur when other platforms are customized. Consult your platform's documentation for vendor-specific advice to supplement the general performance guidance in this article. The Lighthouse insight also includes some limited stack-specific guidance.

Evaluate hosting before everything else

Hosting should be the first consideration, before other optimization approaches. There's limited specific guidance to offer here, but a general rule of thumb is to ensure that your website's host is capable of handling the traffic you send to it. Shared hosting is generally slower. For a small personal website serving mostly static files, this is probably fine; use the optimization techniques that follow to reduce TTFB as much as possible. For a larger application with many users involving personalization, database querying, and other intensive server-side operations, hosting choice becomes critical to achieving low TTFB in the field.

When choosing a provider, look for these qualities:

  • Adequate memory: If your application instance has insufficient memory, it will thrash and struggle to serve pages quickly.
  • Up-to-date backend stack: As new versions of backend languages, HTTP implementations, and database software are released, performance improves. Partner with a host that prioritizes this maintenance.
  • Configuration access: For specific application requirements and the lowest-level access to server configuration files, ask whether it makes sense to customize your own application instance's backend.

Many hosting providers handle these concerns for you, but if you observe long TTFB values even on dedicated hosting, it may be time to re-evaluate the provider's capabilities.

Put a CDN in front of origin

You could have a very well-optimized application backend, but users located far from your origin server may still experience high TTFB in the field. CDNs solve the distance problem with a distributed network of edge servers that cache resources physically closer to users. CDN providers also typically offer additional benefits:

  • Extremely fast DNS resolution times.
  • Serving content over modern protocols such as HTTP/2 or HTTP/3; HTTP/3 in particular solves the head-of-line blocking problem of TCP by using the UDP protocol.
  • Modern versions of TLS, which lower negotiation latency. TLS 1.3 is designed to keep negotiation as short as possible.
  • An "edge worker" feature that uses an API similar to the Service Worker API to intercept requests, manage responses in edge caches, or rewrite responses.
  • Strong compression handling, which is tricky to implement correctly—especially for dynamically generated markup that must be compressed on the fly. CDN providers also cache compressed responses for static resources.

While adopting a CDN involves varying effort from trivial to significant, it should be a high priority for optimizing TTFB if your website doesn't already use one.

Mitigating response delays on the server side

Cache content wherever possible

CDNs cache content at edge servers provided it carries the appropriate Cache-Control HTTP headers. However, this isn't appropriate for personalized content, and requiring a trip back to origin negates much of the CDN's value. For sites that update frequently, even a short cache duration produces noticeable gains on busy sites: only the first visitor in that window pays the full round trip to origin, while others reuse the cached edge response. Some CDNs allow cache invalidation on site release, giving long cache times with instant updates.

Two issues can undermine well-configured caching. Unique query string parameters for analytics measurement can make identical resources look different and bypass the cache. And older or less-visited content may miss the cache entirely, causing higher TTFB on some pages than others; increasing cache times reduces this but raises the risk of serving stale content.

The benefits of cached content also apply beyond CDNs. Server infrastructure may need to generate content from costly database lookups when cached content can't be reused, so more frequently accessed data or precached pages often perform better.

Eliminate redirect chains

Redirects occur when a navigation request receives a response indicating the resource lives elsewhere. One redirect adds unwanted latency, but a redirect that points to another redirect—and so on—is much worse. This particularly affects sites receiving heavy traffic from ads or newsletters, as those links often pass through analytics services. Two types exist:

  • Same-origin redirects: Entirely on your website.
  • Cross-origin redirects: Start on another origin (such as a URL shortener) before arriving at yours.

Focus on eliminating same-origin redirects since they're under your direct control. Audit links for 302 or 301 responses, which are often caused by an omitted https:// scheme (so browsers default to http:// and redirect) or by inconsistent trailing slashes in URLs. Cross-origin redirects are harder to control, but avoid stacking them—for example, don't use multiple link shorteners—and give advertisers or newsletters the correct final URL.

HTTP-to-HTTPS redirects can also be a source of redirect time. The Strict-Transport-Security header (HSTS) enforces HTTPS on the first visit to an origin and makes future visits head straight to the HTTPS scheme. After a good HSTS policy is in place, adding your site to the HSTS preload list similarly speeds up the origin's first visit.

Stream markup as soon as it's ready

Browsers are engineered to process markup incrementally as chunks arrive from the server rather than waiting for the entire response. This matters for large markup payloads. However, it's crucial to keep the stream moving; if the backend holds things up, those initial bits of markup are delayed, and every backend stack has its own potential issues.

Frameworks like React that render markup on demand have traditionally used a synchronous approach to server-side rendering. Newer versions of React include server methods for streaming markup as it's rendered—so you don't wait for the full render to complete before sending the response.

Static rendering, which generates HTML files at build time, can also help. With the full file available immediately, web servers can start sending right away and the inherent nature of HTTP results in streaming markup. While not suitable for pages requiring dynamic, personalized responses, it benefits pages that don't need per-user customization.

Advanced client- and server-side techniques

Leverage a service worker

The Service Worker API can greatly affect TTFB for both documents and the resources they load. A service worker proxies between the browser and server, and its impact depends on how you set it up and whether that aligns with your application's needs.

  • Use a stale-while-revalidate strategy for assets. If a document or required resource is in the cache, this strategy serves it from cache first, then downloads the asset in the background for future interactions. For documents that rarely change, TTFB becomes nearly instant. But for dynamically generated markup—such as content varying by authentication status—you'll always want to hit the network first for freshness. For non-critical resources that change with some frequency, serving the stale copy barely affects user experience and greatly reduces TTFB.
  • Use the app shell model for client-rendered applications. Best suited for SPAs, this delivers the "shell" of the page instantly from the service worker cache, with dynamic content populated and rendered later in the page lifecycle.

Warm up the connection with 103 Early Hints

Even a well-optimized backend can require significant work—including expensive but necessary database queries—which delays the navigation response. The side effect may be delayed render-critical resources such as CSS or client-rendering JavaScript. The 103 Early Hints response code is sent to the browser while the backend is still preparing markup. It hints to the browser which render-critical resources to begin downloading immediately. For supporting browsers, this produces faster document rendering and quicker page loads.

One catch: like caching, Early Hints can mask a site's "real" TTFB. If server infrastructure is slow—underpowered or in need of code optimization—that's less obvious when 103 Early Hints makes TTFB look fast. Sites using Early Hints should measure actual server time via the Server-Timing header or the finalResponseHeadersStart metric of the PerformanceNavigationTiming API.

Working Backward from the Browser

When TTFB is high, the browser is not the bottleneck. The delay happens further up the chain, before the first packet of the response arrives. To find it, start with the server's access logs and see how long the application actually took to generate the response. If that time is near zero, the problem is network latency or the CDN’s cache hit ratio, not the backend.

If the application itself is slow, the next step is to isolate whether the delay is in the framework’s bootstrap, the database queries, or an external API call. A common culprit is the web server configuration — for instance, a reverse proxy that is not configured for keep-alive connections to the upstream application server will add a round trip for every request.

Application-Level Adjustments

For dynamic sites, the most effective change is often caching at the application layer. If the response doesn't need to be unique per user, storing the rendered HTML in memory or in a fast key-value store removes the database and template engine from the critical path entirely. For responses that are user-specific, consider fragment caching for the expensive parts, like sidebars or recommendation blocks, and only render the truly dynamic portion per request.

Another route is to move work out of the request cycle. If the page needs data from a slow external service, fetch that data asynchronously and cache it. Similarly, heavy computation that happens on every request should be moved to a background job that writes its result to a cache. These changes may not reduce the time for the first uncached request, but they will help for the majority of subsequent ones.

Framework-level settings also matter. Many stacks enable debug mode or development error pages by default, which can significantly slow down response generation due to logging and stack trace collection. Ensure the server runs in its production configuration, with opcode caching enabled for PHP and the equivalent for other interpreted languages.

Network and Infrastructure Tuning

The distance between the user and the server is a hard limit on TTFB. A CDN that serves static assets does not help if the HTML document itself is dynamic, but a CDN that can proxy and cache at the edge can cut the round trip time for repeat visitors. If the entire site is dynamic and cannot be cached, consider moving the application to a hosting region closer to the primary user base or using a provider with a well-optimized network path.

On the server side, check for unnecessary redirects and ensure that TLS session resumption is working. A redirect from http to https sends the user to a different origin, which requires a new connection setup. For modern browsers, eliminate any redirects that are not strictly necessary, particularly those that change the hostname, as they force a new DNS lookup and a new TLS handshake.

Continuous Verification

Optimizing TTFB requires the same iterative loop as any other performance work: measure in the field, reproduce in the lab, fix, and re-measure. Changes that help in a synthetic test may not translate to real-user conditions, particularly if the issue is related to network congestion or server load. Keep an eye on the real-user monitoring data to ensure that a fix for one set of conditions doesn't create a problem for another group of visitors.

There is no single solution that works for every stack. But the general principle holds: reduce the number of sequential round trips between the client and the server, and reduce the amount of work done between the first request and the first byte of the response. Apply these techniques where they fit, and rely on field data to guide any further adjustments.