Logging, metrics and tracing for backends
Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.
What you will be able to do
#- Emit structured logs with a correlation id.
- Instrument request rate, errors and duration.
- Expose a health check that distinguishes liveness from readiness.
Overview
#You cannot debug what you cannot see. Structured logs, metrics and traces turn a production incident into a query instead of a guess.
Structured logging
Log JSON with stable fields, not prose. Include a request id so one request can be followed across services.
function log(req, event, extra = {}) {
console.log(JSON.stringify({ ts: new Date().toISOString(), requestId: req.id, event, ...extra }));
}
Metrics
Track request rate, error rate and duration (the RED method) per route. Alert on error rate and latency percentiles, not on raw counts that grow with traffic.
Tracing
A trace follows one request across services with spans. Propagate a trace id in headers so a slow request can be broken into its downstream calls.
Health checks
A liveness check answers whether the process is alive. A readiness check answers whether it can serve traffic, including its database connection. Do not make liveness depend on a downstream dependency, or a blip restarts every instance.
Common pitfalls
- Logging unstructured prose that cannot be filtered.
- Alerting on average latency, which hides the slow tail that users feel.
- Making liveness fail when the database is slow, causing a restart storm.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Write middleware that assigns a request id, logs method, path, status and duration as JSON.
starter.javascriptapp.use((req, res, next) => { // assign id, log on finish });Reveal the reference answer
reference.javascriptapp.use((req, res, next) => { req.id = crypto.randomUUID(); const start = process.hrtime.bigint(); res.on('finish', () => { const durationMs = Number(process.hrtime.bigint() - start) / 1e6; console.log(JSON.stringify({ requestId: req.id, method: req.method, path: req.path, status: res.statusCode, durationMs })); }); next(); });Authored expected output: One JSON log line per request with requestId, method, path, status and durationMs.
Assigning the id early lets downstream logs reuse it, and logging on finish captures the final status and duration.
Exercise 2Explain
Why should a liveness check not query the database?
starter.textGET /health/live -> SELECT 1Reveal the reference answer
reference.textIf liveness depends on the database and the database is briefly slow, every instance fails liveness and the orchestrator restarts them all, turning a small blip into an outage. Liveness should report only that the process is running; readiness can check dependencies and remove the instance from traffic instead.Authored expected output: Explains that a dependency-aware liveness check causes restart storms; readiness handles dependencies.
Separating liveness from readiness keeps a dependency blip from cascading into restarts.
Common misconceptions
#- More logs are better: high-cardinality, unstructured logs are expensive and hard to query.
- Liveness and readiness are the same: liveness restarts a process, readiness removes it from load balancing.
Follow-up practice
#- backend-databases-capstone
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.