perf_hooks.monitorEventLoopDelay is the metric that would have caught every blocked-event-loop incident described elsewhere in this domain, confirmed working in this app's installed runtime. Structured logging, health checks, and AsyncLocalStorage-based request IDs round out what production Node.js needs beyond 'it works locally.'
1. What's the main advantage of structured (JSON) logs over plain text logs in production?
Interview Questions
2 questions
Cheatsheet
Download-ready reference
Cheatsheet
STRUCTURED LOGGING: emit JSON, not prose, console.log(JSON.stringify({ level, event, ...context }))
โ precisely QUERYABLE at scale, unlike plain text.
(pino et al build on this + add perf/filtering)
HEALTH CHECKS, genuinely DIFFERENT questions:
LIVENESS โ "is the process alive at all?" โ fail = RESTART
(keep lightweight, minimal deps)
READINESS โ "can it serve traffic RIGHT NOW?" โ fail = PAUSE traffic
(CAN depend on DB/downstream, that's the point)
โ ๏ธ conflating them โ downstream blips cause UNNECESSARY restarts
diagnostics_channel: pub/sub for INSTRUMENTATION, app code publish()es with NO knowledge of listeners;
APM/monitoring tools subscribe() with ZERO app-code changes.
perf_hooks.monitorEventLoopDelay({ resolution }):
histogram.enable() / .mean / .max / .percentile(p) / .reset()
โ the metric that catches BLOCKED-LOOP issues (long sync work,
ReDoS) as they happen, quantified, BEFORE a user complains.
REQUEST CORRELATION: AsyncLocalStorage-carried requestId ties
logs + diagnostics events + error reports to ONE request's
full async lifecycle (see Error Handling & Async Context).
WORKFLOW: event-loop-delay monitoring (leading signal, always on)
โ correlated logs (narrow down WHEN/WHAT) โ CPU profiling
(--cpu-prof, find the EXACT blocking function).
The beginner framing: a server running correctly on your laptop tells you almost nothing about whether it's healthy in production, under real traffic, at 3am, when nobody's watching a terminal. Observability is the set of practices that make production behavior visible without needing to reproduce the problem locally first.
The precise mental model: this topic covers four distinct, complementary mechanisms, structured logging (what happened), health checks (is it currently working), event-loop-delay monitoring (is it responsive), and request-scoped context (correlating everything above for one specific request).
A plain text log line is fine when a human is tail-ing a single server's output directly, it falls apart at any real scale. Once logs are aggregated across many server instances into a log-search system, unstructured text can only be searched by loose string matching. Structured (JSON) logs are queryable precisely: "show me every login_failed event for userId: 42" is a real, fast query against structured fields, not a hopeful grep. Libraries like pino build on this same JSON-log idea, adding performance optimizations and log-level filtering on top, but the core shift is this one: emit structured data, not prose.
router.add("GET", "/healthz/live", (req, res) => { res.writeHead(200).end("ok"); // "is the process alive and responding at all?"});router.add("GET", "/healthz/ready", async (req, res) => { try { await db.ping(); // "is it ready to actually SERVE traffic right now?" res.writeHead(200).end("ready"); } catch { res.
These answer genuinely different questions, and conflating them causes real production problems. Liveness asks "is this process alive and able to respond at all?", a failing liveness check typically means "restart this instance," since something is fundamentally broken (deadlocked, crashed internals). Readiness asks "is this instance currently able to serve real traffic?", a failing readiness check means "stop routing new traffic here, but don't necessarily restart" (e.g., a database connection is still establishing at startup, or a downstream dependency is temporarily unavailable). Using one check for both purposes causes either unnecessary restarts (treating a temporary readiness failure as a liveness failure) or traffic being routed to an instance that can't actually serve it (treating a readiness concern as if liveness alone were sufficient).
diagnostics_channel: instrumentation decoupled from application code#
const diagnostics_channel = require("diagnostics_channel");const channel = diagnostics_channel.channel("myapp:db-query");// application code publishes an event, with NO KNOWLEDGE of who's listening:channel.publish({ query: sql, durationMs: elapsed });// separately, monitoring/APM code subscribes, entirely decoupled:channel.subscribe((message) => { metrics.record("db_query_duration", message.durationMs);});
Confirmed stable in this app's installed Node v23.11.0: diagnostics_channel provides a pub/sub mechanism specifically designed for instrumentation, application code publishes events without needing to know whether anything is listening, and monitoring tooling (APM agents, custom metrics collectors) subscribes without modifying the application code that publishes. This decoupling is exactly what lets APM tools instrument Node internals and popular libraries without invasive patching.
Event-loop-delay monitoring: the metric that catches blocked loops#
Confirmed working directly against this runtime: monitorEventLoopDelay measures actual event-loop responsiveness by sampling the delay between scheduled and actual timer callback execution, the exact metric that would have flagged the blocked-loop incidents described in Event Loop & libuv (a long synchronous operation) and Security (a ReDoS-triggering regex) as they happened, in production, before a user complaint arrived. A consistently elevated .mean (or .max) is the direct, quantified signal that something is blocking the main thread.
What event-loop-delay monitoring is actually measuring: gaps between scheduled and actual phase timing
The script runs top-to-bottom, synchronously, scheduling four things: a timer (โ timers phase), an immediate (โ check phase), and a file read whose callback (โ poll phase) will itself schedule a NEW timer and a NEW immediate once it runs.
Request IDs via AsyncLocalStorage: tying it all together#
requestContext.run({ requestId }, () => { logWithContext("handling request"); // structured log includes requestId channel.publish({ requestId, query: sql }); // diagnostics event includes it too});
The AsyncLocalStorage mechanism from Error Handling & Async Context is what makes structured logs, diagnostics events, and error reports all correlate to the same requestId across an entire request's async lifecycle, without threading that ID through every function signature by hand.
A service's /healthz/ready check queries the database, and its /healthz/live check just returns 200 OK unconditionally. The database becomes temporarily unreachable for 30 seconds due to a network blip, then recovers on its own.
Solution
During the 30-second window, /healthz/ready correctly returns 503 (not ready), causing the orchestrator to stop routing new traffic to this instance, exactly the intended behavior, since the instance genuinely can't serve requests that need the database. /healthz/live continues returning 200 OK throughout, since the process itself is alive and responsive, it correctly does NOT trigger a restart. Once the database recovers, /healthz/ready starts passing again and traffic resumes, with no restart ever having been necessary. This is exactly why the two checks are kept separate: a readiness-only problem (temporary downstream unavailability) is handled by traffic routing, not by restarting a perfectly healthy process.
Every log() call automatically includes the current requestId, the exact combination of structured JSON output and AsyncLocalStorage-based correlation that production logging setups rely on.
Event-loop-delay monitoring measures the same phase-transition timing covered in Event Loop & libuv, it's a direct, quantified production instrument for the exact mental model that topic builds conceptually. diagnostics_channel and request-ID correlation both build on the AsyncLocalStorage mechanism established in Error Handling & Async Context. And CPU/memory profiling from Performance & Profiling is the natural next step once event-loop-delay monitoring flags that something is wrong, profiling is how you find what.
1. Using the same endpoint/logic for both liveness and readiness#
router.add("GET", "/health", async (req, res) => { await db.ping(); // โ a DB blip now triggers unnecessary RESTARTS, not just traffic pausing res.writeHead(200).end("ok");});
Conflating the two causes an orchestrator to restart a perfectly healthy process over a transient downstream issue that should have only paused traffic routing.
2. Logging unstructured strings in a production service#
console.log(`Request from ${ip} failed: ${err.message}`); // โ not queryable at scale
This works fine locally but becomes effectively unsearchable once logs are aggregated across many instances, structured JSON fields are what make production log search actually usable.
3. Never monitoring event-loop delay, only reacting to user-reported slowness#
// no monitorEventLoopDelay anywhere, the first signal of a blocking issue// is a support ticket, not a metric
Without this metric, a blocking operation (an accidental readFileSync in a hot path, a ReDoS-vulnerable regex) is invisible until someone notices the symptom, by which point it's already been affecting real users.
Keep liveness and readiness checks genuinely separate, with different failure semantics (restart vs. pause-traffic).
Emit structured (JSON) logs, not plain text, for anything running in production at more than trivial scale.
Monitor event-loop delay continuously, not just when investigating a reported problem, it's the leading indicator, not the confirming one.
Correlate logs, diagnostics events, and error reports with a request ID via AsyncLocalStorage, so a single request's full story can be reconstructed after the fact.
monitorEventLoopDelay's own overhead is intentionally small (it's sampling, not intercepting every operation), the entire point is a monitoring mechanism cheap enough to run continuously in production without itself becoming a performance problem.
Structured JSON logging has a small serialization cost per log line compared to a raw string, for extremely hot logging paths, libraries like pino are specifically optimized to minimize this, which is part of why a dedicated logging library often outperforms hand-rolled JSON.stringify calls at high log volume.
writeHead
(
503
).
end
(
"not ready"
);
}
});
withRequestContext
(
requestId
,
fn
) {
return requestContext.run({ requestId }, fn);
}
// usage:
withRequestContext(crypto.randomUUID(), () => {
log("info", "request_started");
// ...deep inside a nested async call, with NO requestId parameter: