Monitoring with Prometheus and Grafana / Start Here

How Prometheus collects, stores and serves metrics

Lesson 4 of 35. Open to read. No account needed.

Your stack is running and the stack check passes. This lesson explains what is happening inside it: how a number in the shop's memory becomes something you can query, graph and alert on, and which component is responsible for each step. Knowing the path is what lets you diagnose monitoring later, because every "the dashboard is empty" problem is a break somewhere along it.

You will finish by stopping the shop on purpose and reading, from Prometheus's own evidence, exactly what it noticed and when.

The Path of One Metric

How Prometheus collects, stores and serves metrics. On the left, the shop is a target that keeps metrics in its code and serves them on /metrics. Inside one Prometheus server process, the scrape loop sends GET /metrics to the shop every 15 seconds and appends the returned samples, with job and instance labels and an up value, to the TSDB, its local time-series storage on disk. The HTTP API and web UI read the TSDB to answer PromQL queries from Grafana, which draws panels but stores no samples, and from a browser or curl. Rule evaluation runs every evaluation interval, reads the TSDB, writes recorded series back into it, and sends alerts to Alertmanager, which groups, routes and silences them and sends notifications to a receiver such as chat, email or a webhook. Arrows point from the side that starts each exchange.

Follow the arrows in the diagram from left to right. Each arrow points from the component that starts the exchange.

1. The target keeps the numbers. A target is anything Prometheus collects metrics from; in your stack, the shop and Prometheus itself. The shop's code holds its metrics in memory and, when asked, renders their current values as text on /metrics. The shop does not send anything anywhere and keeps no history: it only knows the value now.

2. Prometheus pulls. Every scrape interval (15 seconds in your configuration), Prometheus's scrape loop sends GET /metrics to each target and reads the reply. This is called a scrape, and the model is pull: Prometheus decides what to collect and when, from a list in its configuration. Because Prometheus holds the list, it knows when a target that should answer does not, which is the basis of the exercise below.

3. Prometheus labels and stores. Each line in a scrape becomes one sample, a value with a timestamp, in a time series, the history of one metric with one particular set of labels. Prometheus adds two labels to everything it scrapes: job, from the job_name in its configuration, and instance, the address it scraped. Samples go into the TSDB, the time-series database stored in the pmg_prometheus-data volume. All storage is local to this one server.

4. Prometheus records its own view of every scrape. Alongside the target's metrics, each scrape produces a few series about the scrape itself:

SeriesMeaning
up1 if the scrape succeeded, 0 if it failed
scrape_duration_secondsHow long the scrape took
scrape_samples_scrapedHow many samples the target returned

up is the answer to the question from the previous lessons, "is Prometheus actually collecting this target?". It exists even when the target is completely unreachable, precisely because Prometheus wrote it, not the target.

5. Rules run on a timer. Every evaluation interval (also 15 seconds here), Prometheus can evaluate rules: queries it runs by itself. A recording rule saves a query's result as a new series in the TSDB. An alerting rule turns a query that returns results into alerts and sends them to Alertmanager. Your configuration has no rules yet; they arrive in the Rules and Alerting module.

6. Alertmanager notifies, but detects nothing. Alertmanager receives alerts that Prometheus has already decided are true, groups related ones, routes them to the right receiver, applies silences, and sends notifications. It never looks at metrics itself. If no rule fires, it has nothing to say.

7. Clients pull answers. The HTTP API answers queries written in PromQL, Prometheus's query language. The web interface you opened is one client of this API, curl is another, and Grafana is a third. Grafana sends PromQL and draws the answer; it stores no samples. If Prometheus loses data, Grafana has nothing to show.

Why pull?

Pulling means Prometheus has an expected list of targets, so silence is visible: a target that stops answering produces up = 0 instead of simply disappearing. It also means you can open any target's /metrics page in a browser and see exactly what Prometheus sees. Short-lived batch jobs, which may finish before any scrape, are the awkward case; the course covers the narrow situation where pushing through a gateway makes sense later.

A Tour of the Prometheus Interface

Open http://127.0.0.1:19090. The pinned version's top bar has Query, Alerts and a Status menu.

Query is the expression browser. Type an expression in the box and press Execute. The Table tab shows the current value of each matching series; Graph shows values over a time range; Explain breaks an expression into its parts. Try up, press Execute, and stay on Table. You should see two rows (illustrative values):

up{instance="localhost:9090", job="prometheus"}   1
up{instance="shop:8000", job="shop"}              1

Each row is one series: the metric name up, then its labels in braces, then its latest value. The job and instance labels were added by Prometheus, as described above.

Now open Status. Its entries in this version are Target health, Rule health, Service discovery, Runtime & build information, TSDB status, Command-line flags, Configuration and Alertmanager discovery. Choose Target health (address /targets). Each job is a section, and each target a row with four columns:

ColumnWhat it tells you
EndpointThe exact URL scraped, for example http://shop:8000/metrics
LabelsThe labels attached to this target's series
Last scrapeHow long ago the last scrape was, and how long it took
StateUP or DOWN; a DOWN row also shows the error from the last scrape

The same information is available as JSON from the HTTP API, which is what scripts and the stack check use:

curl -s 'http://127.0.0.1:19090/api/v1/query?query=up'
curl -s http://127.0.0.1:19090/api/v1/targets

The first returns the result you saw in the Table tab as JSON: "resultType":"vector" (one value per series) and, for each series, its metric labels and a value pair of a Unix timestamp and the value as a string. The second returns, for each target, fields including scrapeUrl, health, lastScrape, lastScrapeDuration and lastError.

