Ravindra BagaleCourses & study guides मराठी

Chapter 13: Monitoring Basics

DevOps

13.9 What about application metrics?

Why: the problem

Your host dashboard at a food delivery company is all green. CPU 30%, memory 50%, disk 60%. But customers say "orders are not going through". How can both be true? Because host metrics only show the machine, not the business. The app may be waiting on a slow payment gateway, or a queue may be stuck, while the CPU is relaxed. Application metrics are numbers the app itself reports: orders placed per minute, payment failures, checkout latency, items in the queue. They are like the meter in an auto-rickshaw: the engine (host) may be fine, but the meter tells you the trip. Every popular language has a Prometheus library. Spring Boot gives you hundreds of metrics with one dependency. That is why every service you deploy should expose a /metrics page.

What we will build

You will add application metrics to three stacks: a Python FastAPI app with prometheus_client, a Node.js Express app with prom-client, and a Spring Boot app with Micrometer and Actuator. Each one counts orders, measures checkout time and shows a business number. Then Prometheus scrapes all three and you query them the same way.

What: every term in plain English

  • Application metric — A number the app reports about its own work, like orders_total.
  • Instrumentation — Adding metric code to an app.
  • Client library — The package that does it: prometheus_client (Python), prom-client (Node.js), Micrometer (Java).
  • Business metric — A number the business cares about, like payments_failed_total.
  • Histogram buckets — Time ranges like 0.1s, 0.25s, 0.5s, 1s used to count request times.
  • Actuator — Spring Boot module that adds health and metrics endpoints.
  • Default metrics — Process CPU, memory, GC and event loop numbers the library adds for free.
  • Label cardinality — Keep labels small: status, path, method. Never user id or order id.
Create the lab folder Run the Python app Run the Node app Run the Spring Boot app Add scrape jobs
App metrics: code to /metrics to Prometheus to business graph

How: step by step

  1. Create the lab folder

    mkdir -p ~/appmetrics && cd ~/appmetrics
    

    What it does: One folder for three apps.

    Output

    (no output)
    
  2. Run the Python app

    pip install fastapi uvicorn prometheus-client && uvicorn main:app --port 8001
    

    What it does: Example 1.

    Output

    Uvicorn running on http://127.0.0.1:8001
    
  3. Run the Node app

    npm init -y && npm install express prom-client && node server.js
    

    What it does: Example 2.

    Output

    orders api on 8002
    
  4. Run the Spring Boot app

    ./mvnw spring-boot:run
    

    What it does: Example 3.

    Output

    Tomcat started on port 8003
    
  5. Add scrape jobs

    Add the three targets to prometheus.yml (see Verify)
    

    What it does: Prometheus scrapes all three.

    Output

    apps (3/3 up)
    

Example 1: Python FastAPI with prometheus_client

Stack. Python 3, FastAPI, prometheus_client

Goal. Python FastAPI with prometheus_client.

main.py

import random, time
from fastapi import FastAPI
from prometheus_client import Counter, Histogram, Gauge, make_asgi_app

app = FastAPI()
app.mount("/metrics", make_asgi_app())

ORDERS = Counter("orders_total", "Orders placed", ["city", "result"])
CHECKOUT = Histogram("checkout_seconds", "Checkout time",
                     buckets=[0.1, 0.25, 0.5, 1, 2, 5])
QUEUE = Gauge("kitchen_queue_length", "Orders waiting in kitchen")

@app.post("/order/{city}")
def order(city: str):
    start = time.time()
    time.sleep(random.uniform(0.05, 0.6))
    ok = random.random() > 0.03
    ORDERS.labels(city, "ok" if ok else "failed").inc()
    CHECKOUT.observe(time.time() - start)
    QUEUE.set(random.randint(0, 40))
    return {"ok": ok}

What each line does

  • make_asgi_app() — Creates the /metrics page for FastAPI.
  • Counter(..., ["city", "result"]) — Counts orders split by city and ok or failed. Few values, so cardinality is safe.
  • buckets=[...] — Custom latency buckets that fit a checkout.
  • CHECKOUT.observe(...) — Adds one request time to the histogram.
  • QUEUE.set(...) — Sets the current queue length. A gauge.

