Advanced Monitoring of TypeScript Applications: 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

Advanced Monitoring of TypeScript Applications: Metrics and Alerts

\n

In modern development, monitoring has gone beyond simple "is the server alive" checks. For TypeScript applications running in complex distributed environments, an advanced observability system is required. It is not enough to simply log errors — you need to collect custom performance metrics, configure intelligent alerts, and build dashboards for predictive analysis. In this article, we will look at how to implement professional monitoring for TypeScript applications using modern tools and best practices.

\n\n

1. Collecting Custom Performance Metrics

\n

Basic metrics (CPU, memory) often do not provide the full picture. For TypeScript applications, business metrics and runtime metrics are critically important. Let's look at setting up the collection of custom metrics using the prom-client library (Prometheus client for Node.js).

\n\n

Types of Custom Metrics

\n
    \n
  • Counter — for counting events (requests, errors).
  • \n
  • Gauge — for values that can increase and decrease (number of active connections).
  • \n
  • Histogram — for value distribution (response time).
  • \n
  • Summary — for quantiles of execution time.
  • \n
\n\n

Example: Registering Custom Metrics in TypeScript

\n
import client from 'prom-client';\nimport express, { Request, Response } from 'express';\n\n// Create a metric registry\nconst register = new client.Registry();\nclient.collectDefaultMetrics({ register });\n\n// Custom error counter\nconst errorCounter = new client.Counter({\n  name: 'app_errors_total',\n  help: 'Total number of application errors',\n  labelNames: ['type', 'code'],\n  registers: [register],\n});\n\n// Histogram for response time\nconst httpRequestDuration = new client.Histogram({\n  name: 'http_request_duration_seconds',\n  help: 'Duration of HTTP requests in seconds',\n  labelNames: ['method', 'route', 'status'],\n  buckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5],\n  registers: [register],\n});\n\n// Gauge for active users\nconst activeUsers = new client.Gauge({\n  name: 'active_users_count',\n  help: 'Number of currently active users',\n  labelNames: ['user_type'],\n  registers: [register],\n});\n\nconst app = express();\n\n// Middleware for measuring request time\napp.use((req: Request, res: Response, next) => {\n  const end = httpRequestDuration.startTimer();\n  res.on('finish', () => {\n    end({ method: req.method, route: req.path, status: res.statusCode });\n  });\n  next();\n});\n\n// Metrics endpoint\napp.get('/metrics', async (req: Request, res: Response) => {\n  res.set('Content-Type', register.contentType);\n  res.end(await register.metrics());\n});\n\n// Simulate an error\napp.get('/error', (req: Request, res: Response) => {\n  errorCounter.inc({ type: 'validation', code: '400' });\n  res.status(400).send('Bad Request');\n});\n\napp.listen(3000, () => console.log('Server on port 3000'));
\n\n

2. Integration with Prometheus and Grafana

\n

The collected metrics need to be exported and visualized. Prometheus will scrape our /metrics endpoint, and Grafana will display the data on dashboards.

\n\n

Prometheus Configuration for a TypeScript Application

\n
# prometheus.yml\nglobal:\n  scrape_interval: 15s\nscrape_configs:\n  - job_name: 'typescript-app'\n    static_configs:\n      - targets: ['localhost:3000']\n    metrics_path: '/metrics'\n    # Add environment labels\n    relabel_configs:\n      - source_labels: [__address__]\n        target_label: instance\n        regex: '([^:]+):.*'\n        replacement: '${1}'
\n\n

Advanced PromQL Queries for Analysis

\n
    \n
  • rate(app_errors_total[5m]) — error rate over 5 minutes.
  • \n
  • histogram_quantile(0.95, rate(http_request_durati

Blogs

Book Recommendations