Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 25 min · revision 2

PromQL and a rate-errors-duration dashboard

Write the three PromQL queries behind a RED dashboard, request rate, error ratio and p95 latency per route, from one OpenTelemetry histogram; prove them against known numbers with promtool; and generate a Grafana dashboard that shows them for each endpoint.

Contentsand lesson path

What you will learn

  • Query metrics with PromQL and build a dashboard that shows request rate, errors and duration for each endpoint.

01. The problem

ask-api from the previous lab now emits one histogram, http.server.request.duration. Your team wants a dashboard that answers three questions for every endpoint at a glance: how much traffic is it serving, what share of requests fail, and how slow are the slow ones? That is the RED view: rate, errors, duration.

PromQL makes this look easy, and it is also easy to get subtly wrong: a percentile averaged across instances, a ratio that silently drops routes, a rate() applied in the wrong place. So this worked example does three things in order: write each query and say why it has that shape; check all three against made-up data whose answers you can work out by hand; then turn them into a dashboard defined in code.

02. Step 1: Know the series you are querying

In Prometheus, the OpenTelemetry histogram becomes three families of series. Dots in names become underscores, and the unit becomes a _seconds suffix:

The series behind one histogram (labels abridged)
http_server_request_duration_seconds_bucket{http_route, http_response_status_code,
                                            http_request_method, le, job, ...}
http_server_request_duration_seconds_count {same labels, without le}
http_server_request_duration_seconds_sum   {same labels, without le}

le buckets (seconds): 0.005 0.01 0.025 0.05 0.075 0.1 0.25 0.5 0.75 1 2.5 5 7.5 10 +Inf

All three are counters: they only grow while the process runs. _count counts requests, so you do not need a separate request counter. Each _bucket counts requests that took at most le seconds, so the buckets are cumulative and the +Inf bucket equals _count. _sum adds up the durations. The job label names the service: when metrics arrive over OTLP, as in lesson 5, Prometheus sets it from service.name.

Two consequences shape every query below. First, the raw value of a counter is meaningless on a graph, because it depends on when the process last restarted; you always look at how fast it grows. Second, a percentile cannot be read from one series; it has to be estimated from the buckets of many.

03. Step 2: Request rate per route

PromQL · requests per second, per route
sum by (http_route) (
  rate(http_server_request_duration_seconds_count{job="ask-api"}[5m])
)

Read it from the inside out:

  1. [5m] selects every sample of every matching series over the last five minutes, one series per combination of route, status code, method and instance.
  2. rate() turns each series into a per-second rate of increase over that window, and corrects for counter resets when a process restarts.
  3. sum by (http_route) adds the per-series rates and keeps only the route label, so status codes, methods and instances fold together.

The order matters: rate first, then sum. If you summed raw counters first, a restart of one instance would look like a sudden drop in the total, and rate() would read it as a reset of the whole sum. Choose a window of at least four scrape or export intervals, so every window holds several samples; five minutes is a common default for alerts, while a dashboard can let Grafana pick with $__rate_interval.

04. Step 3: Error ratio per route

An error count on its own is hard to judge: 30 errors a minute is a disaster at 40 requests a minute and noise at 40,000. Divide errors by all requests on the same route:

PromQL · share of requests answered with 5xx
sum by (http_route) (
  rate(http_server_request_duration_seconds_count{
    job="ask-api", http_response_status_code=~"5.."}[5m])
)
/
sum by (http_route) (
  rate(http_server_request_duration_seconds_count{job="ask-api"}[5m])
)

=~"5.." is a regular-expression match for any 5xx status. Count 5xx only: a 4xx usually means the client sent something wrong, and folding those in would let one broken client page you. Decide case by case for statuses such as 429, which can mean your own rate limits are hurting users.

Both sides are summed by the same label, so PromQL divides them route by route. There is a catch. A route with no 5xx at all has no series on the left, so it is missing from the result instead of showing 0, and a panel or alert looking for it finds nothing. The fix is to fill the gaps with zeros taken from the right-hand side:

