DEV Community

Observability practices

✅ Introduction

Observability is the ability to understand the internal behavior of a system from the data it generates. It's not just about monitoring whether something is "up or down," but about being able to answer questions like: Why is my application slow? Which endpoint is receiving the most traffic?

In this article, I'll show you how to implement real-world observability in a Node.js application using Prometheus to collect metrics and Grafana to visualize them.

🛠 Tools we'll be using

  • Node.js + Express – for our sample application.
  • Prometheus – for collecting and storing metrics.
  • Grafana – for visualizing them in a beautiful and useful way.
  • Prom-client – ​​a library that exports metrics from Node.js.

👨‍💻 Sample Code: App with Metrics in Node.js

  1. Create a folder and project
mkdir observability-nodejs
cd observability-nodejs
npm init -y
npm install express prom-client
Enter fullscreen mode Exit fullscreen mode
  1. Create a file called index.js and copy this:
const express = require('express');
const client = require('prom-client');

const app = express();
const register = new client.Registry();

// Métrica personalizada: duración de peticiones HTTP
const httpRequestDurationMicroseconds = new client.Histogram({
  name: 'http_request_duration_ms',
  help: 'Duración de las peticiones HTTP en ms',
  labelNames: ['method', 'route', 'code'],
  buckets: [50, 100, 200, 300, 400, 500, 1000]
});

register.registerMetric(httpRequestDurationMicroseconds);
client.collectDefaultMetrics({ register }); // Métricas automáticas

// Ruta principal
app.get('/', (req, res) => {
  const end = httpRequestDurationMicroseconds.startTimer();
  res.send('HELLO WORLD 👋');
  end({ route: '/', code: 200, method: req.method });
});

// Ruta para que Prometheus recoja métricas
app.get('/metrics', async (req, res) => {
  res.set('Content-Type', register.contentType);
  res.end(await register.metrics());
});

// Iniciar servidor
app.listen(3000, () => {
  console.log('Servidor corriendo en http://localhost:3000');
});

Enter fullscreen mode Exit fullscreen mode
  1. Run your app node index.js

Now:
Visit http://localhost:3000 → you'll see “Hello world 👋”
Visit http://localhost:3000/metrics → you'll see metrics in Prometheus format

🔎 How to configure Prometheus

  1. Download Prometheus from: https://prometheus.io/download
  2. Create a file named prometheus.yml:
global:
  scrape_interval: 5s

scrape_configs:
  - job_name: 'node-app'
    static_configs:
      - targets: ['localhost:3000']

Enter fullscreen mode Exit fullscreen mode
  1. Run Prometheus:
    ./prometheus --config.file=prometheus.yml

  2. Open http://localhost:9090 in your browser
    There you can check the metrics with queries like:
    http_request_duration_ms_count

Top comments (0)