Ravindra BagaleCourses & study guides मराठी

Chapter 13: Monitoring Basics

DevOps

13.2 Golden signals — four questions in plain English

Why: the problem

You open Netflix and press play. Four things can go wrong. The video can take ten seconds to start. Too many people can be watching at once. Some requests can fail with an error. The server can be so full that it starts to slow down. Google engineers wrote these four as the "golden signals" in their SRE book: latency, traffic, errors and saturation. If you watch only these four for every service, you will catch most problems that users feel. A new engineer often watches 200 graphs and still misses the outage. A smart engineer watches four lines per service and catches it early. That is why we learn the golden signals before any tool.

What we will build

You will measure all four golden signals in three ways. First, from an nginx access log with plain awk, so you see the idea with no tool at all. Second, from a Python app that exposes the four signals for Prometheus. Third, you will write the four PromQL queries that any Grafana dashboard uses. At the end you will be able to say, for any service: how fast, how busy, how broken and how full.

What: every term in plain English

  • Golden signals — Four numbers to watch for every service: latency, traffic, errors, saturation.
  • Latency — How long a request takes. Example: 120 ms.
  • Traffic — How many requests come in. Example: 300 requests per second.
  • Errors — How many requests fail. Example: 2% of requests give HTTP 500.
  • Saturation — How full the system is. Example: CPU 90%, or 95 of 100 database connections used.
  • p95 / p99 — Percentile. p95 = 300 ms means 95% of requests were faster than 300 ms.
  • RPS — Requests per second.
  • RED and USE — RED = Rate, Errors, Duration for services. USE = Utilization, Saturation, Errors for machines.
Install nginx on a lab VM Add request time to the log Reload nginx Create traffic Read the four signals
Golden signals: request to latency, traffic, errors, saturation

How: step by step

  1. Install nginx on a lab VM

    sudo apt-get update && sudo apt-get install -y nginx
    

    What it does: A web server to create traffic and logs.

    Output

    Setting up nginx (1.24.0-2ubuntu7) ...
    
  2. Add request time to the log

    Edit /etc/nginx/nginx.conf as in Example 1, then sudo nginx -t
    

    What it does: Logs now include how long each request took.

    Output

    nginx: configuration file /etc/nginx/nginx.conf test is successful
    
  3. Reload nginx

    sudo systemctl reload nginx
    

    What it does: Applies the new log format without dropping users.

    Output

    (no output)
    
  4. Create traffic

    for i in $(seq 1 200); do curl -s -o /dev/null localhost/; done; for i in $(seq 1 10); do curl -s -o /dev/null localhost/nope; done
    

    What it does: 200 good requests and 10 errors (404).

    Output

    (no output)
    
  5. Read the four signals

    bash signals.sh
    

    What it does: Prints traffic, errors, latency and CPU from the log and the host.

    Output

    traffic=210 errors=4.8% p95_ms=1 cpu_load=0.10
    

Example 1: Golden signals from an nginx log with awk

Stack. Ubuntu 24.04, nginx, awk

Goal. Golden signals from an nginx log with awk.

/etc/nginx/nginx.conf (inside the http block)

log_format timed '$remote_addr [$time_local] "$request" '
                 '$status $body_bytes_sent rt=$request_time';
access_log /var/log/nginx/access.log timed;

signals.sh

#!/usr/bin/env bash
LOG=/var/log/nginx/access.log
total=$(sudo wc -l "$LOG" | cut -d " " -f1)
errs=$(sudo awk '$7 ~ /^[45]/' "$LOG" | wc -l)
p95=$(sudo grep -o "rt=[0-9.]*" "$LOG" | cut -d= -f2 | sort -n \
      | awk '{a[NR]=$1} END {print a[int(NR*0.95)]*1000}')
load=$(cut -d " " -f1 /proc/loadavg)
echo "traffic=$total errors=$(awk -v e=$errs -v t=$total 'BEGIN{printf "%.1f", e*100/t}')% p95_ms=$p95 cpu_load=$load"

What each line does

  • $request_time — nginx writes how many seconds the request took, like 0.004.
  • awk '$7 ~ /^[45]/' — Picks lines where the status (7th field) starts with 4 or 5: errors.
  • sort -n — Sorts the times from small to big.
  • a[int(NR*0.95)] — Takes the value at the 95% position: the p95 latency.
  • *1000 — Changes seconds to milliseconds.
  • /proc/loadavg — A quick saturation number for the CPU.

