A production API needs a way to tell its owner that users are having a problem and enough evidence to investigate it. That requirement can fit into a small setup. Begin with an external check, structured request logs, captured application errors, a few service measurements, and a notification route somebody actually watches.
The question appeared directly in a May r/node discussion about monitoring for solo developers. The author described a gap between having no monitoring and adopting a large platform. The replies discussed combinations of uptime checks, error tracking, and hosting logs. Those combinations are useful starting points, but the practical test is whether they can explain a failed user request.
This guide builds a small, dependency-free Node example to make that test concrete. It intentionally fails one endpoint, records the failure with a request identifier, and detects the problem through an independent HTTP check. The accompanying examples were checked with Node 22.12.0. The service measurements illustrate what to collect; the small JSON metrics endpoint is a teaching interface, not a replacement for an established metrics collector.
Download the complete runnable examples, including setup instructions and verification commands.
Start with four questions the setup must answer
Describe one important user operation before choosing a dashboard. For an order API, that might be retrieving the current user's orders. Decide what success looks like from the caller's perspective: an acceptable status, a valid response shape, and a bounded response time. A process accepting TCP connections is weaker evidence than a completed operation.
The first question is whether a user outside the server can complete that operation. The second is which requests failed and which release handled them. The third is whether the service is approaching a resource or dependency constraint. The fourth is who receives a useful notification when the problem requires intervention.
Keep the initial scope narrow. An external check covers availability of a chosen path. Logs describe individual events. An error tracker groups exceptions and can connect them to releases. Service measurements show changing rates and durations. OpenTelemetry's signal documentation distinguishes related outputs such as metrics, logs, and traces; each gives a different view of activity. You can adopt that vocabulary without immediately deploying every component.
Write down the limitations beside the design. A public read check may miss a broken authenticated checkout. An exception tracker may miss an incorrect success response. Hosting logs may disappear after their retention window. Making those gaps explicit helps you decide what to add when the application grows.
Collect enough evidence to move from a failed user operation to a specific investigation.
Keep liveness, readiness, and user success distinct
A cheap liveness endpoint answers whether this process can respond. A readiness endpoint answers whether the instance should currently receive application traffic. A synthetic user check answers whether a selected operation succeeds through its real entry point. Give each a clear purpose so one green badge cannot conceal another failing path.
Kubernetes documents separate probe behavior: readiness controls whether a pod receives service traffic, while liveness can trigger a restart. These distinctions are useful on a VPS or managed application host too. A database outage is a reason to investigate dependency availability; repeatedly restarting every application instance may add disruption without repairing the database.
The example exposes /livez and /readyz. Its readiness callback reads cheap application-owned state synchronously. In a real service, update that state using bounded dependency checks and account for startup and shutdown. Avoid making every health request run an expensive database query. A monitoring system should not become a source of load during the incident it is trying to detect.
if (route === '/livez') return json(200, { alive: true });
if (route === '/readyz') {
const canServe = Boolean(ready());
return json(canServe ? 200 : 503, { ready: canServe });
}Keep detailed dependency information behind an appropriate access boundary. Public checks usually need a status and a small response, not database hostnames or connection errors. Test readiness transitions during startup and a simulated dependency failure before connecting them to a load balancer.
Make a request discoverable in the logs
Generate a request identifier at the trusted application boundary and return it in a response header. Record the same identifier when an operation fails and when the HTTP response finishes. Add a release identifier so a developer can distinguish a new defect from an older recurring failure.
Use structured fields instead of a sentence that has to be parsed later. The example records the event, timestamp, request identifier, route name, method, status, and elapsed time. It uses an allowlist of routes and records unknown paths as unmatched. That avoids turning customer-specific paths or arbitrary query strings into logging labels.
const requestId = randomUUID();
const started = performance.now();
res.setHeader('x-request-id', requestId);
res.once('finish', () => {
log('request_finished', {
request_id: requestId,
route,
method: req.method,
status: res.statusCode,
duration_ms: performance.now() - started
});
});Node's HTTP response documentation explains that finish concerns handing the response to the operating system; it does not prove that the remote client received it. The companion code records a separate aborted-request event when the connection closes before completion. Keep that interpretation in mind when investigating network failures.
You can pass the identifier explicitly through a small application. As asynchronous layers multiply, AsyncLocalStorage can carry request context through asynchronous work created within its scope. Test the integration where custom callbacks or event emitters cross boundaries. Context that is present in the initial handler may be missing in a later background task unless you deliberately preserve it.
Capture errors at the boundary that can explain them
Catch expected request-level failures where the application can produce an appropriate response. Send a stable public error code and the request identifier to the caller. Keep diagnostic details in the restricted logging or error-reporting system. A user should have something useful to report without receiving an internal stack trace.
In the lab, an opt-in failure throws an error with the code DEMO_FAILURE. The request handler records the code and stack with the current request identifier, then returns HTTP 500. This creates a deterministic investigation exercise. It does not pretend to reproduce every dependency or process failure.
}).catch(error => {
log('request_failed', {
request_id: requestId,
route,
error: { name: error.name, code: error.code || 'INTERNAL',
stack: error.stack }
});
json(500, { error: 'internal_error', request_id: requestId });
});In production, review what an error object can contain. Error messages may embed customer data, SQL fragments, or third-party responses. Apply redaction before transmission and limit who can search the retained records. The example deliberately avoids logging authorization headers, bodies, or the raw URL, but that does not make arbitrary production error messages safe.
Use an existing error tracker if grouping, source mapping, release comparison, or notifications save operational work. Confirm that an intentionally thrown error reaches the right project and release. Request-level recovery is separate from fatal process faults: Node's process documentation cautions against resuming normal execution after an uncaught exception. Use an external supervisor and test its recovery behavior.
Add a few measurements with bounded labels
Start with request volume, failed-request rate, and response duration for important routes. Add instance memory, restart events, and event-loop delay where they help diagnose the Node process. For a background worker, include oldest pending job age and failed-job counts; healthy HTTP traffic alone cannot establish that the worker is making progress.
Use a real metrics backend or your hosting platform's instrumentation for aggregation across instances and historical comparisons. The lab keeps only per-route counts and a duration sum in memory. Its values reset on restart. It does not calculate a fleet percentile or retain an incident history, and its /metrics endpoint is JSON rather than Prometheus exposition format.
The runtime sample uses Node's event-loop delay histogram. Convert nanoseconds to milliseconds and reset the histogram between reporting windows. Before the histogram has samples, emit an unavailable value rather than treating an empty sample as evidence of healthy scheduling.
const lag = monitorEventLoopDelay({ resolution: 20 });
lag.enable();
const p99 = lag.count ? lag.percentile(99) / 1e6 : null;
log('runtime_sample', {
rss_bytes: process.memoryUsage().rss,
event_loop_p99_ms: p99
});
lag.reset();A high reading is a reason to investigate workload and scheduling. It does not identify the responsible function. Compare it with request duration, CPU evidence, recent changes, and relevant dependency timing. Keep identifiers such as user IDs, raw URLs, and request IDs out of metrics labels. They belong in appropriately controlled event records, where individual investigations need them.
Run the external check from somewhere independent
Point an uptime service or a small scheduled checker at the public hostname and an operation you can safely repeat. A checker running inside the same instance cannot report that the instance lost power. Choose a location and notification mechanism that can still operate when the application host fails.
Validate more than an HTTP success code. The example checker requests /orders, requires status 200, and confirms that orders is an array. Its timeout bounds how long one attempt waits. Use a dedicated synthetic account for authenticated operations and isolate its test data so the check does not create real customer activity.
const response = await fetch(url, {
signal: AbortSignal.timeout(3000), redirect: 'error'
});
const body = await response.json();
return response.status === 200 && Array.isArray(body.orders);Choose check frequency from the detection time the business needs and the load the operation creates. Requiring repeated failures can suppress transient noise while delaying notification. Check timeouts, polling intervals, and confirmation rules all contribute to that delay. Treat the lab's three failed checks as a demonstration policy to change deliberately, not a universal production threshold.
Practice one complete investigation
Run the example in a local terminal with its deliberate failure enabled. The server binds to loopback, and its output is JSON Lines. Start the checker in a separate terminal. It writes status and incident transitions to standard output; connecting an approved notification provider is a deployment task rather than something the sample silently does.
DEMO_FAIL=1 RELEASE_ID=monitoring-demo node server.mjs > demo.jsonl
curl -i http://127.0.0.1:3000/orders
node monitor.mjs http://127.0.0.1:3000/ordersCopy the x-request-id from the failed response and find its matching records. The request_failed record should name DEMO_FAILURE and the release, while the completion record should show the route and HTTP 500. The independent checker should also reject the operation. These are different observations of the same deliberate problem.
Stop the server and restart without DEMO_FAIL=1. Confirm that /orders returns the expected shape and that the checker records recovery. The automated tests exercise these behaviors, verify readiness separately from liveness, check that sensitive request values are absent from the log records, and confirm that repeated failures create one incident transition rather than repeated alerts.
node --test server.test.mjsA small monitoring setup earns its place when this investigation can be completed using evidence it already captured.
Make every alert carry an action
Route a confirmed availability failure to the person responsible for restoring the service. Include the operation, environment, first observed time, release, and a link to a short runbook. Group repeated observations into one incident and send a recovery notification when the operation succeeds again. The lab's state machine demonstrates those transitions; its in-memory state disappears when the monitor restarts.
Separate urgent incidents from work that can wait. A failed customer operation may need immediate attention. A gradual storage trend may belong in a daytime task with a capacity forecast. Google's monitoring guidance emphasizes actionable, low-noise notifications and the cost of interrupting people. Review whether an alert changed a decision after each incident.
Agree on coverage honestly. A solo developer who cannot respond overnight should not imply round-the-clock support through a dashboard setting. Document the response expectation, escalation route, and temporary mitigation. A second recipient needs access to the runbook and relevant systems before an outage makes that access urgent.
Keep a small maintenance routine. Check that retention still covers useful investigation windows, the synthetic account still works, and the notification destination still reaches its owner. Re-run the deliberate failure after replacing a logger, changing deployment configuration, or moving the service. Add distributed tracing or deeper profiling when an investigation demonstrates the missing evidence. The next monitoring component should solve a problem you can name and verify.




