Prometheus & Grafana

Prometheus & Grafana in DevOps Tools: Prometheus is a pull-based metrics system: on a fixed interval it scrapes numeric time series from your services and…

Prometheus is a pull-based metrics system: on a fixed interval it scrapes numeric time series from your services and stores them, and Grafana turns those series into dashboards. This lesson covers the two data types everyone trips over -- counters and gauges -- how PromQL turns a raw counter into a meaningful rate, how a histogram yields a percentile, and the single most common instrumentation bug: subtracting counter values by hand across a restart.


The Analogy: A Utility Meter-Reading Round

A gas utility runs a metering department. Every property has a meter, and a reader walks a fixed round on a timetable -- the same route, at the same interval -- writing down each dial. Crucially, the plant never phones the meters; the reader goes to them on a schedule and pulls the numbers. That is exactly how Prometheus works: it does not wait for your services to push metrics at it, it scrapes each target on a set scrape interval, so a service that has crashed simply produces a gap in the round rather than a silent absence of pushed data.

The dials come in two kinds, and confusing them is the classic beginner error. A consumption meter is cumulative: it only ever climbs and is never meant to run backwards, so the gas used in a period is not the dial's value but the difference between this round's reading and the last -- a subtraction over a rising number. That is a Prometheus counter, and the useful quantity is its increase or its rate, never its raw height. Other instruments, like a line-pressure gauge, are read as-is: the number on the face right now is the answer, and subtracting two pressure readings would be meaningless. That is a gauge.

The office keeps every reading it has ever taken as a time series per meter, tagged with the district and tariff, and its wall dashboards plot consumption per hour and per district by taking rates over those cumulative counters, and estimate typical versus worst-case service from the spread of readings. Slicing the data by label -- "show me the industrial tariff in the north district" -- is what PromQL does, and because each reading is just a small number, decades of them cost almost nothing to keep.

The failure that ambushes this department is the meter swap. Now and then an old unit is replaced, or a mechanical dial rolls past its maximum and wraps back to zero, so the next reading is lower than the last. A clerk who blindly computes "this reading minus last reading" gets a negative consumption -- an obvious nonsense that either bills the customer a credit or, worse, sails past an automated report because nobody thought to guard against a counter going down. The correct procedure recognises the swap and counts the new meter's climb from zero. That is precisely the counter-reset problem that Prometheus's rate() and increase() are built to handle, and precisely the trap a hand-rolled subtraction falls into -- the design flaw we will reproduce at the end.


Syntax or Core Structure

Prometheus stores every metric as a time series: a stream of timestamped numbers. The two fundamental kinds behave differently, so you read them differently. A counter only ever rises, so its value alone is uninteresting -- what you want is its increase over a window, or that increase divided by the seconds to get a per-second rate. A gauge can move in either direction, so its latest value is the answer directly. The snippet models both from five scrapes taken fifteen seconds apart.

COUNTER = [100, 130, 175, 205, 250]     # http_requests_total at 15s scrapes
WINDOW_S = 60                           # 0..60s spanned by 5 samples

# a counter: report its increase and its per-second rate, never its raw height
increase = COUNTER[-1] - COUNTER[0]
rate = increase / WINDOW_S
print('counter samples: %s' % COUNTER)
print('increase over %ds: %d requests' % (WINDOW_S, increase))
print('rate: %.2f req/s' % rate)

# a gauge: read the latest value directly; subtracting two gauges is meaningless
GAUGE = [40, 55, 50, 62, 58]            # memory_used_percent
print('gauge samples: %s' % GAUGE)
print('current gauge value: %d' % GAUGE[-1])
print('gauge average: %.1f' % (sum(GAUGE) / len(GAUGE)))

Output:

counter samples: [100, 130, 175, 205, 250]
increase over 60s: 150 requests
rate: 2.50 req/s
gauge samples: [40, 55, 50, 62, 58]
current gauge value: 58
gauge average: 53.0

The counter climbed from 100 to 250, so 150 requests arrived across the 60-second window, which is a rate of 2.50 per second. Notice that the raw number 250 told you nothing on its own -- only the difference carried meaning. The gauge is the opposite: its current reading of 58 percent is directly useful, and while its average over the window (53.0) is a reasonable summary, you would never subtract its endpoints the way you did with the counter. Getting this distinction right is the foundation of every correct PromQL query.


Technical Depth: Scraping, PromQL, and Histograms

The scrape configuration

Prometheus learns what to pull, and how often, from a single YAML file. Each job names a set of targets; every scrape interval Prometheus fetches the metrics endpoint from each one and appends the samples to its time-series database.