Green output

$ for c in pune mumbai pune; do curl -s -X POST localhost:8001/order/$c; done
{"ok":true}{"ok":true}{"ok":true}
$ curl -s localhost:8001/metrics/ | grep -E "^orders_total|^checkout_seconds_count|^kitchen"
orders_total{city="pune",result="ok"} 2.0
orders_total{city="mumbai",result="ok"} 1.0
checkout_seconds_count 3.0
kitchen_queue_length 17.0

Expected result. The app now reports business numbers. In Prometheus: sum by (city) (rate(orders_total[5m])) shows orders per second per city.

Example 2: Node

Stack. Node.js 20, Express, prom-client

Goal. Node.js Express with prom-client.

server.js

const express = require("express");
const client = require("prom-client");

const app = express();
client.collectDefaultMetrics();

const payments = new client.Counter({
  name: "payments_total", help: "Payments", labelNames: ["method", "result"],
});
const latency = new client.Histogram({
  name: "http_request_duration_seconds", help: "Request time",
  labelNames: ["route", "status"], buckets: [0.05, 0.1, 0.3, 0.5, 1, 2],
});

app.post("/pay/:method", (req, res) => {
  const end = latency.startTimer({ route: "/pay/:method" });
  const ok = Math.random() > 0.05;
  payments.inc({ method: req.params.method, result: ok ? "ok" : "failed" });
  res.status(ok ? 200 : 502).send(ok ? "paid" : "gateway error");
  end({ status: res.statusCode });
});

app.get("/metrics", async (req, res) => {
  res.set("Content-Type", client.register.contentType);
  res.end(await client.register.metrics());
});

app.listen(8002, () => console.log("orders api on 8002"));

What each line does

  • collectDefaultMetrics() — Adds Node.js process CPU, memory, event loop lag and GC numbers.
  • labelNames: ["method", "result"] — upi, card or wallet, and ok or failed.
  • route: "/pay/:method" — Use the route pattern, not the real URL, to keep cardinality low.
  • latency.startTimer(...) — Starts a timer; end() records the time.
  • client.register.metrics() — Returns all metrics as text.

Green output

$ for m in upi upi card; do curl -s -X POST localhost:8002/pay/$m; echo; done
paid
paid
paid
$ curl -s localhost:8002/metrics | grep -E "^payments_total|^nodejs_eventloop_lag_seconds "
payments_total{method="upi",result="ok"} 2
payments_total{method="card",result="ok"} 1
nodejs_eventloop_lag_seconds 0.0021

Expected result. Payments by method and result, plus free Node.js health numbers like event loop lag.

Example 3: Spring Boot with Micrometer and Actuator

Stack. Java 21, Spring Boot 3, Micrometer

Goal. Spring Boot with Micrometer and Actuator.

pom.xml (dependencies)

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
  <groupId>io.micrometer</groupId>
  <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

application.yml

server:
  port: 8003
management:
  endpoints:
    web:
      exposure:
        include: health,prometheus
  metrics:
    tags:
      application: orders-java
    distribution:
      percentiles-histogram:
        http.server.requests: true

OrderController.java

@RestController
public class OrderController {
    private final Counter orders;
    public OrderController(MeterRegistry registry) {
        this.orders = Counter.builder("orders_placed")
            .description("Orders placed").tag("channel", "app").register(registry);
    }
    @PostMapping("/order")
    public String order() {
        orders.increment();
        return "ok";
    }
}

What each line does

  • spring-boot-starter-actuator — Adds /actuator endpoints like health and metrics.
  • micrometer-registry-prometheus — Makes metrics available in Prometheus format.
  • include: health,prometheus — Exposes only these two endpoints. Do not expose everything.
  • tags: application: orders-java — Adds a label to every metric, so you can filter by app.
  • percentiles-histogram — Adds buckets so you can get p95 for HTTP requests.
  • Counter.builder("orders_placed") — A custom business counter. Micrometer adds _total in Prometheus.

