This article explains how to monitor an HTTP API in production: which signals to collect, how to instrument a service to produce them, how to alert without drowning in noise, and what usage analytics add on top. It is for developers who operate an API and want to know about problems before their users report them. The examples use Node.js with Express and Prometheus.
Monitoring answers whether the API is working right now. Analytics answers how it is being used over time. Both are built from the same raw material, which is a record of every request.
Decide what to measure
Google's Site Reliability Engineering book describes four golden signals for a user-facing system, and they are a sound starting set for any API.
- Latency is how long requests take. Track it as percentiles (p50, p95, p99) rather than an average, and separate successful requests from failed ones, since an error returned quickly would otherwise make latency look better.
- Traffic is the demand on the service, usually requests per second, broken down by route.
- Errors are the requests that fail. Count
5xxresponses separately from4xx: the first are your faults, the second are mostly the client's, though a sudden rise in4xxoften means you shipped a breaking change. - Saturation is how full the service is: CPU, memory, database connections in use, queue depth.
There are no universal targets for these numbers. An acceptable p95 for an endpoint that returns a cached lookup is very different from one that generates a report. Set a service level objective (SLO) per API from what its consumers need, for example "99.5% of requests succeed, and 95% complete within 300 ms, measured over 30 days", and judge the metrics against that.
Instrument every request
Instrumentation belongs in middleware, so that every route is covered without each handler having to remember. Two outputs are worth producing: metrics for dashboards and alerts, and a structured log line for investigation.
For metrics, a single latency histogram labelled by method, route and status code yields latency percentiles, traffic and error rate together. The setup with prom-client is shown in API Performance Optimization; the queries later in this article assume that http_request_duration_seconds histogram.
For logs, write one JSON object per request. The middleware below also assigns each request an ID, reusing one supplied by an upstream proxy if present, and returns it in the response so a client can quote it in a support request.
const crypto = require('crypto');
app.use((req, res, next) => {
const start = process.hrtime.bigint();
const requestId = req.get('x-request-id') || crypto.randomUUID();
res.set('x-request-id', requestId);
res.on('finish', () => {
const durationMs = Number(process.hrtime.bigint() - start) / 1e6;
console.log(JSON.stringify({
time: new Date().toISOString(),
requestId,
method: req.method,
route: req.route ? req.baseUrl + req.route.path : 'unmatched',
status: res.statusCode,
durationMs: Math.round(durationMs),
apiKeyId: req.apiKey ? req.apiKey.id : null
}));
});
next();
});Three details matter here. The log records the route pattern (/users/:id), which is what you group by, rather than the raw path. It records the ID of the API key, never the key itself. And it uses a monotonic clock (process.hrtime), so a system clock adjustment cannot produce a negative duration.
Pass the request ID to any downstream service you call and include it in every log line written while handling the request. When a request crosses several services, this is what lets you follow it. Distributed tracing with OpenTelemetry formalizes the same idea and adds timing for each hop.
Add health checks
A health check is an endpoint that load balancers, orchestrators and uptime monitors call to decide whether an instance should receive traffic. Two kinds are useful, and they answer different questions.
A liveness check says the process is running and able to respond. It should not depend on anything external, otherwise a database outage causes every instance to be restarted for no benefit. A readiness check says the instance can do useful work right now, so it does test critical dependencies.
app.get('/healthz', (req, res) => {
res.json({ status: 'ok' });
});
app.get('/readyz', async (req, res) => {
try {
await pool.query('SELECT 1');
res.json({ status: 'ready' });
} catch (err) {
res.status(503).json({ status: 'unavailable' });
}
});Keep both checks cheap, because they are called every few seconds, and exclude them from request metrics so they do not dilute the real traffic.
Internal checks cannot tell you that DNS, the TLS certificate or the load balancer is broken. Add an external probe that calls a real endpoint from outside your network on a schedule and checks the status code and a field in the response. This is the measurement that corresponds most closely to what users experience.
Alert on symptoms
An alert should mean that a person needs to do something. Alerts that fire without requiring action train the team to ignore them, and then the important one is ignored too.
The practical rule is to page on symptoms that users feel, namely elevated error rate, high latency and failed external probes, and to treat causes such as high CPU or a full disk as lower-priority tickets or dashboard panels. High CPU with normal latency and no errors is not an emergency.
The Prometheus rule below fires when more than 2% of requests have failed with a 5xx status for ten minutes. The threshold and duration are examples; derive yours from the SLO.
groups:
- name: api
rules:
- alert: HighErrorRate
expr: |
sum(rate(http_request_duration_seconds_count{status_code=~"5.."}[5m]))
/
sum(rate(http_request_duration_seconds_count[5m])) > 0.02
for: 10m
labels:
severity: page
annotations:
summary: "More than 2% of API requests are failing"The for clause is what prevents a brief spike from waking someone up. For latency, alert on a percentile computed from the histogram buckets:
histogram_quantile(0.95,
sum by (le, route) (rate(http_request_duration_seconds_bucket[5m])))Add one alert for the absence of data. If traffic drops to zero during hours when it never normally does, something upstream is broken, and no error-rate alert will fire because there are no requests to fail. Every paging alert should link to a short runbook that says what the alert means and what to check first.
Analyze usage
Operational metrics are aggregated and kept for weeks. Usage analytics needs the per-request records, kept for longer and attributed to a customer. The structured log line above, shipped to a data store you can query, is enough to start with.
The questions worth answering from that data are concrete ones. Which endpoints carry most of the traffic, and which are never called and could be deprecated? Which API keys send the most requests, and are any approaching their plan limit? Which clients have a high 4xx rate, suggesting they are integrating incorrectly and may need better documentation or a support email? How is traffic growing, and when will it exceed current capacity?
If you enforce quotas, track rejections as a metric of their own. A steady trickle of 429 responses for one customer is a sales conversation; a sudden burst across many customers is more likely a bug in your limiter or a retry storm.
The same applies in the other direction when you consume third-party APIs. Record the latency and status of each outbound call, labelled by provider. If you call APIStack, for example, a 429 response means you exceeded the plan's per-minute limit or monthly quota, and the response carries a Retry-After header saying how long to wait. Counting those responses tells you when it is time to add caching or move to a larger plan; the limits for each plan are listed under rate limits and quotas.
Build dashboards people read
A dashboard is for answering a question quickly, so build each one around a single question. The first should be an overview per service that shows the four signals over the last few hours: request rate, error rate, p50 and p95 latency, and saturation of the tightest resource. Someone responding to an alert should be able to tell within seconds whether the problem is real and when it started.
Put a deploy marker on every time-series panel. Most incidents begin with a change, and seeing that the error rate rose two minutes after a release shortens the investigation considerably. Below the overview, add a per-route breakdown so the responder can see whether a problem is global or confined to one endpoint.
Keep usage and business dashboards separate from operational ones. They have different readers, different time ranges and no place in an incident.
Summary
- Collect latency percentiles, traffic, errors and saturation for every route, and judge them against an objective you set for that API rather than a generic target.
- Instrument in middleware: one histogram for metrics and one structured log line per request, with a request ID and the route pattern, and without credentials.
- Separate liveness from readiness, and add an external probe that exercises the API the way a client does.
- Page only on symptoms users feel, with a
forduration to ignore blips, and alert when traffic unexpectedly disappears. - Keep per-request records attributed to an API key so you can answer usage questions and see who is hitting limits.