Web Development

Server-Timing for Small PHP Applications - Show Backend Work Without Calling It the Whole Request

Server-Timing for Small PHP Applications - Show Backend Work Without Calling It the Whole Request

A browser can show that a request spent a long time waiting for its first byte, but that does not reveal what happened inside the application. Was the database slow? Did a template take longer than expected? Did an upstream API consume most of the time? The waterfall identifies a boundary; it does not automatically explain the work behind it.

The Server-Timing response field offers a small bridge across that boundary. A server can attach selected metrics to one response, and a browser may display them in developer tools or expose them through the Performance API. That sounds simple, but useful instrumentation requires restraint. A number chosen by the application is not the whole request, a long list of internal names can leak architecture, and a precise-looking duration can still measure the wrong boundary.

What Server-Timing actually communicates

The W3C Server Timing specification defines a metric name with two optional parameters: dur for a duration and desc for a description. Multiple metrics can appear in one field:

Server-Timing: db;dur=18.4, view;dur=3.1, cache;desc="hit"

Here, db, view, and cache are names selected by the application. They are not a standard vocabulary. The duration is normally interpreted as milliseconds by the JavaScript interface, although the draft notes that a unit cannot be enforced in practice. Consistent units are therefore part of the application's contract.

The specification deliberately does not provide a server-side startTime. Client, server, and intermediary clocks cannot be assumed to be synchronized, so the browser cannot place an arbitrary server timestamp reliably on its own timeline. A metric can say that a database phase lasted 18.4 milliseconds; it does not say exactly where that phase began relative to DNS, connection setup, or another machine's work.

There is another important qualification: the W3C document published on November 2, 2026 is a Working Draft, not a W3C Recommendation. The basic feature is implemented broadly according to MDN's Server-Timing reference, but draft details and browser presentation can still evolve. An application should treat the header as useful observability metadata, not as a permanent vendor-neutral dashboard format.

It is not the same as TTFB

Chrome's Network panel documentation describes Waiting (TTFB) as including a network round trip and the time the server takes to prepare a response. The browser observes that interval from its side of the connection. A Server-Timing metric, by contrast, covers whatever interval the server code chose to measure.

Suppose an application reports app;dur=40 while the browser shows a 90-millisecond wait. It is tempting to label the remaining 50 milliseconds “the network.” That subtraction is not automatically valid. The application timer might begin after the web server accepted and parsed the request. It might omit queueing in PHP-FPM, a reverse proxy, TLS processing, response buffering, or another intermediary. Measurement overhead and clock behavior also differ.

The honest reading is narrower: the application says its defined app interval lasted about 40 milliseconds. To make that useful, document where the interval begins and ends. Do not let a short name silently acquire a larger meaning.

Design a small metric vocabulary first

A header with twenty phases can look more scientific than a header with three, yet it may be harder to interpret and more expensive to maintain. Start with boundaries tied to decisions a developer can make:

  • db: total time spent in database calls made by this request;
  • upstream: time waiting for one external service;
  • view: time spent rendering the response representation;
  • app: one documented application interval, not “everything before the first byte.”

These are examples, not recommended universal names. A database total can hide one pathological query among several normal ones. An upstream total can hide retries. Nested phases may overlap, so adding their durations may exceed the outer interval. Server Timing does not standardize parent-child relationships or guarantee that metrics form a complete accounting ledger.

Keep names stable and low-cardinality. A route name may be useful; a full URL containing identifiers, a SQL statement, a filename, a customer name, or an exception message usually is not. Descriptions are sent to the client too. The specification recommends short names and descriptions to reduce response overhead, and its privacy section warns that metrics can disclose application or infrastructure information.

A restrained PHP example

PHP's hrtime() documentation says the timestamp is monotonic and cannot be adjusted. That makes differences between two readings suitable for elapsed-time measurement. With true, a 64-bit platform returns a numeric nanosecond value. The following example converts those differences to milliseconds:

<?php
$requestStart = hrtime(true);

$dbStart = hrtime(true);
$rows = loadVisibleArticles();
$dbMs = (hrtime(true) - $dbStart) / 1e6;

$viewStart = hrtime(true);
$html = renderArticleList($rows);
$viewMs = (hrtime(true) - $viewStart) / 1e6;

$appMs = (hrtime(true) - $requestStart) / 1e6;

$metric = static fn (float $value): string =>
    number_format($value, 1, '.', '');

header(sprintf(
    'Server-Timing: db;dur=%s, view;dur=%s, app;dur=%s',
    $metric($dbMs),
    $metric($viewMs),
    $metric($appMs)
));

