Measuring the cost of a request
You do not need a distributed tracing platform to find slow paths. You need a timestamp at the edges and the discipline to look at the gap.
Most performance work starts with a tool and ends with a number nobody trusts. It is more useful to start with a question: from the moment a request arrives to the moment the response leaves, where did the time go?
Two timestamps are enough to begin
Before adding spans, exporters, and dashboards, log two things per request: when it started and when it finished. That gives you a distribution of total latency, split by route. Almost every project has one route that dominates, and almost nobody looks at it first.
const start = performance.now();
try {
return await handler(req);
} finally {
log.info({
route: req.route,
ms: performance.now() - start,
status: res.statusCode,
});
}
This takes twenty minutes and immediately answers the question “is this actually slow, or does it just feel slow?”
Find the gap, then add a span
Once a route is identified, add spans around the handful of things it does: a database query, an outbound HTTP call, serialization. You are looking for the unaccounted time — the gap between the total and the sum of the parts.
Common culprits:
- N+1 queries. The total looks like “database”, but it is 40 individual queries each waiting on a round trip.
- Serialization. A large JSON response can cost more CPU than the query that produced it.
- Connection setup. A new TLS handshake per request will dominate everything else and never show up in application timings.
- Lock contention. Time spent waiting for a pool is invisible unless you measure acquisition separately from use.
Percentiles, not averages
An average of 120ms can hide a p99 of four seconds. Report p50, p95, and p99. If you only have room for two numbers, use p50 and p99; the tail is where users notice.
Also measure at the edge, not just inside the application. A p99 of 80ms in the app and 1.2s at the client usually means the network, a proxy, or a cold connection — all of which sit outside your request handler.
The uncomfortable part
Most performance work is not optimization. It is removing work:
- Delete a query nobody reads.
- Cache a value that changes hourly.
- Paginate a response that returns everything.
- Stop logging a megabyte of JSON per request.
The fastest code is the code that does not run. Measurement matters because it tells you which code that is, and it keeps you from spending a week optimizing the part that was already fast.
A small checklist
- Log total latency by route. Find the worst one.
- Add spans until the time is accounted for. Investigate the gap.
- Check the tail, not the average.
- Measure from the client’s side at least once.
- Remove work before making work faster.
That is the whole method. It scales from a side project to a service with real traffic, and it does not require a vendor.