PromQL · the same ratio, with 0 for routes that never failed
(
  sum by (http_route) (rate(http_server_request_duration_seconds_count{
    job="ask-api", http_response_status_code=~"5.."}[5m]))
  or
  0 * sum by (http_route) (
    rate(http_server_request_duration_seconds_count{job="ask-api"}[5m]))
)
/
sum by (http_route) (
  rate(http_server_request_duration_seconds_count{job="ask-api"}[5m])
)

or keeps every series from its left side and adds the series from its right side whose labels are not already present; multiplying by 0 turns those into zeros. Routes with no traffic at all still divide 0 by 0 and give NaN, which Grafana shows as a gap. That is honest: no traffic means no error ratio.

05. Step 4: p95 latency per route

PromQL · 95th percentile duration, per route
histogram_quantile(0.95,
  sum by (le, http_route) (
    rate(http_server_request_duration_seconds_bucket{job="ask-api"}[5m])
  )
)

histogram_quantile() needs the rate of each bucket, summed across everything you want to fold together, with le kept in the by clause. It walks the cumulative buckets, finds the one where 95% of requests have been counted, and interpolates linearly inside it. Drop le and the function has no buckets to walk, so it returns nothing.

Because you sum bucket rates before computing the quantile, the result is a real p95 across all instances. The tempting alternative, computing p95 per instance and then averaging, gives a number that is not the 95th percentile of anything. Remember too that the answer is an estimate whose precision depends on the buckets: anything between 0.25 s and 0.5 s is placed by interpolation. If your latency target sits between two boundaries, configure the histogram with a boundary at the target, through an OpenTelemetry View.

The mean is cheaper and still useful next to the percentile, for example to see whether the whole distribution moved or only its tail:

PromQL · mean duration, per route
sum by (http_route) (
  rate(http_server_request_duration_seconds_sum{job="ask-api"}[5m])
)
/
sum by (http_route) (
  rate(http_server_request_duration_seconds_count{job="ask-api"}[5m])
)

06. Step 5: Prove the queries against known numbers

Before a query goes on a dashboard or into an alert, check it on data where you know the answer. promtool, which ships with Prometheus, runs PromQL against series you describe in a YAML file and compares the results with what you expect. 0+600x10 means a series that starts at 0 and grows by 600 per interval for ten intervals: a counter at 10 requests per second.

YAML · red_test.yml
# Ten minutes of made-up traffic, one sample per minute, then three checks.
tests:
  - interval: 1m
    input_series:
      # /ask answered 600 requests a minute with 200 and 30 with 502.
      - series: 'http_server_request_duration_seconds_count{
          http_route="/ask", http_response_status_code="200"}'
        values: '0+600x10'
      - series: 'http_server_request_duration_seconds_count{
          http_route="/ask", http_response_status_code="502"}'
        values: '0+30x10'
      - series: 'http_server_request_duration_seconds_count{
          http_route="/healthz", http_response_status_code="200"}'
        values: '0+120x10'
      # Buckets count requests at or below each boundary (le), in seconds.
      - series: 'http_server_request_duration_seconds_bucket{
          http_route="/ask", http_response_status_code="200", le="0.1"}'
        values: '0+300x10'
      - series: 'http_server_request_duration_seconds_bucket{
          http_route="/ask", http_response_status_code="200", le="0.25"}'
        values: '0+480x10'
      - series: 'http_server_request_duration_seconds_bucket{
          http_route="/ask", http_response_status_code="200", le="0.5"}'
        values: '0+582x10'
      - series: 'http_server_request_duration_seconds_bucket{
          http_route="/ask", http_response_status_code="200", le="+Inf"}'
        values: '0+600x10'
      # The 502s fail fast: all 30 a minute land in the first bucket.
      - series: 'http_server_request_duration_seconds_bucket{
          http_route="/ask", http_response_status_code="502", le="0.1"}'
        values: '0+30x10'
      - series: 'http_server_request_duration_seconds_bucket{
          http_route="/ask", http_response_status_code="502", le="0.25"}'
        values: '0+30x10'
      - series: 'http_server_request_duration_seconds_bucket{
          http_route="/ask", http_response_status_code="502", le="0.5"}'
        values: '0+30x10'
      - series: 'http_server_request_duration_seconds_bucket{
          http_route="/ask", http_response_status_code="502", le="+Inf"}'
        values: '0+30x10'
    promql_expr_test:
      - expr: |
          sum by (http_route) (
            rate(http_server_request_duration_seconds_count[5m])
          )
        eval_time: 10m
        exp_samples:
          - labels: '{http_route="/ask"}'
            value: 10.5
          - labels: '{http_route="/healthz"}'
            value: 2
      - expr: |
          (
            sum by (http_route) (rate(http_server_request_duration_seconds_count{
              http_response_status_code=~"5.."}[5m]))
            or
            0 * sum by (http_route) (
              rate(http_server_request_duration_seconds_count[5m]))
          )
          /
          sum by (http_route) (rate(http_server_request_duration_seconds_count[5m]))
        eval_time: 10m
        exp_samples:
          - labels: '{http_route="/ask"}'
            value: 0.047619047619047616
          - labels: '{http_route="/healthz"}'
            value: 0
      - expr: |
          histogram_quantile(0.95,
            sum by (le, http_route) (
              rate(http_server_request_duration_seconds_bucket[5m])
            )
          )
        eval_time: 10m
        exp_samples:
          - labels: '{http_route="/ask"}'
            value: 0.46691176470588236
Terminal · in the folder that holds red_test.yml
# promtool ships in the Prometheus release archive (Linux x86-64 shown here).
V=3.16.0; A=prometheus-$V.linux-amd64
curl -sSfLO "https://github.com/prometheus/prometheus/releases/download/v$V/$A.tar.gz"
tar xzf "$A.tar.gz"
"./$A/promtool" test rules red_test.yml
# Or, with Docker:
# docker run --rm -v "$PWD":/w -w /w --entrypoint promtool \
#   prom/prometheus:v3.16.0 test rules red_test.yml
Expected output
Processing test file: red_test.yml
  SUCCESS

Every expected value can be checked by hand from the per-minute increases:

The arithmetic behind the expected values
requests per minute, /ask:  200s 600 + 502s 30 = 630   -> 630 / 60 = 10.5 per second
error ratio, /ask:          30 / 630                   = 0.0476
cumulative buckets, /ask:   <=0.1: 330   <=0.25: 510   <=0.5: 612   <=+Inf: 630
95th percentile rank:       0.95 x 630 = 598.5, between 510 and 612 -> (0.25, 0.5]
linear interpolation:       0.25 + 0.25 x (598.5 - 510) / (612 - 510) = 0.4669 s

Now break a query on purpose to see a failure: change sum by (le, http_route) to sum by (http_route) in the third test and run promtool again. It prints FAILED, the expression, the expected sample and got: nil, because without le there are no buckets left to interpolate. Keep a test like this next to every recording rule and alert; it catches typos in label names, too, which PromQL otherwise accepts silently as matching nothing.

07. Step 6: Turn the queries into a dashboard

Grafana stores a dashboard as JSON. Writing that JSON by hand is error-prone, and clicking it together in the UI leaves nothing to review. A short script keeps the dashboard in version control next to the service, with each query defined once. Save it in the ask-service folder from lab 2.

Python · make_dashboard.py
"""Write the RED dashboard for ask-api as Grafana dashboard JSON."""
import json
import pathlib

M = "http_server_request_duration_seconds"
SEL = 'job="ask-api", http_route=~"$route"'
WIN = "[$__rate_interval]"  # Grafana picks a window that suits the scrape interval

RATE = f"sum by (http_route) (rate({M}_count{{{SEL}}}{WIN}))"
ERRORS = (
    f'(sum by (http_route) (rate({M}_count{{{SEL}, http_response_status_code=~"5.."}}'
    f"{WIN})) or 0 * {RATE}) / {RATE}"
)
BUCKETS = f"sum by (le, http_route) (rate({M}_bucket{{{SEL}}}{WIN}))"
P95 = f"histogram_quantile(0.95, {BUCKETS})"
PROM = {"type": "prometheus", "uid": "prom"}


def panel(pid: int, title: str, expr: str, unit: str, x: int) -> dict:
    return {
        "id": pid,
        "type": "timeseries",
        "title": title,
        "datasource": PROM,
        "gridPos": {"x": x, "y": 0, "w": 8, "h": 9},
        "fieldConfig": {"defaults": {"unit": unit}, "overrides": []},
        "targets": [
            {
                "refId": "A",
                "datasource": PROM,
                "expr": expr,
                "legendFormat": "{{http_route}}",
                "exemplar": True,  # dots that link to traces, where available
            }
        ],
    }


route_variable = {
    "name": "route",
    "type": "query",
    "datasource": PROM,
    "query": f'label_values({M}_count{{job="ask-api"}}, http_route)',
    "refresh": 2,  # reload the route list when the time range changes
    "includeAll": True,
    "multi": True,
    "current": {"text": "All", "value": "$__all"},
}
dashboard = {
    "uid": "ask-api-red",
    "title": "ask-api: rate, errors, duration",
    "schemaVersion": 41,
    "time": {"from": "now-30m", "to": "now"},
    "refresh": "30s",
    "templating": {"list": [route_variable]},
    "panels": [
        panel(1, "Requests per second", RATE, "reqps", 0),
        panel(2, "Share of requests failing with 5xx", ERRORS, "percentunit", 8),
        panel(3, "p95 latency", P95, "s", 16),
    ],
}
out = pathlib.Path("stack/grafana/dashboards/ask-api-red.json")
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(dashboard, indent=2))
print(f"wrote {out} with {len(dashboard['panels'])} panels")
Terminal · inside ask-service/, with the venv active
python make_dashboard.py
Expected output
wrote stack/grafana/dashboards/ask-api-red.json with 3 panels

The design choices are the ones a reviewer should look for:

  • One row, three panels, same order everywhere: rate, errors, duration. Anyone on call reads every service's dashboard the same way.
  • Units on every panel: reqps, percentunit (Grafana shows 0.048 as 4.8%) and s. A latency axis without a unit is a classic source of factor-of-1,000 mistakes.
  • A route variable, filled from the label values Prometheus actually has, so one dashboard serves every endpoint, and legendFormat naming each line by its route.
  • $__rate_interval instead of a fixed [5m]: Grafana chooses a window of at least four scrape intervals that also suits the zoom level.
  • Exemplars on, so the latency panel can show dots that link to traces once they are available.

Lesson 5 starts Grafana with this file already provisioned. To load it into another Grafana now, use Dashboards, New, Import and paste the JSON.

08. Check your understanding

Practice check · 3 questions

Read the queries

Three PromQL decisions from this worked example.

Q1. Why does the request-rate query apply rate() to each series and only then sum by route?
Q2. The simple error-ratio query returns a series for /ask but none for /healthz, which has steady traffic. What is the most likely reason?
Q3. In a 5-minute window, a route's cumulative bucket rates per second are le=0.1: 3, le=0.25: 8, le=0.5: 10, le=+Inf: 10. What does histogram_quantile(0.5, ...) return?
Practice only: not graded, not saved, not evidence.

09. Apply it

For the service in your skill project:

  • write the three RED queries for its histogram, with the label names your instrumentation really emits (check the /metrics page or Prometheus's label browser first);
  • add a promtool test with at least two routes, one of them without errors, and expected values you have worked out by hand;
  • generate the dashboard and add a fourth panel for the p95 duration of the outbound model call, from the httpx client histogram http_client_request_duration_seconds, broken down by server_address.

10. Review prompt

Without looking back, write the three RED queries for a histogram called rpc_server_duration_seconds grouped by a label rpc_method. Explain in one sentence each why rate() comes before sum, why le must survive the aggregation, and why the simple error ratio can hide healthy methods. Then name two settings every dashboard panel should have.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check