Green output

$ curl -s localhost:8003/actuator/health
{"status":"UP"}
$ curl -s localhost:8003/actuator/prometheus | grep -E "^orders_placed_total|^jvm_memory_used_bytes\{area=\"heap\"" | head -3
orders_placed_total{application="orders-java",channel="app"} 12.0
jvm_memory_used_bytes{application="orders-java",area="heap",id="G1 Eden Space"} 2.5165824E7

Expected result. Spring Boot gives JVM, HTTP, database pool and your own business metrics at /actuator/prometheus. Many Indian banks and TCS projects use exactly this setup.

Verify: did it work?

  1. Scrape all three

    Add to prometheus.yml: job apps with targets host.docker.internal:8001, :8002, :8003 and metrics_path per job (/metrics/, /metrics, /actuator/prometheus)
    

    What it does: Each app is a target.

    Output

    apps-python UP, apps-node UP, apps-java UP
    
  2. One query for all

    sum by (job) (rate(http_request_duration_seconds_count[5m]))
    

    What it does: Requests per second per app.

    Output

    {job="apps-node"} 0.8
    

When it is red 1

Spring Boot /actuator/prometheus returns 404

Cause. The endpoint is not exposed or the registry dependency is missing.

Fix, step by step

  1. Add micrometer-registry-prometheus to pom.xml.
  2. Set management.endpoints.web.exposure.include: health,prometheus.
  3. Rebuild and restart.

When it is red 2

Prometheus memory grows every hour

Cause. A label has too many values, like user_id or full URL path.

Fix, step by step

  1. Find it: topk(5, count by (name)({name=~".+"}))
  2. Replace the label with a route pattern or remove it.
  3. Restart the app to drop old series.

When it is red 3

Duplicated timeseries in CollectorRegistry

Cause. In Python the same metric was created twice, often because the module was imported twice or in a reload.

Fix, step by step

  1. Create metrics once at module top level.
  2. Do not create metrics inside request handlers.
  3. Turn off auto reload in production.

Cleanup

  1. Stop apps

    pkill -f uvicorn ; pkill -f server.js ; pkill -f spring-boot
    

    What it does: Stops the three apps.

    Output

    (no output)
    
  2. Remove scrape jobs

    Delete the apps jobs from prometheus.yml and reload
    

    What it does: Stops scraping.

    Output

    (no output)
    

Ravindra Bagale's Tip

The host can have free CPU and the business can still be down. The app must export its own numbers: orders, payments, queue.

Practice tasks

Easy Add a version label

Why: Knowing which version runs helps during deploys.

What to do: Expose app_info{version="1.4.2"} 1.

How:
  1. Use a Gauge or Info metric.
  2. Set it once at start.

Check: Prometheus shows the version per instance.

Medium Compare cities

Why: Business teams love city-wise numbers.

What to do: Make a Grafana bar chart of orders per city for the last hour.

How:
  1. sum by (city) (increase(orders_total[1h]))

Check: You see a bar per city.

Hard Alert on payment failures

Why: Payment failures are real money lost.

What to do: Write an alert when failed payments are above 5% for 5 minutes.

How:
  1. Use payments_total with result="failed" divided by all.
  2. for: 5m, severity critical.

Check: The alert fires in a test with forced failures.

Easy Say application metrics in two lines

Why: If you can say it simply, you understand it. Juniors and interviewers both want the short version first.

What to do: Write two short lines about application metrics for a fresher who knows only Linux, Git and Docker basics.

How:
  1. Write the problem it solves.
  2. Write the one command, query or config line you use for it.
  3. Read it aloud to a friend.

Check: A fresher understands it without asking a question.

Easy Keep a throwaway monitoring lab

Why: Practice needs a lab you can break. If it gets messy, you delete the containers and start again in one minute.

What to do: Run Node Exporter in Docker and read its metrics page.