Green output

$ bash signals.sh
traffic=210 errors=4.8% p95_ms=1 cpu_load=0.10

Expected result. You measured all four signals with no monitoring tool. Traffic 210, errors 4.8%, p95 latency 1 ms, CPU load 0.10.

Example 2: A Python app that exposes the four signals for Prometheus

Stack. Python 3, Flask, prometheus_client

Goal. A Python app that exposes the four signals for Prometheus.

app.py

import random, time
from flask import Flask, Response
from prometheus_client import Counter, Histogram, Gauge, generate_latest

app = Flask(__name__)
REQS = Counter("http_requests_total", "Requests", ["path", "status"])
LAT = Histogram("http_request_duration_seconds", "Latency", ["path"])
INFLIGHT = Gauge("http_inflight_requests", "Requests being served now")

@app.route("/order")
def order():
    INFLIGHT.inc()
    with LAT.labels("/order").time():
        time.sleep(random.uniform(0.01, 0.3))
        status = "500" if random.random() > 0.97 else "200"
    REQS.labels("/order", status).inc()
    INFLIGHT.dec()
    return ("failed", 500) if status == "500" else "ok"

@app.route("/metrics")
def metrics():
    return Response(generate_latest(), mimetype="text/plain")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, threaded=True)

What each line does

  • Counter("http_requests_total", ...) — A number that only goes up. Gives traffic and errors.
  • ["path", "status"] — Labels. They let us split the count by URL and status code.
  • Histogram(...) — Puts each request time into buckets. Gives latency and p95.
  • Gauge(...) — A number that goes up and down. Here: requests in progress (saturation).
  • LAT.labels("/order").time() — Measures how long the block takes.
  • generate_latest() — Prints all metrics in the Prometheus text format at /metrics.

Green output

$ pip install flask prometheus-client
$ python3 app.py &
$ for i in $(seq 1 300); do curl -s -o /dev/null localhost:8000/order; done
$ curl -s localhost:8000/metrics | grep -E "^http_requests_total|_count"
http_requests_total{path="/order",status="200"} 291.0
http_requests_total{path="/order",status="500"} 9.0
http_request_duration_seconds_count{path="/order"} 300.0

Expected result. The app now tells anyone who asks: 300 requests, 9 errors, and how long they took. Prometheus will read this page every 15 seconds.

Example 3: The four golden signals as PromQL queries

Stack. Prometheus 2.x / 3.x, PromQL

Goal. The four golden signals as PromQL queries.

golden.promql

# 1. Traffic: requests per second over 5 minutes
sum(rate(http_requests_total[5m]))

# 2. Errors: percent of requests that failed
100 * sum(rate(http_requests_total{status=~"5.."}[5m]))
    / sum(rate(http_requests_total[5m]))

# 3. Latency: p95 in seconds
histogram_quantile(0.95,
  sum by (le) (rate(http_request_duration_seconds_bucket[5m])))

# 4. Saturation: busy CPU percent on each server
100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])))

What each line does

  • rate(...[5m]) — How fast a counter grew per second, averaged over 5 minutes.
  • sum(...) — Adds all servers and paths together.
  • status=~"5.." — Regex match: any status that starts with 5.
  • histogram_quantile(0.95, ...) — Finds the p95 latency from the histogram buckets.
  • sum by (le) — Keeps the bucket label le, which histogram_quantile needs.
  • mode="idle" — Idle CPU time. 1 minus idle gives busy CPU.

Green output

Traffic     4.97 req/s
Errors      3.0 %
Latency p95 0.285 s
Saturation  instance="10.0.1.12:9100"  7.4 %

Expected result. Paste each query in the Prometheus Graph tab (port 9090). These four lines are the top row of almost every real service dashboard at companies like Zomato and Flipkart.

Verify: did it work?

  1. Check metrics page

    curl -s localhost:8000/metrics | grep -c http_
    

    What it does: Counts metric lines from your app.

    Output

    27
    
  2. Check the error share

    curl -s localhost:8000/metrics | grep status=\"500\"
    

    What it does: Shows the error counter.

    Output

    http_requests_total{path="/order",status="500"} 9.0
    

When it is red 1

ModuleNotFoundError: No module named 'prometheus_client'

Cause. The library is not installed in this Python.

Fix, step by step

  1. pip install prometheus-client
  2. Check with: python3 -c "import prometheus_client"
  3. Start the app again.

When it is red 2

nginx: [emerg] unknown log format "timed"

Cause. access_log uses the name "timed" before log_format defines it, or log_format is outside the http block.

Fix, step by step

  1. Put log_format above access_log inside http { }.
  2. Run sudo nginx -t.
  3. Reload nginx.

When it is red 3

histogram_quantile returns NaN

Cause. No requests came in the time window, so there is nothing to measure.

Fix, step by step

  1. Send traffic with the curl loop.
  2. Wait 30 seconds for a scrape.
  3. Run the query again with [5m].

Cleanup

  1. Stop the app

    pkill -f app.py
    

    What it does: Stops the Python app.

    Output

    (no output)
    
  2. Restore the nginx log format

    Remove the log_format lines, then sudo nginx -t && sudo systemctl reload nginx
    

    What it does: Back to the default log line.

    Output

    nginx: configuration file /etc/nginx/nginx.conf test is successful
    

Ravindra Bagale's Tip

Remember four questions: how fast, how busy, how many errors, how full. Every service needs these four graphs.

Practice tasks

Easy Find p99 too

Why: p99 shows the worst 1% of users, often the most loyal heavy users.

What to do: Change 0.95 to 0.99 in the latency query.

How:
  1. Run both queries.
  2. Write both numbers.

Check: p99 is higher than p95.

Medium Golden signals for MySQL

Why: Databases have the same four signals.

What to do: Write traffic, errors, latency and saturation for a MySQL server.

How:
  1. Traffic: queries per second.
  2. Errors: aborted connects.
  3. Latency: slow queries.
  4. Saturation: Threads_connected vs max_connections.

Check: You have one metric for each signal.

Hard Build a 4-panel dashboard

Why: Seeing all four together is the real habit.

What to do: In Grafana make one row with the four queries from Example 3.

How:
  1. Add Prometheus as a data source.
  2. Add four Stat or Time series panels.
  3. Save as "Orders golden signals".

Check: The dashboard shows four live numbers.

Easy Say golden signals 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 golden signals 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, open any app you use (Instagram, Paytm) and write the four golden signals for it in plain words. Example for Paytm UPI: latency = time from Pay to "Success", traffic = payments per second, errors = failed payments, saturation = bank API connections in use.

Recap

  • Watch four signals per service: latency, traffic, errors, saturation.
  • Use p95 or p99 for latency, not the average.
  • Counters give traffic and errors; histograms give latency; gauges give saturation.
  • You can measure them with awk, but Prometheus does it all the time for you.
  • RED is for services, USE is for machines.

FAQ

Why not use average latency?

A few very slow requests hide inside a nice average. p95 shows what real slow users feel.

Are golden signals only for web apps?

No. Queues, databases and batch jobs also have speed, volume, failures and fullness.

What is a good error rate?

Depends on the business. Many teams aim for under 0.1% for payments.

Where do I see these in AWS?

The Application Load Balancer gives RequestCount, HTTPCode_Target_5XX_Count and TargetResponseTime in CloudWatch.

What is the difference between RED and golden signals?

RED is the first three golden signals. Golden signals add saturation.

Interview questions

  1. What are the four golden signals?

    Latency, traffic, errors and saturation, from the Google SRE book.

  2. Why use percentiles for latency?

    Averages hide slow outliers. p95 and p99 show the experience of the slowest users.

  3. Explain RED vs USE.

    RED (rate, errors, duration) for request-driven services; USE (utilization, saturation, errors) for resources like CPU, disk and network.

  4. How do you compute error rate in PromQL?

    sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])).

  5. What is saturation for a database?

    Connections used vs the max, or queue length, or disk IO wait.

  6. Counter vs gauge?

    A counter only increases, like total requests. A gauge goes up and down, like memory used.

Quick quiz

Q1. Name the four golden signals.

Latency, traffic, errors, saturation.

Q2. What does p95 = 300 ms mean?

95% of requests finished in 300 ms or less.

Q3. Which metric type only goes up?

Counter.

Q4. Which PromQL function gives per-second speed of a counter?

rate().

Q5. Is CPU 90% a traffic or a saturation signal?

Saturation.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards