13.6 Prometheus — scrape and store
Why: the problem
PhonePe gets lakhs of UPI payments per minute. The team wants to know: how many payments failed in the last 5 minutes, on which server, and is it worse than last week? Prometheus answers questions like these with its query language, PromQL. Prometheus is not only a collector. It is a time series database with a powerful calculator. It also has service discovery, so new EC2 or Kubernetes servers are found automatically, recording rules to pre-compute heavy queries, and retention to decide how long data stays. If you can write ten good PromQL queries, you can build any dashboard and any alert. That is why we spend a full lesson on Prometheus itself.
What we will build
You will write a richer prometheus.yml with relabeling and EC2 service discovery. Then you will practise the PromQL queries you will use every day: rate, sum by, topk, percent used, increase and offset. Finally you will add recording rules and check everything with promtool, the Prometheus checker.
What: every term in plain English
- PromQL — Prometheus Query Language. Used to select and calculate metrics.
- Instant vector — The latest value of each series, like node_load1 now.
- Range vector — Values over a window, like node_load1[5m].
- rate() — Per-second speed of a counter over a window.
- increase() — How much a counter grew in a window, like errors in the last hour.
- Recording rule — A query Prometheus runs again and again and saves as a new metric.
- Service discovery — Finding targets automatically from AWS, Kubernetes or files.
- Retention — How long Prometheus keeps data, like 15 days.
How: step by step
-
Open the query page
Browser: http://SERVER_IP:9090/graphWhat it does: Type a query, click Execute, choose Table or Graph.
Output
(query box) -
Try a simple query
node_load1What it does: Shows the latest load of each server.
Output
node_load1{instance="node-exporter:9100",job="node"} 0.21 -
Try a range query
node_load1[1m]What it does: Shows the raw points of the last minute (4 points at 15s).
Output
0.21 @1761406800 0.19 @1761406815 ... -
Check config before reload
promtool check config prometheus.ymlWhat it does: Catches YAML and rule mistakes.
Output
SUCCESS: prometheus.yml is valid prometheus config file syntax -
Reload without restart
curl -X POST localhost:9090/-/reloadWhat it does: Works when Prometheus runs with --web.enable-lifecycle.
Output
(no output)
Example 1: A real-world prometheus
Stack. Prometheus, AWS EC2 service discovery
Goal. A real-world prometheus.yml with EC2 discovery and relabeling.
prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s
external_labels:
cluster: mumbai-prod
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
- job_name: node-ec2
ec2_sd_configs:
- region: ap-south-1
port: 9100
filters:
- name: tag:Monitoring
values: ["on"]
relabel_configs:
- source_labels: [__meta_ec2_tag_Name]
target_label: name
- source_labels: [__meta_ec2_private_ip]
regex: (.*)
replacement: ${1}:9100
target_label: __address__
Start flags (compose command line)
command:
- --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.retention.time=15d
- --web.enable-lifecycle
What each line does
external_labels— Added to every series. Useful when many Prometheus servers exist.rule_files— Where recording and alert rules live.ec2_sd_configs— Ask AWS for all EC2 instances in Mumbai (ap-south-1).filters tag:Monitoring = on— Only servers with this tag are scraped.__meta_ec2_tag_Name to name— Copy the EC2 Name tag into a nice label.__address__— The address Prometheus will scrape. We set private IP plus :9100.retention.time=15d— Keep 15 days of data.--web.enable-lifecycle— Allows the /-/reload endpoint.
Green output
Targets page:
node-ec2 (3/3 up)
http://10.0.1.12:9100/metrics UP name="orders-web-1"
http://10.0.1.13:9100/metrics UP name="orders-web-2"
http://10.0.2.40:9100/metrics UP name="orders-db-1"
Expected result. New servers with tag Monitoring=on appear in about a minute, with no config change. Prometheus needs an IAM role with ec2:DescribeInstances.
Example 2: Ten PromQL queries you will use every day
Stack. PromQL
Goal. Ten PromQL queries you will use every day.
daily.promql
# 1. Which servers are down? (1 = up, 0 = down)
up == 0
# 2. CPU busy percent per server
100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])))
# 3. Memory used percent
100 * (1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)
# 4. Disk used percent on /
100 * (1 - node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"})
# 5. Network in, megabits per second
rate(node_network_receive_bytes_total{device="eth0"}[5m]) * 8 / 1e6
# 6. Top 3 busiest servers
topk(3, 100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))))
# 7. Errors in the last hour
sum(increase(http_requests_total{status=~"5.."}[1h]))
# 8. Traffic now vs same time last week
sum(rate(http_requests_total[5m])) / sum(rate(http_requests_total[5m] offset 7d))
# 9. Disk full in 4 hours? (linear guess)
-1 * predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 4 * 3600) > 0
# 10. Servers rebooted in the last hour
changes(node_boot_time_seconds[1h]) > 0
What each line does
up == 0— up is a metric Prometheus makes for every target. 0 means the scrape failed.avg by (instance)— Average all CPUs of one server into one number.topk(3, ...)— Keep only the 3 highest.increase(...[1h])— Total errors in the last hour.offset 7d— Same query, 7 days ago. 1.3 means 30% more traffic than last week.predict_linear(...)— Draws a straight line through the last 6 hours and guesses the value 4 hours later. A negative value means the disk will be full.changes(...)— How many times the value changed. Boot time changes on reboot.
Green output
1. (empty result: all servers up)
2. {instance="10.0.1.12:9100"} 34.2 {instance="10.0.1.13:9100"} 31.0
3. {instance="10.0.1.12:9100"} 61.5
4. {instance="10.0.2.40:9100", mountpoint="/"} 82.0
6. orders-web-1 34.2, orders-web-2 31.0, orders-db-1 12.4
8. 1.27
Expected result. These ten queries cover health, capacity and trends. Save them in your notes; you will paste them into Grafana and alerts again and again.
Example 3: Recording rules to make dashboards fast, checked with promtool
Stack. Prometheus recording rules, promtool
Goal. Recording rules to make dashboards fast, checked with promtool.
rules/recording.yml
groups:
- name: node-recording
interval: 30s
rules:
- record: instance:cpu_busy:percent
expr: 100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])))
- record: instance:mem_used:percent
expr: 100 * (1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)
- record: job:http_errors:ratio5m
expr: sum by (job) (rate(http_requests_total{status=~"5.."}[5m])) / sum by (job) (rate(http_requests_total[5m]))
Check and reload
sudo docker run --rm -v $PWD:/c --entrypoint promtool \
prom/prometheus:v2.54.1 check rules /c/rules/recording.yml
curl -s -X POST localhost:9090/-/reload
curl -s "localhost:9090/api/v1/query?query=instance:cpu_busy:percent" | grep -o '"value":[^]]*'
What each line does
record: instance:cpu_busy:percent— The name of the new saved metric. The style is level:metric:operation.expr:— The query to run every 30 seconds.interval: 30s— How often this group runs.promtool check rules— Validates the file before you load it./-/reload— Loads new rules without a restart.
Green output
Checking /c/rules/recording.yml
SUCCESS: 3 rules found
"value":[1761407000.5,"34.21"
Expected result. Grafana can now query instance:cpu_busy:percent, which is one cheap lookup instead of a heavy calculation each time.
Verify: did it work?
-
Rules loaded?
curl -s localhost:9090/api/v1/rules | grep -o '"name":"[^"]*"' | headWhat it does: Shows rule group and rule names.
Output
"name":"node-recording" "name":"instance:cpu_busy:percent" -
How big is the database?
sudo docker compose exec prometheus du -sh /prometheusWhat it does: Size on disk.
Output
412M /prometheus
When it is red 1
Error executing query: vector cannot contain metrics with the same labelset
Cause. The division matched many series with the same labels after a by() or on a counter without rate.
Fix, step by step
- Use rate() on counters before dividing.
- Make both sides have the same labels with by (instance).
- Use ignoring(mode) or on(instance) when labels differ.
When it is red 2
Lifecycle API is not enabled
Cause. /-/reload was called but the flag is missing.
Fix, step by step
- Add --web.enable-lifecycle to the command.
- Restart Prometheus once.
- Use curl -X POST localhost:9090/-/reload after that.
When it is red 3
ec2_sd: operation error EC2: DescribeInstances, UnauthorizedOperation
Cause. The Prometheus server role cannot list EC2 instances.
Fix, step by step
- Attach a policy that allows ec2:DescribeInstances.
- Wait one minute.
- Check Status, then Service Discovery in the UI.
Cleanup
-
Delete test rules
rm rules/recording.yml && curl -s -X POST localhost:9090/-/reloadWhat it does: Removes the rules.
Output
(no output) -
Free disk in a lab
sudo docker compose down -vWhat it does: Deletes the stored data.
Output
Volume monstack_prom-data Removed
Ravindra Bagale's Tip
Memorise ten PromQL queries: up, CPU, memory, disk, rate, topk, increase, offset. The rest are built from these.
PromQL चे १० query लक्षात ठेवा: up, CPU, memory, disk, rate, topk, increase, offset. बाकी सगळं यांच्यावरून बनतं.
PromQL के १० query याद रखो: up, CPU, memory, disk, rate, topk, increase, offset. बाकी सब इन्हीं से बनते हैं.
Practice tasks
Easy Count your series
Why: Series count shows how heavy your Prometheus is.
What to do: Run count({__name__=~".+"}).
- Paste it in the Graph page.
Check: You see a number like 3,500.
Medium Find the biggest metric
Why: High cardinality hides in one or two metrics.
What to do: Run topk(5, count by (__name__)({__name__=~".+"})).
- Read the top names.
Check: You know which metric uses most series.
Hard File-based discovery
Why: Many companies keep target lists in files from Ansible.
What to do: Use file_sd_configs with a targets.json file.
- Write targets.json with two servers.
- Point file_sd_configs to it.
- Edit the file and see targets change without reload.
Check: Targets update within a minute.
Easy Say Prometheus and PromQL 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 Prometheus and PromQL for a fresher who knows only Linux, Git and Docker basics.
- Write the problem it solves.
- Write the one command, query or config line you use for it.
- 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.
- docker run -d --name ne -p 9100:9100 prom/node-exporter
- curl -s localhost:9100/metrics | grep node_load1
- 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.
- If you used Prometheus, try the CloudWatch console or AWS CLI.
- Keep the same question: is it up, is it fast, is it failing, is it full?
- 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.
- Follow the error section.
- Copy the exact message into your notes.
- 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.
- 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.
- 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.
- 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, write a PromQL query that shows the free disk in GB on every server, sorted from smallest to biggest with sort(). Then add it as a recording rule and check it with promtool.
Recap
- Prometheus stores metrics and answers PromQL queries.
- rate, sum by, topk, increase and offset cover most daily needs.
- Service discovery finds EC2 or Kubernetes targets automatically.
- Recording rules make heavy queries cheap.
- Always run promtool before reload.
FAQ
How long should I keep data?
15 to 30 days locally is common. Use remote storage for more.
Why is my query slow?
Too many series or a long range. Use recording rules and smaller windows.
rate or irate?
rate for alerts and dashboards; irate only for very spiky short views.
Can Prometheus run in HA?
Run two identical servers. Alertmanager removes duplicate alerts.
What is Amazon Managed Service for Prometheus?
AWS runs Prometheus storage for you; you send data with remote_write.
Interview questions
-
What is the difference between rate and increase?
rate gives per-second average; increase gives the total growth in the window. increase = rate times window seconds.
-
What is a recording rule and why use it?
A rule that pre-computes a query and stores it as a new series, to make dashboards and alerts fast.
-
How does Prometheus discover targets in AWS?
With ec2_sd_configs, plus relabel_configs to set the address and labels from EC2 tags.
-
How do you reload Prometheus config?
Send SIGHUP or POST to /-/reload with --web.enable-lifecycle; validate with promtool first.
-
What does predict_linear do?
It does a linear regression over a range and predicts the value in the future, often for disk-full alerts.
Quick quiz
Q1. Which function gives per-second speed of a counter?
rate().
Q2. What does up == 0 show?
Targets Prometheus could not scrape.
Q3. How do you compare with last week?
Use offset 7d.
Q4. What does a recording rule do?
Saves the result of a query as a new metric on a schedule.
Q5. Which tool checks the config?
promtool.
Did you understand? Let us try it once more.
Revision card
Interview card
Comparison card