global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: "prometheus"
    static_configs:
      - targets: ["localhost:9090"]

  - job_name: "node"
    static_configs:
      - targets: ["node-exporter:9100"]

  - job_name: "app"
    metrics_path: /metrics
    static_configs:
      - targets: ["app:8080"]

Metric types and how to query them

Reaching for the wrong PromQL function for a metric type is the most common query mistake. This table is the cheat sheet.

Metric typeWhat it doesRead it with
CounterOnly increases, resets to 0 on restartrate() or increase()
GaugeMoves up or down freelythe raw value, or avg_over_time()
HistogramBuckets observations by sizehistogram_quantile() over buckets
SummaryClient-computed quantilesthe raw quantile series

Histograms: a percentile without storing every sample

A Prometheus histogram does not keep every observation. It keeps a set of cumulative buckets, each counting how many observations fell at or below a boundary (its le, "less than or equal"). To recover a percentile, histogram_quantile finds the bucket that contains the target rank and interpolates linearly within it. The function below is that algorithm, run against a histogram of 100 latency observations.

BUCKETS = [(0.1, 50), (0.5, 80), (1.0, 95), (2.5, 100)]   # (le, cumulative count)
TOTAL = 100

def histogram_quantile(q, buckets, total):
    rank = q * total
    prev_le, prev_cum = 0.0, 0
    for le, cum in buckets:
        if cum >= rank:
            frac = (rank - prev_cum) / (cum - prev_cum)
            return prev_le + (le - prev_le) * frac
        prev_le, prev_cum = le, cum
    return buckets[-1][0]

for q in (0.50, 0.90, 0.95, 0.99):
    print('p%d latency: %.3fs' % (int(q * 100), histogram_quantile(q, BUCKETS, TOTAL)))

Output:

p50 latency: 0.100s
p90 latency: 0.833s
p95 latency: 1.000s
p99 latency: 2.200s

The interpolation is visible in the p90: the 90th observation lands inside the bucket spanning 0.5s to 1.0s, which holds 15 observations (from cumulative 80 to 95), and the target sits 10 of those 15 in, so the estimate is 0.5 + 0.5 times 10/15, or 0.833s. This is why histogram accuracy depends entirely on bucket boundaries: had there been no bucket between 0.5 and 1.0, every request in that range would report as the bucket edge. Choose buckets around the latencies you actually care about, or your percentiles will be quantised to the nearest boundary.


Real World Example: The Counter That Went Backwards

A team ships a dashboard panel showing request throughput. To keep it simple, an engineer computes the rate in application code as "the last scrape value minus the first, divided by the window" -- the meter-reading subtraction from the analogy. It looks right in every test, because in a test the process never restarts mid-window. Then a routine deploy rolls the pods during business hours, the counter resets to zero on the new process, and the panel prints a negative throughput. Because nothing alerts on "throughput below zero", the graph simply shows a dip and the on-call engineer wastes an hour hunting a phantom traffic collapse.

The program below reproduces the incident with five scrapes, where the third scrape is lower than the second because the process restarted between them. It compares the naive subtraction against a reset-aware increase of the kind rate() computes internally.

SAMPLES = [100, 130, 10, 35, 60]        # counter scraped every 15s; a restart resets it
WIN_S = 60

naive_delta = SAMPLES[-1] - SAMPLES[0]  # last - first, ignoring resets
naive_rate = naive_delta / WIN_S

def reset_aware_increase(samples):
    total = 0
    for i in range(1, len(samples)):
        if samples[i] < samples[i - 1]:
            total += samples[i]         # reset: the counter climbed samples[i] from 0
        else:
            total += samples[i] - samples[i - 1]
    return total

increase = reset_aware_increase(SAMPLES)
correct_rate = increase / WIN_S
reset_seen = any(SAMPLES[i] < SAMPLES[i - 1] for i in range(1, len(SAMPLES)))

print('scrape samples (counter): %s' % SAMPLES)
print('naive delta (last - first): %d' % naive_delta)
print('naive rate: %.2f req/s' % naive_rate)
print('reset detected between scrapes: %s' % reset_seen)
print('reset-aware increase: %d' % increase)
print('correct rate: %.2f req/s' % correct_rate)
print('naive rate is non-negative (plausible): %s' % (naive_rate >= 0))
print('correct rate is non-negative (plausible): %s' % (correct_rate >= 0))
print('naive and correct agree: %s' % (naive_rate == correct_rate))

Output:

scrape samples (counter): [100, 130, 10, 35, 60]
naive delta (last - first): -40
naive rate: -0.67 req/s
reset detected between scrapes: True
reset-aware increase: 90
correct rate: 1.50 req/s
naive rate is non-negative (plausible): False
correct rate is non-negative (plausible): True
naive and correct agree: False

The two answers disagree completely. The naive delta is -40, giving a nonsensical rate of -0.67 requests per second, while the reset-aware pass correctly sums each segment -- 30, then the 10 the counter climbed after the reset, then 25, then 25 -- for a true increase of 90 and a rate of 1.50 per second. Real traffic never stopped; only the measurement broke.

The design flaw is the assumption that a counter is monotonic within the query window. Subtracting the endpoints is correct only if the counter never resets, and that assumption fails on every deploy, crash, or pod reschedule -- which in a healthy system happens constantly. Prometheus's rate() and increase() are built precisely to detect a sample lower than its predecessor, treat it as a reset, and count the climb from zero, which is why you must always express counter throughput with those functions and never with hand-rolled arithmetic. The reproduction here still has two honest limits worth stating: the reset-aware pass assumes at most one reset between any two adjacent scrapes, so a service that restarts twice inside one 15-second interval would still be undercounted; and it cannot distinguish a genuine reset from a counter that legitimately wrapped a 64-bit boundary, though at real request volumes that wrap is centuries away and safely ignored.


Common Mistakes

  1. Graphing a raw counter. A counter's absolute value climbs forever and means nothing on its own. Always wrap it in rate() or increase() to get a per-second or per-window quantity.
  1. Subtracting counter endpoints by hand. As the example showed, last minus first goes negative across a restart. Use rate() or increase(), which are reset-aware, rather than arithmetic on the samples.
  1. Using rate() on a gauge. rate() assumes the series only rises; applied to a gauge that moves both ways it produces garbage. Read a gauge directly or with avg_over_time().
  1. Choosing histogram buckets badly. If no bucket boundary sits near your target latency, histogram_quantile can only report the nearest edge. Pick buckets around the values you actually care about.
  1. Averaging percentiles across instances. Taking the mean of each pod's p99 does not give the fleet p99. Aggregate the raw histogram buckets first, then compute the quantile once over the sum.
  1. High-cardinality labels. Putting a user id, request id, or full URL in a label multiplies the number of time series and can exhaust Prometheus memory. Keep labels to bounded, low-cardinality values.
  1. Too short a rate window. A rate() window shorter than about four scrape intervals can miss samples and produce jumpy, gap-ridden graphs. Make the window a comfortable multiple of the scrape interval.
  1. Confusing scrape interval with evaluation interval. The scrape interval controls how often data is collected; the evaluation interval controls how often rules and alerts run. Setting one when you meant the other yields stale alerts or wasted scrapes.
  1. Leaving Grafana on default credentials. A dashboard stack shipped with the admin password unchanged is an open door to your entire metrics estate. Set a real password and put the UI behind authentication before exposing it.

Best Practices

  • Express every counter as a rate or an increase, never as a raw value, so restarts and resets are handled for you and the units are meaningful.
  • Match the rate() window to a small multiple of the scrape interval -- a common choice is five times -- so the graph is smooth without lagging real changes.
  • Size histogram buckets around the latencies your SLOs mention, so histogram_quantile interpolates over a bucket rather than snapping to a distant edge.
  • Keep metric labels low-cardinality; push per-request identifiers into logs or traces so the time-series count stays bounded and Prometheus stays healthy.
  • Aggregate histograms before quantiling: sum the buckets across instances, then apply histogram_quantile once, to get an honest fleet-wide percentile.
  • Store dashboards and alert rules as code in version control, so a Grafana or Prometheus rebuild is reproducible rather than a hand-clicked ritual.
  • Secure the stack: change default Grafana credentials, put both UIs behind authentication, and never expose the scrape or admin ports to the public internet.
  • Use recording rules to pre-compute expensive PromQL expressions, so dashboards and alerts read a cheap pre-aggregated series instead of recomputing on every refresh.

Practice Exercises

  1. Extend the counter example to also compute the rate over just the last two samples (a shorter window) and compare it to the full-window rate, then explain in a sentence why the short window is noisier.
  1. Add a fifth bucket at le 5.0 with cumulative count 100 to the histogram and recompute p99 by hand under the interpolation rule, then run the code to confirm your answer.
  1. Modify the reset-aware function to count how many resets occurred in a series, and test it on a sequence that restarts twice, confirming it detects both drops.
  1. Write the PromQL you would use to graph the per-second error rate (fraction of 5xx responses) for a service, given a counter split by a status label, and explain which function makes it reset-safe.