DEV Community

Cover image for How to Monitor With Prometheus and Grafana Without Drowning in Dashboards
Mango Developer
Mango Developer

Posted on Originally published at mangodeveloper.com

How to Monitor With Prometheus and Grafana Without Drowning in Dashboards

I've seen a Grafana instance with 412 dashboards. Three of them were useful. The rest were created by someone who left the company two years ago, and they all showed the same data sliced slightly differently. That's the graveyard monitoring tools become when you don't have a strategy. This article is the strategy: which metrics to collect, how to write PromQL that actually answers questions, how to build dashboards that survive more than a sprint, and how to set up alerts that don't cry wolf.

Prometheus and Grafana aren't the only monitoring stack, but they're the one most teams end up with. They're free, they're battle-tested at scale (SoundCloud, DigitalOcean, Uber), and they compose well. The trade-off is operational overhead-you run them, you back them up, you tune their storage. If you want to never think about it, pay Datadog. If you want control and you're willing to learn the model, this is the path.

Why Prometheus Over Datadog, InfluxDB, or New Relic

Let me be honest about what each tool is good at:

Tool Model Cost model Sweet spot Weakness
Prometheus Pull, time-series Free (ops cost) Service metrics, alerting Not for high-cardinality logs/traces; long-term storage is bolt-on
Datadog Agent, push Per-host, per-metric "I want one bill and no ops" Gets expensive fast; vendor lock-in
InfluxDB Push, time-series Free OSS / paid cloud IoT, event data Query language less ergonomic for SRE work
New Relic Agent, push Per-GB ingest APM-first teams Less flexible for custom metrics
VictoriaMetrics Pull, Prometheus-compatible Free OSS / paid Drop-in Prometheus replacement with better storage Smaller community than Prometheus itself
Mimir / Thanos Pull, federated Free OSS Long-term Prometheus storage at scale Complex to operate

I default to Prometheus for new services. When the team has more money than time, I tell them to pay Datadog. When the team is on Kubernetes and wants "Prometheus but easier," I suggest Grafana Cloud's hosted Prometheus (Mimir under the hood). The model is what matters-once you understand the Prometheus pull model and PromQL, every compatible system is the same.

Prerequisites

  • A Linux box or a Kubernetes cluster. We'll use Docker Compose for the demo.
  • Comfort with the command line and YAML.
  • A service you want to monitor. If you don't have one, we'll use a toy FastAPI app.
  • 8GB RAM minimum for a single-node Prometheus + Grafana setup at modest retention.
  • Some understanding of what a time series is: (metric_name, labels) -> [(timestamp, value), ...].

The Mental Model: Pull, Not Push

This is the single most important thing to understand about Prometheus: it pulls. Your services expose metrics on an HTTP endpoint (usually /metrics), and Prometheus scrapes them on a schedule. This is the opposite of StatsD, Datadog agents, and most APM tools, which push.

CodeCopy

Enter fullscreen mode Exit fullscreen mode

+-----------------+ scrape /metrics +------------------+
| prometheus | --------------------------> | your app:8000 |
| (pull, 15s) | <-------------------------- | /metrics |
+-----------------+ text exposition +------------------+
|
| remote_write (optional)
v
+-----------------+ +------------------+
| alertmanager | <--- fire alert rules | grafana |
| (pagerduty, | when conditions met | (dashboards) |
| slack, email) | | queries prom |
+-----------------+ +------------------+
|
v
+-----------------+
| on-call phone | <--- pages you at 3am
+-----------------+

Enter fullscreen mode Exit fullscreen mode

The pull model has consequences:

  • Prometheus needs network access to your services. If your services are behind a private VPC, Prometheus lives in that VPC.
  • A service that's down doesn't push a "down" metric-Prometheus notices it couldn't scrape, and up{job="x"} == 0. This is how service outage detection works.
  • Short-lived jobs (cron, Lambda) don't live long enough to be scraped. Use the Pushgateway for these, with the caveat that you must clean up old metrics.
  • Each scrape has a fixed timestamp. Backfilling is awkward. Plan for forward-only data.

Installation: Docker Compose Stack

Here's a complete dev stack you can docker compose up -d and have a working Prometheus + Grafana + Alertmanager in five minutes:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

docker-compose.yml

version: "3.8"

services:
prometheus:
image: prom/prometheus:v2.55.0
container_name: prometheus
ports: ["9090:9090"]
volumes:

  • ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
  • ./prometheus/rules.yml:/etc/prometheus/rules.yml:ro
  • prometheus_data:/prometheus command:
  • --config.file=/etc/prometheus/prometheus.yml
  • --storage.tsdb.path=/prometheus
  • --storage.tsdb.retention.time=30d
  • --storage.tsdb.retention.size=10GB
  • --web.enable-lifecycle
  • --web.enable-admin-api

alertmanager:
image: prom/alertmanager:v0.27.0
container_name: alertmanager
ports: ["9093:9093"]
volumes:

  • ./alertmanager/config.yml:/etc/alertmanager/config.yml:ro command:
  • --config.file=/etc/alertmanager/config.yml

grafana:
image: grafana/grafana:11.3.0
container_name: grafana
ports: ["3000:3000"]
environment:

  • GF_SECURITY_ADMIN_PASSWORD=admin
  • GF_USERS_ALLOW_SIGN_UP=false volumes:
  • grafana_data:/var/lib/grafana
  • ./grafana/provisioning:/etc/grafana/provisioning:ro

node-exporter:
image: prom/node-exporter:v1.8.2
container_name: node-exporter
ports: ["9100:9100"]
pid: host
volumes:

  • /proc:/host/proc:ro
  • /sys:/host/sys:ro
  • /:/rootfs:ro command:
  • --path.procfs=/host/proc
  • --path.sysfs=/host/sys
  • --path.rootfs=/rootfs

volumes:
prometheus_data:
grafana_data:

Enter fullscreen mode Exit fullscreen mode


plaintext

Prometheus config:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

prometheus/prometheus.yml

global:
scrape_interval: 15s
evaluation_interval: 15s
external_labels:
cluster: dev
region: local

alerting:
alertmanagers:

  • static_configs:
  • targets: ["alertmanager:9093"]

rule_files:

  • /etc/prometheus/rules.yml

scrape_configs:

  • job_name: prometheus static_configs:
  • targets: ["localhost:9090"]

  • job_name: node
    static_configs:

  • targets: ["node-exporter:9100"]

  • job_name: api
    metrics_path: /metrics
    static_configs:

  • targets: ["host.docker.internal:8000"]
    labels:
    service: api
    env: dev

Enter fullscreen mode Exit fullscreen mode


markdown

This gives you:

The Four Golden Signals (and RED, USE)

Before instrumenting, know what to instrument. Google's SRE book defines four golden signals: latency, traffic, errors, saturation. For request-driven services, the RED method (Rate, Errors, Duration) is a tighter subset. For resources (CPU, disk, network), USE (Utilization, Saturation, Errors).

Signal What Example metric Question it answers
Latency How long requests take http_request_duration_seconds Are we slow?
Traffic How much demand http_requests_total Are we busy?
Errors How often we fail http_requests_total{status=~"5.."} Are we broken?
Saturation How full is the system process_cpu_seconds_total, node_filesystem_avail_bytes Are we about to break?

Every service you run should expose all four. Every dashboard should have all four on the first row. Every alert should be tied to one of these violating a threshold.

Instrumenting a Python Service

Use the official prometheus_client library. Here's a FastAPI app with the four golden signals properly instrumented:

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

app.py

import time
from collections import Counter
from fastapi import FastAPI, Request, Response
from prometheus_client import (
Counter, Histogram, Gauge, generate_latest, CONTENT_TYPE_LATEST,
)

app = FastAPI()

--- Metrics ---

Note: label cardinality matters. status and method are fine (low cardinality).

path is dangerous - if path includes IDs, you explode the series count.

REQUESTS = Counter(
"http_requests_total",
"Total HTTP requests",
["method", "status", "endpoint"],
)

REQUEST_LATENCY = Histogram(
"http_request_duration_seconds",
"HTTP request latency",
["method", "endpoint"],
buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0),
)

INFLIGHT = Gauge(
"http_requests_inflight",
"Currently in-flight HTTP requests",
)

ERRORS = Counter(
"http_errors_total",
"Total HTTP 5xx errors",
["endpoint"],
)

@app.middleware("http")
async def prometheus_middleware(request: Request, call_next):
INFLIGHT.inc()
start = time.perf_counter()
try:
response = await call_next(request)
except Exception:
REQUESTS.labels(
method=request.method,
status="500",
endpoint=request.url.path,
).inc()
ERRORS.labels(endpoint=request.url.path).inc()
raise
finally:
INFLIGHT.dec()
duration = time.perf_counter() - start
REQUEST_LATENCY.labels(
method=request.method,
endpoint=request.url.path,
).observe(duration)
REQUESTS.labels(
method=request.method,
status=str(response.status_code),
endpoint=request.url.path,
).inc()
return response

@app.get("/healthz")
def healthz():
return {"status": "ok"}

@app.get("/api/users/{user_id}")
def get_user(user_id: int):
return {"id": user_id, "name": "demo"}

@app.get("/metrics")
def metrics():
return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)

Enter fullscreen mode Exit fullscreen mode


markdown

Critical decisions in this code:

  • Histogram, not Summary. Histograms can be aggregated across instances (Prometheus computes quantiles server-side via histogram_quantile). Summaries cannot. Always use Histogram for latency.
  • Buckets matter. Default buckets are tuned for ~1s latencies. For a fast API, you want finer buckets at the low end (5ms, 10ms, 25ms). For a slow batch job, you want bigger buckets.
  • endpoint not path. I use request.url.path which includes the ID. This is wrong if you have /api/users/123 and /api/users/456-each becomes a separate series. Use a route template like /api/users/{user_id} instead. FastAPI gives you this via request.scope["route"].path_format.
  • No high-cardinality labels. Never label with user_id, session_id, request_id. Each unique label value = one new time series. 100k users × 5 metrics = 500k series. Prometheus will OOM.

The cardinality rule is the most important one in Prometheus. Read it twice.

PromQL: The Queries You'll Actually Use

PromQL has a learning curve. Here are the queries I use weekly:

promqlCopy

Enter fullscreen mode Exit fullscreen mode


prometheus

Request rate (per second) over last 5 min, by endpoint

sum(rate(http_requests_total[5m])) by (endpoint)

Error rate as percentage

sum(rate(http_requests_total{status=~"5.."}[5m]))
/
sum(rate(http_requests_total[5m]))

  • 100

p99 latency (server-side quantile from histogram)

histogram_quantile(0.99,
sum(rate(http_request_duration_seconds_bucket[5m])) by (le, endpoint)
)

CPU usage per pod (from cAdvisor)

sum(rate(container_cpu_usage_seconds_total[5m])) by (pod)

Memory usage % for a node

(node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes)
/ node_memory_MemTotal_bytes * 100

Saturation: requests queueing (inflight)

http_requests_inflight

Top 5 endpoints by request rate

topk(5, sum(rate(http_requests_total[5m])) by (endpoint))

Saturation prediction: disk full in N hours

predict_linear(node_filesystem_avail_bytes[1h], 24 * 3600) < 0

Enter fullscreen mode Exit fullscreen mode


markdown

The mental model: every metric is a vector (set of time series with labels). Operations like sum, rate, histogram_quantile transform vectors. by (...) groups; without (...) is the inverse. The [5m] is a range vector-values over the last 5 minutes. rate() computes per-second rate over that range.

The two most common PromQL mistakes:

  1. Forgetting rate() on counters. Counters go up forever. Plotting http_requests_total directly gives a meaningless line going up. Always rate(counter[window]).
  2. Not aggregating before histogram_quantile. You have to sum(rate(bucket)) by (le) first, then wrap in histogram_quantile. Otherwise you get per-instance quantiles, which is rarely what you want.

Recording Rules: Pre-compute Expensive Queries

Some PromQL is expensive to evaluate at query time-especially anything with histogram_quantile over a long range. Pre-compute it with recording rules:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

prometheus/rules.yml

groups:

  • name: api.rules interval: 30s rules:
  • record: api:request_rate:5m
    expr: sum(rate(http_requests_total[5m]))

  • record: api:error_rate:5m
    expr: |
    sum(rate(http_requests_total{status=~"5.."}[5m]))
    /
    sum(rate(http_requests_total[5m]))

  • record: api:request_latency_p99:5m
    expr: |
    histogram_quantile(0.99,
    sum(rate(http_request_duration_seconds_bucket[5m])) by (le, endpoint))

  • record: api:request_latency_p99:5m_global
    expr: |
    histogram_quantile(0.99,
    sum(rate(http_request_duration_seconds_bucket[5m])) by (le))

Enter fullscreen mode Exit fullscreen mode


markdown

Now api:request_latency_p99:5m_global is a cheap query-it returns a precomputed series. Dashboards that use recording rules load instantly. Dashboards that compute histogram_quantile over 30 days of data take 30 seconds and may OOM Prometheus under concurrent load.

Naming convention I use: <job>:<metric>:<aggregation>[:<scope>]:<window>. Colons are conventional in Prometheus rule names. Reads well.

Alerting Rules: Don't Page Me for Nothing

Bad alerts destroy on-call morale. Every alert should be actionable (a human can do something about it), urgent (it can't wait until morning), and real (not a flapping symptom of something else).

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

prometheus/rules.yml (continued)

  • name: api.alerts rules:
  • alert: HighErrorRate
    expr: |
    (
    sum(rate(http_requests_total{status=~"5.."}[5m]))
    /
    sum(rate(http_requests_total[5m]))
    ) > 0.05
    for: 5m
    labels:
    severity: page
    service: api
    annotations:
    summary: "API error rate above 5%"
    description: "Error rate is {{ $value | humanizePercentage }} for the last 5 minutes."

  • alert: HighLatencyP99
    expr: api:request_latency_p99:5m_global > 1
    for: 10m
    labels:
    severity: ticket
    service: api
    annotations:
    summary: "API p99 latency above 1s"
    description: "p99 is {{ $value }}s. SLO is 1s."

  • alert: ServiceDown
    expr: up{job="api"} == 0
    for: 2m
    labels:
    severity: page
    annotations:
    summary: "API service is down"
    description: "{{ $labels.instance }} has been down for 2 minutes."

  • alert: DiskWillFillIn24h
    expr: predict_linear(node_filesystem_avail_bytes[1h], 24 * 3600) < 0
    for: 1h
    labels:
    severity: ticket
    annotations:
    summary: "Disk {{ $labels.device }} on {{ $labels.instance }} will fill in 24h"

  • alert: PrometheusTSDBCardinalityTooHigh
    expr: prometheus_tsdb_symbol_table_size > 100000000
    for: 10m
    labels:
    severity: ticket
    annotations:
    summary: "Prometheus symbol table over 100MB - likely cardinality explosion"

Enter fullscreen mode Exit fullscreen mode


markdown

Key principles:

  • for: 5m waits 5 minutes before firing. This kills flapping alerts. Without it, a 30-second blip pages you.
  • Two severities: page and ticket. Page = wake someone up. Ticket = look at it tomorrow. If you have only one severity, you have no severity.
  • Never alert on absolute values. "CPU > 80%" is meaningless on a 4-core box doing batch work and on a 64-core box doing interactive work. Alert on latency, error rate, saturation that's user-visible.
  • Use SLO-based alerts when possible. "Error budget burn rate is 14x" is a better alert than "error rate is 5%." It tells you that you're burning your monthly error budget in 2 hours and you'll miss your SLO.

Alertmanager: Routing, Inhibition, Silences

Alertmanager receives alerts from Prometheus and routes them to receivers (PagerDuty, Slack, email). It also handles deduplication, grouping, and silences.

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

alertmanager/config.yml

route:
receiver: default
group_by: ["alertname", "service", "severity"]
group_wait: 30s
group_interval: 5m
repeat_interval: 4h

routes:

  • matchers:
  • severity = page
    receiver: pagerduty
    continue: false

  • matchers:

  • severity = ticket
    receiver: slack
    continue: false

receivers:

  • name: default slack_configs:
  • api_url: $SLACK_WEBHOOK
    channel: "#alerts"

  • name: pagerduty
    pagerduty_configs:

  • service_key: $PAGERDUTY_KEY
    severity: critical

  • name: slack
    slack_configs:

  • api_url: $SLACK_WEBHOOK
    channel: "#alerts"
    send_resolved: true

inhibit_rules:

  • source_matchers: [alertname = "ServiceDown"] target_matchers: [alertname = "HighErrorRate"] equal: ["service"]
Enter fullscreen mode Exit fullscreen mode


markdown

Key points:

  • group_by merges similar alerts into one notification. Don't put high-cardinality labels here.
  • repeat_interval is how often the same firing alert re-notifies. 4h is a reasonable default; shorter and you'll hate your life.
  • inhibit_rules are crucial. If a service is down, you don't need 50 alerts about its error rate, latency, and queue depth. Inhibit them.
  • Silences are for planned maintenance. Schedule them in advance via the Alertmanager UI or API.

The --web.enable-lifecycle flag on Prometheus enables the POST /-/reload endpoint, which lets you reload rules without restarting Prometheus. Combine with a config-reload sidecar (e.g., prometheus-config-reloader) for automatic rule updates.

Grafana: Datasources, Dashboards, Provisioning

Add Prometheus as a datasource in Grafana. Use provisioning so it's version-controlled:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

grafana/provisioning/datasources/prometheus.yml

apiVersion: 1
datasources:

  • name: Prometheus type: prometheus access: proxy url: http://prometheus:9090 isDefault: true editable: false jsonData: timeInterval: "15s" httpMethod: POST
Enter fullscreen mode Exit fullscreen mode


plaintext

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

grafana/provisioning/dashboards/api.yml

apiVersion: 1
providers:

  • name: api-dashboards orgId: 1 folder: API type: file disableDeletion: false updateIntervalSeconds: 30 options: path: /var/lib/grafana/dashboards/api
Enter fullscreen mode Exit fullscreen mode


plaintext

A useful dashboard template (golden signals layout). Save as JSON in /var/lib/grafana/dashboards/api/overview.json:

JSONCopy

Enter fullscreen mode Exit fullscreen mode


json
{
"title": "API Overview",
"schemaVersion": 39,
"panels": [
{
"type": "stat", "title": "Requests/s",
"gridPos": {"h": 4, "w": 6, "x": 0, "y": 0},
"targets": [{"expr": "sum(rate(http_requests_total[5m]))", "refId": "A"}]
},
{
"type": "stat", "title": "Error rate",
"gridPos": {"h": 4, "w": 6, "x": 6, "y": 0},
"targets": [{"expr": "sum(rate(http_requests_total{status=~\"5..\"}[5m])) / sum(rate(http_requests_total[5m])) * 100", "refId": "A"}]
},
{
"type": "stat", "title": "p99 latency",
"gridPos": {"h": 4, "w": 6, "x": 12, "y": 0},
"targets": [{"expr": "histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))", "refId": "A"}]
},
{
"type": "stat", "title": "In-flight",
"gridPos": {"h": 4, "w": 6, "x": 18, "y": 0},
"targets": [{"expr": "sum(http_requests_inflight)", "refId": "A"}]
},
{
"type": "timeseries", "title": "Latency p50/p95/p99",
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 4},
"targets": [
{"expr": "histogram_quantile(0.50, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))", "legend": "p50", "refId": "A"},
{"expr": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))", "legend": "p95", "refId": "B"},
{"expr": "histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))", "legend": "p99", "refId": "C"}
]
}
]
}

Enter fullscreen mode Exit fullscreen mode


markdown

The rules I enforce on dashboards:

  1. First row is the four golden signals as stat panels. Anyone looking at the dashboard sees the SRE health in 2 seconds.
  2. Second row is a time series of latency percentiles (p50, p95, p99). One panel, three lines.
  3. Third row is error rate over time, with status code breakdown.
  4. Fourth row is saturation: CPU, memory, connections.
  5. No more than 12 panels per dashboard. If you need more, split into multiple dashboards. Cognitive load matters.
  6. Use recording rules in dashboard queries. A dashboard that runs histogram_quantile over 7 days for 8 panels will load slowly and stress Prometheus.
  7. Use template variables for service, env, instance. Let users filter.
  8. Set refresh to 30s, not 5s. 5s burns Prometheus CPU for no perceptible benefit.

Exporters: Beyond Your Own Code

Most of what you monitor isn't your code-it's MySQL, Postgres, Redis, Nginx, Kafka, Kubernetes. Each has an exporter that exposes metrics in Prometheus format.

Exporter What it gives you Don't miss
node-exporter Host CPU/mem/disk/net node_filesystem_avail_bytes, node_cpu_seconds_total
mysqld-exporter MySQL internals mysql_global_status_Threads_running, InnoDB row operations
postgres-exporter Postgres internals pg_stat_activity_count, pg_locks_count
redis-exporter Redis internals redis_connected_clients, redis_memory_used_bytes
nginx-exporter Nginx stub status nginx_connections_active, upstream response times (needs custom log format)
blackbox-exporter External probes (HTTP, ICMP, TCP) Synthetic checks from outside
kube-state-metrics Kubernetes object state Pod phases, deployment replicas
cAdvisor Container metrics container_cpu_usage_seconds_total, container_memory_working_set_bytes

The blackbox-exporter is special-it's the only one that lets you check things Prometheus can't reach directly. Use it for synthetic checks: "is my public HTTPS endpoint up from outside the VPC?" Configure a job that probes https://api.example.com/healthz from the blackbox exporter every 30s. Alert if it fails.

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml
scrape_configs:

  • job_name: blackbox_http metrics_path: /probe params: module: [http_2xx] static_configs:
  • targets:
  • https://api.example.com/healthz
  • https://www.example.com relabel_configs:
  • source_labels: [address] target_label: __param_target
  • source_labels: [__param_target] target_label: instance
  • target_label: address replacement: blackbox-exporter:9115
Enter fullscreen mode Exit fullscreen mode


markdown

Pushgateway: For Cron and Batch Jobs

The pull model breaks for short-lived jobs. A cron job that runs for 5 seconds never gets scraped. Use the Pushgateway: your job pushes metrics on completion, Prometheus scrapes the Pushgateway, and you set a TTL on the pushed metrics.

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

registry = CollectorRegistry()
last_run = Gauge(
"batch_job_last_run_timestamp_seconds",
"Unix timestamp of last successful run",
registry=registry,
)
records = Gauge(
"batch_job_records_processed_total",
"Records processed in last run",
registry=registry,
)

... do the work ...

last_run.set_to_current_time()
records.set(12345)

push_to_gateway(
"pushgateway:9091",
job="nightly_etl",
registry=registry,
)

Enter fullscreen mode Exit fullscreen mode


plaintext

Configure Prometheus to scrape the Pushgateway:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml
scrape_configs:

  • job_name: pushgateway honor_labels: true static_configs:
  • targets: ["pushgateway:9091"]
Enter fullscreen mode Exit fullscreen mode


markdown

Critical: set honor_labels: true so the job label from the pushed metric isn't overwritten by the scrape job label. Otherwise every pushed metric gets relabeled as pushgateway, and you lose which job it came from.

The Pushgateway is not a replacement for StatsD-style push. It's specifically for batch job results. Don't push application metrics through it-use the pull model with /metrics.

Production Considerations

Scaling

Single Prometheus handles ~1M active time series comfortably on a modern box with 16GB RAM. Past that, you have three options:

  1. Shard by job. Run multiple Prometheus instances, each scraping a subset of services. Use Grafana's datasource per panel or set up federation.
  2. Federation. One "global" Prometheus scrapes aggregates from per-cluster Prometheis. Cheap to set up; doesn't scale to billions of series.
  3. Long-term storage (Thanos/Mimir/Cortex). These add S3-compatible object storage and a query layer. This is how you go multi-cluster, multi-region, multi-year retention. Operations cost goes up significantly.