Exercise: Follow a Scrape Failure

Goal. Stop the shop on purpose and observe how each part of the path reports it, then restore it. This is the skill behind every later diagnosis: read the evidence that each component produces instead of guessing.

Starting state. The stack from the previous lesson is running and bash tests/check-stack.sh reports seven passes. Run every command from ~/pmg-practice.

Effects. Stops and restarts only the pmg-shop-1 container. Nothing is deleted.

Predict first

Before stopping anything, write down what you expect each of these to show while the shop is stopped:

  1. Target health for the shop job.
  2. The value of up{job="shop"}.
  3. A Grafana panel graphing the shop's metrics (you have none yet; predict).
  4. An alerting rule that fires when up == 0 (you have none yet; predict).
  5. The load generator.

Stop the shop and watch

docker compose stop shop

Then reload Status > Target health in the browser every few seconds. The shop row stays UP until the next scrape, then turns DOWN. On the author's machine that took 14 seconds, just under one 15-second interval; you will see anything from almost immediately up to about 15 seconds, depending on where in the interval you stopped it.

The DOWN row shows an error like this (illustrative):

Get "http://shop:8000/metrics": dial tcp: lookup shop on 127.0.0.11:53: no such host

Read it from the right. no such host means the name shop could not be turned into an address. 127.0.0.11:53 is Docker's internal name server, which only knows the names of running containers in the network; a stopped container's name disappears. So this message says "the shop's container is not running", not "the shop answered badly". Other failures produce other messages, and the step they name (name lookup, connecting, an HTTP status, a timeout) tells you where the path broke.

Query up{job="shop"} on the Query page, or from the terminal:

curl -s 'http://127.0.0.1:19090/api/v1/query?query=up%7Bjob%3D%22shop%22%7D'

The %7B and similar sequences are the URL-encoded form of up{job="shop"}. The value is now "0". Prometheus still writes an up sample for the shop at every interval; it just records failure.

Check the load generator:

docker compose logs --tail 3 loadgen

It prints nothing new. It catches the connection errors and retries every two seconds, which is why it did not crash.

Restore it

docker compose start shop

Within about one interval the target is UP again. Now look at the history of up for the shop over the last few minutes. On the Query page, enter up{job="shop"}[3m] and use the Table tab: a range like [3m] asks for every sample in the last three minutes rather than only the latest. The author saw this sequence of values, oldest first:

1, 1, 0, 1, 1

Each value is one scrape, 15 seconds apart. The single 0 is the scrape that happened while the shop was stopped. Your sequence will differ in length and in how many zeros it contains, depending on how long the shop was down.

What your predictions should have been

  1. Target health: DOWN after the next scrape, with the name-lookup error.
  2. up{job="shop"} = 0 while stopped, written by Prometheus every interval.
  3. A panel of the shop's own metrics would show a gap or stop updating, because no new samples arrive; it would not show zero. Only up, written by Prometheus, records the failure as a value.
  4. A rule on up == 0 would find the shop's series and, after any waiting period the rule specifies, send an alert to Alertmanager, which would send a notification.
  5. The load generator keeps running and retries.

Prediction 3 is the one most people get wrong, and it matters: when a target disappears, its own metrics go silent rather than turning into zeros. Alert on up, which Prometheus always writes, not on the absence of a value you hope to see.

When something differs

  • The row never turns DOWN. Confirm the container really stopped: docker compose ps --all should show the shop as exited. Then wait a full 15 seconds and reload; the page does not refresh by itself.
  • up{job="shop"} returns nothing at all. The query was mistyped (label values are case-sensitive and need double quotes), or you are looking at a time before the shop was ever scraped.
  • The target stays DOWN after start. Check docker compose logs shop for a Python error, and confirm curl -s http://127.0.0.1:19200/healthz answers.

Independent task

Without the browser, find the shop target's health and last error from the terminal while it is stopped. Use the targets API with grep -o to extract only the fields you need. Then explain what the instance label would be if the configuration listed the target as shop:8000 under a job called api.

Answer

Stop the shop, wait one interval, then:

curl -s http://127.0.0.1:19090/api/v1/targets | grep -o '"health":"[a-z]*"'
curl -s http://127.0.0.1:19090/api/v1/targets | grep -o '"lastError":"[^,]*'

The first prints one "health" value per target ("up" for Prometheus, "down" for the shop). The second prints each target's last error; the shop's begins with Get \"http://shop:8000/metrics\" (the API escapes the quotes inside the message) and ends with no such host. The pattern stops at the first comma, which is enough to show the message. Restart the shop with docker compose start shop afterwards.

The instance label would still be shop:8000: it is the scraped address, while the job name only sets the job label, which would become api.

Cleanup. Make sure the shop is running again (bash tests/check-stack.sh reports seven passes). Keep the stack for the next module.

Check Your Understanding

  1. Grafana shows no data for the shop. Name the two places on the path you would check first, in order, and why.
  2. Why can up report a failure when the target's own metrics cannot?
  3. True or false: Alertmanager decides that the error rate is too high.

Answers

  1. First, Prometheus's Target health page or up{job="shop"}: if Prometheus is not collecting the shop, nothing downstream can show it. Second, the query Grafana sends, by running it on Prometheus's Query page: if it returns data there, the problem is in Grafana's panel, not in collection.
  2. up is written by Prometheus at every scrape attempt, success or not. A target's own metrics only arrive when a scrape succeeds, so they go silent instead of reporting failure.
  3. False. A Prometheus alerting rule decides; Alertmanager only groups, routes, silences and notifies the alerts it receives.

30 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy