13.11 Anti-patterns
Why: the problem
A Bengaluru fintech team had great tools: Prometheus, Grafana, PagerDuty. Still, they had a three hour outage that nobody noticed for 40 minutes. Why? They watched CPU of every server but not the payment success rate. Their Grafana was open to the internet with the default password. They had 300 alert rules, and the real one went to a Slack channel everyone had muted. Their Prometheus crashed because a developer added user_id as a label, creating millions of series. None of these were tool problems. They were habit problems, called anti-patterns. An anti-pattern is a common way of doing something that looks right but hurts you later. Like eating only junk food because it is quick. Knowing the anti-patterns saves you from learning them the painful way, at 2 a.m., in front of your manager.
What we will build
You will fix five real anti-patterns, each with a bad version and a good version you can run. First, alerting on causes (CPU) instead of symptoms (user errors). Second, high cardinality labels that blow up Prometheus. Third, an open Grafana and open exporters, fixed with login settings and firewall rules. Fourth, alerts with no for: time and no owner. Fifth, using averages that hide slow users. Each fix comes with a command to prove it.
What: every term in plain English
- Anti-pattern — A common habit that looks right but causes harm later.
- Symptom-based alert — An alert on what users feel: errors, slow pages, failed payments.
- Cause-based alert — An alert on an inside reason: high CPU, many threads. Often noisy.
- Cardinality explosion — When labels with many values create millions of series and crash Prometheus.
- Alert owner — The team or person who must act on an alert.
- Flapping — An alert that goes firing, resolved, firing again and again.
- SLO — Service Level Objective. A target like "99.9% of payments succeed in a month".
- Error budget — The allowed failures in the SLO. 99.9% means 0.1% may fail.
How: step by step
-
List all alert rules
curl -s localhost:9090/api/v1/rules | python3 -m json.tool | grep '"name"' | wc -lWhat it does: How many rules you have. Too many is a smell.
Output
42 -
Find noisy alerts
Look at Alertmanager history or Slack and count fires per alert for 7 daysWhat it does: Alerts that fire daily and nobody acts on are noise.
Output
HighCPU fired 61 times, no action -
Find the biggest metrics
topk(10, count by (__name__)({__name__=~".+"}))What it does: Shows metrics with most series.
Output
{__name__="http_requests_total"} 184022 -
Check what is public
curl -s -m 5 http://PUBLIC_IP:9100/metrics | head -1 (from outside)What it does: Must time out.
Output
curl: (28) Connection timed out -
Apply the fixes
Examples 1 to 3What it does: Rules, labels and access fixed.
Output
(see below)
Example 1: Symptom alerts instead of cause alerts
Stack. Prometheus alert rules
Goal. Symptom alerts instead of cause alerts.
rules/bad.yml (do not copy)
groups:
- name: bad
rules:
- alert: HighCPU
expr: instance:cpu_busy:percent > 70
labels: {severity: critical}
rules/good.yml
groups:
- name: good
rules:
- alert: CheckoutErrorsHigh
expr: job:http_errors:ratio5m{job="checkout"} > 0.02
for: 5m
labels: {severity: critical, team: payments}
annotations:
summary: "Checkout errors {{ $value | humanizePercentage }} for 5m"
runbook: "https://wiki.example.in/runbooks/checkout-errors"
- alert: CheckoutSlow
expr: histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket{job="checkout"}[5m]))) > 1
for: 10m
labels: {severity: warning, team: payments}
- alert: CPUSaturatedLong
expr: instance:cpu_busy:percent > 95
for: 30m
labels: {severity: warning, team: platform}
What each line does
HighCPU > 70, no for:— Bad: fires on every short spike, at night, even when users are fine.CheckoutErrorsHigh— Good: fires only when users actually fail to pay.for: 5m— Good: a short blip does not page anyone.team: payments— Good: the alert has an owner, so routing sends it to the right team.runbook— Good: tells the person what to do.CPU > 95 for 30m, warning— CPU is still watched, but as a calm warning for capacity planning.
Green output
Last 7 days:
Before: HighCPU fired 61 times, 0 real incidents
After: CheckoutErrorsHigh fired 1 time (real incident, gateway timeout)
CheckoutSlow fired 2 times (real, slow DB query)
CPUSaturatedLong fired 0 times
Expected result. From 61 useless pages to 3 useful ones. People trust alerts again.
Example 2: Stop a cardinality explosion
Stack. Python prometheus_client, Prometheus relabeling
Goal. Stop a cardinality explosion.
Bad Python code (do not copy)
REQS = Counter("http_requests_total", "Requests", ["path", "user_id"])
REQS.labels(request.path, user.id).inc() # /order/98123, user 5512...
Good Python code
REQS = Counter("http_requests_total", "Requests", ["route", "status"])
REQS.labels("/order/{id}", str(status)).inc()
Safety net in prometheus.yml
- job_name: apps
sample_limit: 50000
metric_relabel_configs:
- regex: user_id
action: labeldrop
What each line does
["path", "user_id"]— Bad: every user and every order id makes a new series. Lakhs of series.["route", "status"]— Good: a few routes times a few status codes = small, fixed number."/order/{id}"— Use the route pattern, not the real URL.sample_limit: 50000— If a target suddenly sends more than 50,000 series, the scrape fails instead of crashing Prometheus.action: labeldrop— Removes the user_id label before storing, as a quick fix until code is changed.
Green output
Before: prometheus_tsdb_head_series 2,310,442 RAM 14 GB queries timing out
After: prometheus_tsdb_head_series 38,120 RAM 1.2 GB queries in 80 ms
Expected result. Series dropped from 2.3 million to 38 thousand. Watch prometheus_tsdb_head_series on your own Prometheus every week.
Example 3: Lock down Grafana and the exporters
Stack. Grafana, Docker Compose, ufw, AWS security groups
Goal. Lock down Grafana and the exporters.
Grafana environment in compose.yaml
environment:
- GF_SECURITY_ADMIN_PASSWORD__FILE=/run/secrets/grafana_admin
- GF_USERS_ALLOW_SIGN_UP=false
- GF_AUTH_ANONYMOUS_ENABLED=false
- GF_SERVER_ROOT_URL=https://grafana.example.in
ports:
- "127.0.0.1:3000:3000"
Ubuntu firewall on each server
sudo ufw allow from 10.0.0.10 to any port 9100 proto tcp
sudo ufw deny 9100/tcp
sudo ufw allow OpenSSH
sudo ufw --force enable
sudo ufw status numbered
What each line does
__FILE suffix— Grafana reads the admin password from a secret file, not plain env.ALLOW_SIGN_UP=false— Strangers cannot create accounts.ANONYMOUS_ENABLED=false— No viewing without login."127.0.0.1:3000:3000"— Grafana listens only on localhost. Put nginx with HTTPS or an ALB in front.ufw allow from 10.0.0.10 ... 9100— Only the Prometheus server can read the exporter.ufw deny 9100/tcp— Everyone else is blocked.
Green output
Status: active
To Action From
-- ------ ----
[ 1] 9100/tcp ALLOW IN 10.0.0.10
[ 2] 9100/tcp DENY IN Anywhere
[ 3] OpenSSH ALLOW IN Anywhere
From your laptop: curl -m 5 http://PUBLIC_IP:9100/metrics
curl: (28) Connection timed out after 5001 milliseconds
Expected result. Grafana needs a login and is not directly public. Exporters answer only the Prometheus server. On AWS do the same with security groups.
Verify: did it work?
-
Count series
curl -s localhost:9090/api/v1/query?query=prometheus_tsdb_head_series | grep -o '"value":[^]]*'What it does: Track this number weekly.
Output
"value":[1761410000,"38120" -
Check anonymous access is off
curl -s -o /dev/null -w "%{http_code}" localhost:3000/api/dashboards/homeWhat it does: Must be 401 without login.
Output
401
When it is red 1
Prometheus OOMKilled (exit code 137)
Cause. Too many series used all the memory. Usually a new high-cardinality label.
Fix, step by step
- Find the metric with topk(10, count by (name)(...)).
- Drop the label with metric_relabel_configs.
- Add sample_limit to the job and fix the app code.
When it is red 2
Alert flaps every few minutes
Cause. The value moves around the threshold and there is no for: time.
Fix, step by step
- Add for: 10m.
- Use a slightly wider window like [10m].
- Consider a lower resolve level with keep_firing_for: 5m.
When it is red 3
ufw: WARN: Rules updated, but SSH lost after enable
Cause. OpenSSH was not allowed before enabling the firewall.
Fix, step by step
- Use the AWS console Session Manager or serial console to log in.
- Run sudo ufw allow OpenSSH.
- Always allow SSH before ufw enable.
Cleanup
-
Remove bad test rules
rm rules/bad.yml && curl -s -X POST localhost:9090/-/reloadWhat it does: Keeps only the good rules.
Output
(no output) -
Reset firewall on a lab VM
sudo ufw --force resetWhat it does: Removes all lab firewall rules.
Output
Resetting all rules to installed defaults.
Ravindra Bagale's Tip
The tool is rarely wrong — the question is wrong. Alert on what hurts the user, not on CPU alone.
Tool चुकीचा नसतो, सवाल चुकीचा असतो. User ला काय त्रास होतो त्यावर alert लावा, फक्त CPU वर नाही.
Tool गलत नहीं होता, सवाल गलत होता है. User को क्या तकलीफ़ होती है उस पर alert लगाओ, सिर्फ CPU पर नहीं.
Practice tasks
Easy Delete one useless alert
Why: Removing noise is the fastest win.
What to do: Find one alert nobody acted on last month and remove it.
- Check history.
- Delete the rule.
- Tell the team why.
Check: One fewer noisy alert.
Medium Write one SLO
Why: SLOs turn monitoring into a business promise.
What to do: Write "99.5% of orders succeed over 30 days" as a PromQL ratio.
- sum(increase(orders_total{result="ok"}[30d])) / sum(increase(orders_total[30d]))
Check: You get a number like 0.997.
Hard Burn rate alert
Why: Burn rate alerts catch fast and slow budget loss.
What to do: Write a multi-window burn rate alert for the SLO.
- 1h and 5m windows with factor 14.4.
- 6h and 30m windows with factor 6.
Check: promtool test shows it fires on a fast failure.
Easy Say monitoring anti-patterns 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 monitoring anti-patterns 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, list every alert you have (or from this chapter) in a table with three columns: who acts, what they do, and how often it fired last week. Delete or change any alert with no clear action.
Recap
- Alert on symptoms users feel, not every cause.
- Every alert needs a for: time, an owner and a runbook.
- Never use ids or raw URLs as labels.
- Grafana needs login; exporters must be private.
- Watch prometheus_tsdb_head_series weekly.
FAQ
Is CPU monitoring useless then?
No. Keep it on dashboards and as calm capacity warnings, not as 2 a.m. pages.
How many alerts should a team have?
No fixed number. Each one must need action. Many teams have 10 to 30 for a service.
What is keep_firing_for?
A Prometheus setting that keeps an alert firing for a while after it clears, to stop flapping.
Can I put Grafana behind Google login?
Yes, with Grafana OAuth settings for Google, Azure AD or Okta.
How do I find who owns an alert?
Add a team label to every rule and route by it.
Interview questions
-
What are common monitoring anti-patterns?
Alerting on causes, too many alerts, no for: duration, no owner or runbook, high cardinality labels, public dashboards and exporters, relying on averages.
-
What is an SLO and error budget?
An SLO is a reliability target like 99.9%; the error budget is the allowed failure, 0.1%, which you can spend on releases.
-
How do you protect Prometheus from cardinality issues?
Review labels in code, use sample_limit, metric_relabel_configs to drop labels, and monitor head series.
-
What is symptom-based alerting?
Alerting on user-visible problems like error rate and latency instead of internal metrics.
-
How do you secure monitoring endpoints?
Private networks, security groups, firewall rules, TLS and auth for exporters, SSO for Grafana.
Quick quiz
Q1. Which alert is better: CPU above 70% or checkout errors above 2%?
Checkout errors, because users feel it.
Q2. What causes a cardinality explosion?
Labels with many values, like user id or full URL.
Q3. What does sample_limit do?
Fails a scrape that sends too many series, protecting Prometheus.
Q4. Should Grafana allow anonymous access on the internet?
No.
Q5. What fixes flapping?
A for: duration and wider windows.
Did you understand? Let us try it once more.
Revision card
Interview card