How:
  1. docker run -d --name ne -p 9100:9100 prom/node-exporter
  2. curl -s localhost:9100/metrics | grep node_load1
  3. docker rm -f ne

Check: You see a line that starts with node_load1 and a number.

Medium Do it on a second stack

Why: Monitoring ideas must work on Prometheus and on CloudWatch. Only the tool changes, not the thinking.

What to do: Repeat this lesson on a different stack than the one you used first.

How:
  1. If you used Prometheus, try the CloudWatch console or AWS CLI.
  2. Keep the same question: is it up, is it fast, is it failing, is it full?
  3. Compare the two graphs side by side.

Check: Both tools answer the same question with a number and a graph.

Medium Break it on purpose

Why: You must know the red error by face. During an outage there is no time to read slowly.

What to do: Cause one error from the "When it is red" part of this lesson and fix it.

How:
  1. Follow the error section.
  2. Copy the exact message into your notes.
  3. Write the fix in one line.

Check: You fixed it using only the steps, without searching the web.

Medium Write a one-page runbook

Why: At 2 a.m. nobody remembers PromQL. A short page saves the on-call person.

What to do: Write a one-page runbook for this lesson.

How:
  1. Title, when the alert fires, the graph to open, the exact commands, how to check, how to undo.

Check: A teammate can follow it alone, without calling you.

Hard Explain it like an interview

Why: Interviewers want real stories, not definitions.

What to do: Record a 60 second answer about this lesson.

How:
  1. Say the problem, the metric you watched, the number you saw and the fix.

Check: Your answer has a real metric name and a real number.

Hard Draw the flow top to bottom

Why: A drawing shows where a number is born and where it ends up.

What to do: Draw this lesson as boxes from top to bottom.

How:
  1. Start at the server or app, go through the exporter, Prometheus or CloudWatch, then Grafana, then the alert on your phone.

Check: Each box matches a real command or file in this lesson.

Homework: try at home

Try at home

At home, add a business metric to any small app you built in this course, for example "signups_total" or "files_uploaded_total". Show it on a Grafana Stat panel with "increase over the last 24h".

Recap

  • Host metrics show the machine; app metrics show the business.
  • Every language has a Prometheus client library.
  • Use counters for events, histograms for time, gauges for current levels.
  • Keep labels small; never use ids as labels.
  • Spring Boot needs only Actuator and Micrometer.

FAQ

Does instrumentation slow the app?

Very little. A counter increase takes nanoseconds.

Should I use OpenTelemetry instead?

OpenTelemetry is the new standard for metrics, logs and traces. It can export to Prometheus too.

What about short batch jobs?

Use Pushgateway or the textfile collector because they finish before a scrape.

Where do I put /metrics in Kubernetes?

Same port; add a ServiceMonitor or scrape annotations.

Should /metrics be public?

No. Keep it on an internal port or behind the network.

Interview questions

  1. How do you add Prometheus metrics to a Spring Boot app?

    Add actuator and micrometer-registry-prometheus, expose the prometheus endpoint, and scrape /actuator/prometheus.

  2. What is the difference between counter, gauge, histogram and summary?

    Counter only goes up; gauge goes up and down; histogram counts values into buckets and allows server-side percentiles; summary computes quantiles in the client and cannot be aggregated.

  3. What is high cardinality and how to avoid it?

    Too many unique label combinations; use bounded labels like status and route, never user ids or raw URLs.

  4. What business metrics would you add to a checkout service?

    Orders placed, payment failures by method, checkout latency, cart abandonment and queue length.

  5. How do you monitor batch jobs?

    Pushgateway or textfile collector with a last-success timestamp and duration metric.

Quick quiz

Q1. Which library is used in Node.js?

prom-client.

Q2. Which Spring Boot endpoint shows Prometheus metrics?

/actuator/prometheus.

Q3. Why not use user_id as a label?

It creates too many series (high cardinality).

Q4. Which metric type for queue length?

Gauge.

Q5. Why use route patterns in labels?

To keep the number of label values small.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards