Monitoring JavaScript Applications: Advanced Metrics and Alerts

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Monitoring JavaScript Applications: Metrics and Alerts (Advanced Level)



Modern JavaScript applications on Node.js are becoming increasingly complex: microservices, event-driven architectures, real-time systems. Simple "up/down" monitoring no longer provides a complete picture. Ensuring stability and high performance requires an advanced approach: collecting business metrics, analyzing latency, configuring smart alerts, and observability. In this article, we will explore how to build an advanced monitoring system using Node.js, Prometheus, and Grafana.



1. Key Metrics for Node.js Applications



Monitoring starts with choosing the right metrics. For a production environment, three groups are critical:



  • RED metrics (Rate, Errors, Duration) — request rate, error count, response time.
  • USE metrics (Utilization, Saturation, Errors) — CPU load, memory usage, number of open file descriptors.
  • Business metrics — number of active users, task queue size, event processing speed.


Example of collecting metrics using the prom-client library:



const client = require('prom-client');const httpRequestDuration = new client.Histogram({    name: 'http_request_duration_seconds',    help: 'Duration of HTTP requests in seconds',    labelNames: ['method', 'route', 'status_code'],    buckets: [0.1, 0.3, 0.5, 1, 3, 5]});

app.use((req, res, next) => { const end = httpRequestDuration.startTimer(); res.on('finish', () => { end({ method: req.method, route: req.route?.path || 'unknown', status_code: res.statusCode }); }); next();});


It is also essential to monitor garbage collection (GC) and event loop lag — this will help identify performance issues before they become critical.



2. Configuring Alerts: From Simple to Smart



Alerts are not just notifications about server downtime. At an advanced level, alerts should be:



  • Contextual — taking into account time of day, day of week, business cycles.
  • Multi-level — Warning, Critical, Pager.
  • Predictive — based on trends (e.g., a 20% increase in latency over 15 minutes).


Example of a Prometheus Alertmanager rule using prediction:



groups:  - name: nodejs_alerts    rules:      - alert: HighErrorRate        expr: rate(http_requests_errors_total[5m]) / rate(http_requests_total[5m]) > 0.05        for: 2m        labels:          severity: critical        annotations:          summary: "High error rate ({{ $value | humanizePercentage }})"          description: "More than 5% of requests are returning errors over the last 2 minutes."

- alert: MemoryLeak expr: predict_linear(nodejs_heap_bytes_used{space="total"}[30m], 3600) > 1e9 for: 5m labels: severity: warning annotations: summary: "Predicted memory leak" description: "Heap usage may exceed 1GB within an hour."


It is important to configure alert deduplication and grouping to avoid overwhelming the on-call engineer with hundreds of similar messages. Use group_wait and group_interval in the Alertmanager configuration.



3. Advanced Logging: Structured Logs and Tracing



Standard console.log is not suitable for production. Use structured logging with libraries like pino or winston in JSON format. This makes it easy to parse logs and integrate them with aggregation systems (ELK, Loki).



Example of configuring pino:



const pino = require('pino');const logger = pino({    level: process.env.LOG_LEVEL ||                

Blogs

Book Recommendations