Metrics: counts, latency, errors
Google SRE folklore calls them the four golden signals: latency, traffic, errors, and saturation. For most web backends, the first three are enough to catch the majority of outages. How slow are requests? How many are you serving? What fraction are failing? Dashboards built on those three numbers catch most problems before users do.
import { Request, Response, NextFunction } from 'express';
interface Metrics {
requests: number;
errors: number;
totalMs: number;
}
export const metrics: Metrics = { requests: 0, errors: 0, totalMs: 0 };
export function metricsMiddleware(req: Request, res: Response, next: NextFunction) {
const start = Date.now();
metrics.requests++;
res.on('finish', () => {
metrics.totalMs += Date.now() - start;
if (res.statusCode >= 500) metrics.errors++;
});
next();
}
// A minimal metrics endpoint
export function metricsHandler(req: Request, res: Response) {
const avg = metrics.requests === 0 ? 0 : metrics.totalMs / metrics.requests;
res.json({
requests: metrics.requests,
errors: metrics.errors,
avgLatencyMs: avg.toFixed(1),
errorRate: metrics.requests === 0 ? 0 : metrics.errors / metrics.requests,
});
}A minimal metrics middleware that counts requests, measures latency, and tracks errors.
This toy implementation counts in memory, which is fine for a demo but terrible in production: every instance has its own counter, the numbers reset on restart, and there is no history. In real systems you use Prometheus, OpenTelemetry, or a hosted APM. They scrape your metrics endpoint, store the time series, and draw dashboards. The concept is the same: expose the numbers, let a real system aggregate.
One refinement worth calling out: average latency lies. A few slow requests buried in a sea of fast ones are invisible in an average. Always track p50, p95, and p99 latency. The gap between them tells you where the tail hides. If your p95 is 200ms and your p99 is 3 seconds, one in a hundred users is having a bad day and your dashboard will not catch it unless you look at the right metric.
Quiz: Quiz
Loading practiceโฆ