echo $html;

The two application functions are placeholders, not benchmark results. The useful pattern is the boundary: read a monotonic clock immediately around the work, convert one known unit, format it predictably, and emit fixed metric names. The PHP header() manual also requires the field to be scheduled before actual output. A framework may provide its own response-header API, which is often a better integration point than calling header() deep inside business code.

This example rounds to one decimal place because extra digits do not create extra accuracy. It also avoids putting dynamic labels into the field. If a description must contain spaces, quote it according to the field syntax and construct it from a controlled vocabulary rather than raw user or database text.

Read the metrics in the browser

Developer tools can surface the metrics alongside a request's timing information, although the exact interface varies by browser. They are also available as PerformanceServerTiming objects attached to navigation and resource timing entries. MDN documents the name, duration, and description properties.

For a same-origin page, a small inspection snippet can read the current navigation entry:

const [navigation] = performance.getEntriesByType('navigation');

for (const metric of navigation?.serverTiming ?? []) {
  console.table({
    name: metric.name,
    duration: metric.duration,
    description: metric.description
  });
}

This is convenient for diagnostics and carefully designed real-user monitoring, but collection changes the responsibility of the feature. Once metrics are sent to analytics, retention, sampling, user consent, access control, and the possibility of sensitive labels all need review. A browser-visible field should be treated as disclosed data, not as a private log line.

Cross-origin visibility is a separate decision

Script access to detailed timing information is restricted by origin by default. A resource provider can use Timing-Allow-Origin to permit specified origins to see otherwise restricted Resource Timing values, including server timing entries. The MDN Timing-Allow-Origin reference emphasizes that this permission is independent of CORS.

Timing-Allow-Origin: https://app.example.test

Passing a CORS check does not by itself reveal detailed timing, and granting timing access does not grant JavaScript access to a response body. They answer different questions. A wildcard may be acceptable for intentionally public, coarse metrics, but it should not be copied onto responses that reveal internal service names, tenancy information, cache topology, or user-specific behavior.

Operational limits matter more than syntax

Cached responses can make a metric historical

RFC 9111 generally requires caches to retain received response fields when storing a response. If a cache reuses that response, its Server-Timing values may describe the request that created the cached representation rather than fresh origin work. That can be useful when a cache intermediary adds its own metric, but misleading when an old application duration looks current. Define whether the response may be cached and what each metric means on a cache hit.

Sampling can be more honest than universal detail

Instrumentation consumes CPU, code complexity, and header bytes. Expensive profiling should not be smuggled into every public request merely because the final transport is one field. A small set of cheap timers may be safe on every response; deeper metrics may belong behind authentication, a diagnostic flag protected by authorization, or controlled sampling. The selection rule should live in application code, not in user-supplied metric names.

One request does not establish a trend

A single slow db value is a clue, not a diagnosis. It does not identify the query, lock, data distribution, or system load that produced it. Aggregates can reveal distributions, but they can also mix routes, cache states, deployments, and user populations until the average means little. Keep dimensions bounded and compare like with like.

What Server-Timing should not replace

Server Timing is best understood as a client-visible summary of selected work. Logs remain better for discrete events and errors. Distributed traces preserve relationships across services. Database slow-query logs identify statements. Profilers show where code consumes CPU. Request IDs connect evidence without exposing all of it in the response.

Those tools can support a claim that a phase is slow and help explain why. The header makes a narrower contribution: it puts a few server-defined measurements next to the browser's view of one request. That proximity can shorten an investigation, but it does not remove the need for server-side evidence.

A modest adoption checklist

  • Name each metric and write down its exact start and end boundaries.
  • Use a monotonic elapsed-time source and one consistent unit.
  • Expose only values that are safe for the response's audience.
  • Keep names, descriptions, and dimensions short and bounded.
  • Check cache behavior, reverse proxies, and framework header handling.
  • Test what DevTools and the Performance API actually show in supported browsers.
  • Decide separately whether cross-origin scripts should receive timing access.
  • Correlate unusual values with logs, traces, or profiles before assigning a cause.

Conclusion

Server-Timing can make a browser waterfall less opaque without pretending that the browser can see inside the server. Its value comes from carefully named boundaries: a database interval, an upstream wait, a render phase, or another small piece of work that the application can measure consistently.

The field becomes misleading when it is treated as the whole request, when unrelated phases are added as if they never overlap, or when internal detail is exposed simply because developer tools can display it. Start with a few safe metrics, document what they exclude, and let richer server-side observability answer the questions that a response header cannot.

References