Performance

  • Cardinality is everything. Run prometheus_tsdb_symbol_table_size and topk(10, prometheus_tsdb_series) regularly. If series count grows without bound, you have a label leak.
  • Reduce scrape interval carefully. 15s is standard. 60s halves storage. 5s doubles it and stresses PromQL rate() math. Don't go below 15s unless you have a real reason.
  • TSDB retention. --storage.tsdb.retention.time=30d and --storage.tsdb.retention.size=10GB. The size limit is a hard ceiling-Prometheus will delete old data to stay under it. Set both; whichever hits first wins.

Caching

Prometheus doesn't cache query results. Grafana does (per-user, per-panel, configurable). For dashboards that lots of people stare at, enable Grafana's query cache.

Security

  • Enable basic auth on Prometheus. By default it's wide open. Anyone who can reach it can run expensive queries.
  • Use TLS. Even on internal networks. Cert-manager + a self-signed CA works fine.
  • Restrict admin API. --web.enable-admin-api exposes endpoints like /-/reload and the snapshot API. Don't expose it publicly.

Monitoring

Prometheus should monitor itself. The prometheus job in our config does this. Watch:

  • prometheus_tsdb_head_series - series count in the head block. Growing trend = cardinality leak.
  • prometheus_tsdb_head_samples_appended_total - samples ingested per second.
  • prometheus_rule_evaluation_duration_seconds - how long rules take to evaluate. Spikes = slow PromQL.
  • prometheus_target_scrape_pool_targets - number of targets per scrape job. Drops = endpoints down.

Logging

Prometheus logs to stdout. Use structured logging (--log.format=json) and ship to your log aggregator. The interesting events: rule evaluation failures, scrape failures, WAL replays.

Deployment

  • Run Prometheus as a StatefulSet on Kubernetes, with a PVC for /prometheus.
  • Use the prometheus-operator (kube-prometheus-stack Helm chart) for a batteries-included setup. It handles config reloading, rule management, and Alertmanager integration.
  • For multi-cluster, consider Grafana Cloud's hosted Mimir instead of running your own Thanos.

Common Mistakes

Mistake 1: Labeling with user IDs. Each unique user_id creates a new time series. 100k users × 5 metrics = 500k series. Prometheus OOMs. Detect with topk(20, count by (__name__)({__name__=~".+"})) - if any single metric has >10k series, you have a cardinality leak.

Mistake 2: Using Summary instead of Histogram. Summaries pre-compute quantiles client-side. You can't aggregate them. Always use Histogram; compute quantiles server-side with histogram_quantile.

Mistake 3: Default buckets on Histograms. Default buckets are 0.005s to 10s, which is fine for HTTP APIs. For a database with sub-ms latency, you're missing resolution at the low end. For a batch job that takes minutes, you're wasting buckets at the high end. Define explicit buckets.

Mistake 4: Alerting on raw counter values. http_requests_total > 1000 is meaningless-it's almost always > 1000 after the first hour. Alert on rate() or increase().

Mistake 5: Page-level alerts without for:. A 5-second blip pages you. Always use for: 5m or longer for page severity.

Mistake 6: One Prometheus for everything. Mix prod + staging + dev in one Prometheus. Now an outage in dev makes prod dashboards slow. Shard by environment at minimum.

Mistake 7: Not running Alertmanager. Alerts go nowhere. Always wire up Alertmanager, even if it's just to Slack for the first month.

Mistake 8: Grafana as the only alert sink. Grafana has its own alerting, but it duplicates Prometheus alerting. Pick one (Prometheus + Alertmanager is the better choice) and disable the other. Otherwise alerts fire from both and on-call gets two pages for the same issue.

Troubleshooting Real Production Issues

Symptom: Prometheus is OOMing.
Cardinality explosion. Check prometheus_tsdb_head_series. Run:

promqlCopy

Enter fullscreen mode Exit fullscreen mode


prometheus
topk(20, count by (name)({name=~".+"}))

Enter fullscreen mode Exit fullscreen mode

The metric with the most series is your culprit. Almost always it's a label with high cardinality (user_id, request_id, error_message). Fix the instrumentation; restart Prometheus.

Symptom: Dashboards load slowly.
You're computing expensive queries at view time. Convert them to recording rules. Also check if multiple users are running the same expensive query-Grafana's query cache helps here.

