How-To Guide

How to Implement Server-Timing Headers

Record and expose Server-Timing metrics, break down where request time goes, and use the header to debug latency without a denylisting conversation.

On this page

  1. Introduction
  2. Instrument the phases
  3. Emit the header correctly
  4. Gate and sanitize by environment
  5. Correlate with traces and logs
  6. Test that the header is present and valid
  7. Common pitfalls
  8. Conclusion

Introduction

When a request is slow, the first question is where the time went. Without instrumentation, the answer comes from a profiling session that may not capture the exact production conditions. Server-Timing offers a lightweight alternative: the server records durations for internal phases and returns them in a response header, so the same request that was slow also carries a breakdown of why. It is a diagnostic that travels with the traffic instead of requiring a separate investigation.

This tutorial instruments a Node.js request handler to record database, cache, and downstream durations, emit them in a Server-Timing header, and keep the output safe and small. It covers the header grammar, environment gating, correlation with trace IDs, and the tests that keep the header well-formed.

Instrument the phases

Wrap each significant phase in a high-resolution timer. Use performance.now rather than wall-clock time, because it is monotonic and unaffected by clock adjustments, and record the elapsed duration in milliseconds. Name each metric with a short, stable identifier such as db, cache, or api, and keep the set small: a header with twenty metrics is noise, while three or four that map to real bottlenecks are actionable.

Measure the phases you actually suspect, not everything. The database query, the cache lookup, and outbound calls are the usual suspects; the time spent in your own serialization is usually small. If a phase is too fast to measure reliably, its absence from the header is itself informative. Avoid measuring inside a loop and reporting the sum without noting that it aggregates many calls, or the number will mislead.

class Timing {
  constructor() { this.metrics = []; }
  async measure(name, fn) {
    const start = performance.now();
    try {
      return await fn();
    } finally {
      this.metrics.push({ name, dur: performance.now() - start });
    }
  }
  header() {
    return this.metrics
      .map((m) => m.name + ';dur=' + m.dur.toFixed(1))
      .join(', ');
  }
}

const timing = new Timing();
await timing.measure('db', () => db.query('select 1'));
await timing.measure('cache', () => cache.get('user:1'));

Emit the header correctly

The Server-Timing grammar is a comma-separated list of metrics, each with a name and optional parameters. The common parameter is dur, the duration in milliseconds with a decimal fraction. A metric may also carry a desc string describing it and any number of extension parameters. Round durations to one decimal place; excessive precision inflates the header without adding information.

Keep the header within a sane size. Headers count toward the response and some proxies or clients cap them, so a hundred-metric header risks being dropped or slowing every response. Emit a handful of the most relevant metrics per request and rely on sampled detailed logging for the rest. Set the header before sending the body, since headers cannot be changed afterward.

function writeTiming(res, timing, opts = {}) {
  const metrics = opts.detailed
    ? timing.metrics
    : timing.metrics.filter((m) => m.dur >= 5); // only notable phases in prod
  if (metrics.length === 0) return;
  res.setHeader('Server-Timing',
    metrics.map((m) => m.name + ';dur=' + m.dur.toFixed(1)).join(', '));
}

writeTiming(res, timing, { detailed: process.env.NODE_ENV !== 'production' });

Gate and sanitize by environment

In development, expose every metric with descriptive names so a developer sees the full picture. In production, expose a curated subset, and use generic names that do not reveal internal topology. A metric desc such as ‘primary-postgres-12’ or a name that embeds a queue topic tells an attacker about your infrastructure. Keep names to a small fixed vocabulary and drop the desc parameter in production.

Never include user data, query text, or connection strings. The durations are safe; the labels are the risk surface. Treat the header value as public output that happens to describe internal timing, and review it as you would any other response field that leaves the trust boundary.

Correlate with traces and logs

Server-Timing is most useful when it ties to the rest of your observability. Include the request ID or trace ID so a slow header can be matched to the corresponding server-side trace, and emit the same durations to your metrics system so you can alert on them. The header answers what was slow for this one request; the metrics answer whether it is a trend.

Record the same phase names in structured logs so a search for one request yields both the log lines and the header value. Consistency between the header names and the log field names lets a dashboard join them without a translation layer.

function logTimings(logger, timing, requestId) {
  for (const m of timing.metrics) {
    logger.info('phase', { requestId, phase: m.name, durMs: Number(m.dur.toFixed(1)) });
  }
}

Test that the header is present and valid

Add a test that asserts the header exists, parses as a comma-separated list, and contains the expected metric names with numeric dur values. Add a test that a production environment drops metrics below the threshold and omits descriptions. Finally, assert the header does not contain a hostname or a user identifier, which turns the sanitization rule into an enforced invariant.

curl -sD - -o /dev/null http://localhost:3000/report | grep -i server-timing
# expect: Server-Timing: db;dur=12.4, cache;dur=0.8, api;dur=31.2

Common pitfalls

Recording every phase so the header becomes noise, leaking internal names in descriptions, using wall-clock time that jumps under clock changes, reporting aggregate durations without saying they are aggregates, and omitting the sampling strategy so production headers vary unpredictably are the recurring mistakes. A fixed metric vocabulary, environment gating, and a header-validity test address them.

Conclusion

Server-Timing turns a slow request into its own explanation. Instrument a few meaningful phases with a monotonic timer, emit a small well-formed header, gate detail by environment, and never leak topology in names or descriptions. Self-check by asserting the header parses and by confirming production omits descriptions and low-value metrics. Correlated with trace IDs, it becomes the front edge of a latency investigation rather than a guess.

Sources: W3C: Server Timing, MDN: Server-Timing header, MDN: PerformanceServerTiming.

FAQ

Is Server-Timing visible to browsers?
Yes. The header is exposed to JavaScript through the Performance API and is shown in browser devtools, which makes it a convenient way to show users or developers where time went without a separate profiling session.
Does exposing timings leak sensitive information?
The durations themselves are usually safe, but metric names and descriptions can leak internal topology, such as a database host or a queue name. Keep names generic in production and never include connection strings, query text, or user identifiers.

Related Examples