Symptom: An alert didn't fire when it should have.
Check the alert's for: clause. Check if Alertmanager received it (look at its UI). Check if it was inhibited by another alert. Check the route matchers.

Symptom: Alert fires every 5 minutes then resolves.
Flapping. The threshold is right at the edge of normal. Either widen for:, or use a different signal that doesn't flap. Common with disk space alerts when there's a logging process that writes and cleans up.

Symptom: rate() returns no data.
Counter hasn't been observed in the window. Either the service is down (check up{job="..."}) or the counter doesn't exist (check http_requests_total directly).

Symptom: histogram_quantile returns NaN.
The le label is missing or the buckets aren't cumulative. Histograms require cumulative buckets (+Inf is the last). If you defined custom buckets, ensure +Inf is included (prometheus_client does this automatically).

Symptom: Prometheus disk fills up.
Lower retention. Or you have a cardinality leak (samples per second went through the roof). Check prometheus_tsdb_head_samples_appended_total rate.

Symptom: Scrape target shows as down.
Check up{job="..."}. If 0, either the target is unreachable, the /metrics endpoint isn't there, or it's returning non-200. Look at Prometheus's target page (http://prometheus:9090/targets) for the error message.

Cost Considerations, Alternatives, Comparison

Running your own Prometheus is free in license, expensive in ops time. Rough cost breakdown for a team of 10:

Approach Setup cost Monthly ops cost Storage cost Sweet spot
Self-hosted Prometheus + Grafana 2-4 weeks $500-2k equiv Varies (10GB-1TB) Teams with strong SRE
Grafana Cloud (hosted Prometheus) 1 day $0-500+ depending on series Included Small/mid teams wanting zero ops
Datadog 1 day $15-50/host + custom metrics Included "Just pay and forget" teams
VictoriaMetrics (self-hosted) 2-4 weeks $300-1k equiv Lower than Prometheus High-volume teams
New Relic 1 day Per-GB ingest Included APM-first teams

The break-even for self-hosting vs Grafana Cloud is usually around 100GB/month of metrics ingest. Below that, hosted is cheaper in total cost. Above that, self-hosting saves money but costs time.

For long-term storage at scale, Thanos or Mimir with S3 backing is the standard. Mimir is the newer, horizontally scalable option; Thanos is older but battle-tested. Both work; pick based on team familiarity.

Real-World Use Cases

E-commerce checkout SLOs. Track 99% checkout latency under 2s. Alert when error budget burn rate exceeds 14x (i.e., you're spending 2 weeks of error budget per day). Two Prometheus instances (prod + staging), one Grafana, alerts to PagerDuty.

Multi-cluster Kubernetes. One Prometheus per cluster, scraping kubelet/cAdvisor/kube-state-metrics. Thanos Receive aggregates to a global view. Grafana queries Thanos for cross-cluster dashboards. 3-year retention.

API gateway observability. Nginx in front of microservices. Nginx-exporter + per-service Prometheus clients. Per-tenant dashboards via Grafana templating. Blackbox exporter for synthetic checks from external PoPs.

Database capacity planning. Postgres-exporter feeding 1 year of metrics. Use predict_linear on pg_database_size_bytes to forecast when you'll hit disk limits. Alerts on pg_locks_count and pg_stat_activity_count.

Background job monitoring. Pushgateway receiving metrics from cron jobs and Airflow DAGs. Alert if batch_job_last_run_timestamp_seconds is more than 26 hours old. Dashboard shows last-run status for all jobs.

Conclusion

Prometheus and Grafana are the monitoring stack most teams standardize on for a reason: the model is right. Pull-based, time-series, label-driven, with a query language that lets you express the actual questions you have. The trick is not over-engineering it. Start with the four golden signals, build one dashboard per service, set up three or four real alerts, and resist the urge to instrument everything.

The discipline pays off. After six months of running this stack well, you'll catch problems before users do. After a year, you'll have SLOs that the business trusts and dashboards that are actually useful. The graveyard of unused dashboards is avoidable, but only if you treat monitoring as engineering, not as a side task.


Originally published on Mango Developer.

Top comments (0)