Lesson 5: Cloud-Native Observability with Prometheus, PromQL & Grafana
๐ง The Concept (Explain Like Iโm 5)
Imagine a busy hospital intensive care unit:
- The Patient (Your Application): Constantly emits vital signs every millisecond (heartbeats, blood pressure, oxygen saturation).
- The Sensors (Prometheus Exporters & Instrumentations): Attached to the patient, translating vitals into standard numbers and publishing them on a hospital radio channel (
http://pod:8080/metrics). - The Continuous Recorder (Prometheus): A high-speed computer that tunes into every patientโs radio channel once every 15 seconds (The Scrape Loop) and writes the time series into an ultra-fast in-memory database (TSDB - Time Series Database).
- The Bedside Monitor (Grafana): The beautiful digital screen above the bed. It graphs blood pressure trends over the last 24 hours and turns bright red when a dangerous spike occurs.
- The Emergency Pager (Alertmanager): Automatically calls the on-call doctorโs phone (PagerDuty) the moment oxygen drops below 90% for more than 2 minutes.
๐ฌ Under the Hood: The 4 Core Metric Types in Prometheus
Understanding metric types is fundamental to writing correct PromQL queries. Prometheus supports exactly four metric primitives:
| Metric Type | Behavior | Example | The Golden Rule |
|---|---|---|---|
| Counter | A cumulative metric whose value can only increase or reset to zero on restart. | http_requests_total, packet_drop_count |
NEVER query a Counter raw! Always wrap in rate() or increase(). |
| Gauge | A metric that represents a single numerical value that can arbitrarily go up or down. | node_memory_bytes_free, active_user_sessions |
Query directly, or use avg_over_time() to smooth noisy spikes. |
| Histogram | Samples observations (usually request durations or response sizes) and counts them in configurable buckets (le = less than or equal). |
http_request_duration_seconds_bucket |
Used with histogram_quantile() to calculate p50, p95, and p99 percentiles. |
| Summary | Calculates quantiles directly on the client application side. | rpc_duration_seconds |
Avoid in distributed microservices! Summaries cannot be aggregated across multiple pods. |
How Histogram Buckets Actually Work Under the Hood
When you record a request that took 0.045 seconds, the application increments the counters in all matching buckets:
http_request_duration_seconds_bucket{le="0.01"} 124 # Requests <= 10ms
http_request_duration_seconds_bucket{le="0.05"} 842 # Requests <= 50ms (includes the 124)
http_request_duration_seconds_bucket{le="0.10"} 1102 # Requests <= 100ms
http_request_duration_seconds_bucket{le="+Inf"} 1150 # Total requests
http_request_duration_seconds_sum 48.2 # Total sum of all seconds spent
http_request_duration_seconds_count 1150 # Total count of requests
๐บ๏ธ Visual Architecture: The Prometheus Operator Pipeline
In modern Kubernetes, platform teams do not manage Prometheus configuration files by hand. We deploy the Prometheus Operator (kube-prometheus-stack), which introduces declarative Custom Resource Definitions (CRDs):
flowchart LR
subgraph WorkloadNamespace ["Namespace: workloads"]
AppPod1["Pod 1 (:8080/metrics)"]
AppPod2["Pod 2 (:8080/metrics)"]
ServiceMonitor["<b>ServiceMonitor CRD</b><br/>selector: app=payment<br/>endpoints: /metrics :8080"]
end
subgraph MonitoringNamespace ["Namespace: monitoring"]
PromOperator["<b>Prometheus Operator</b><br/>Watches CRDs & generates config"]
Prometheus["<b>Prometheus Server (TSDB)</b><br/>Scrapes endpoints every 15s"]
PromRule["<b>PrometheusRule CRD</b><br/>Alert definitions (p99 > 500ms)"]
Alertmanager["<b>Alertmanager</b><br/>Deduplication, grouping, routing"]
Grafana["<b>Grafana</b><br/>Visual Dashboards"]
end
ServiceMonitor -.->|"Discovered by"| PromOperator
PromRule -.->|"Discovered by"| PromOperator
PromOperator -->|"Reloads config dynamically"| Prometheus
Prometheus -->|"HTTP GET /metrics"| AppPod1
Prometheus -->|"HTTP GET /metrics"| AppPod2
Prometheus -->|"Evaluates alerts every 15s"| Alertmanager
Alertmanager --> PagerDuty["๐จ PagerDuty / Slack Webhook"]
Grafana -->|"PromQL Queries"| Prometheus
๐งฎ PromQL Mastery: The 4 Golden Signals of SRE
Googleโs Site Reliability Engineering (SRE) framework defines the 4 Golden Signals of system health: Latency, Traffic, Errors, and Saturation. Here are the battle-tested enterprise formulas:
1. Latency: The 99th Percentile (p99)
Average latency is a lie. If 99 users experience 10ms and 1 user experiences 10 seconds, the average is 110ms, hiding the fact that 1% of users are experiencing catastrophic delays.
๐ Formula: histogram_quantile(0.99, โ(rate(http_request_duration_seconds_bucket[5m])) by (le, service))
# p99 Latency over 5-minute sliding window across services
histogram_quantile(
0.99,
sum(rate(http_request_duration_seconds_bucket[5m])) by (le, service)
)
[!NOTE] How
rate()Handles Counter Resets If a Pod crashes and restarts, its counter resets from 1,000,000 back to 0.rate()automatically detects the reset and calculates the true rate without generating negative numbers or massive false spikes!
2. Traffic: Requests Per Second (RPS)
# Total HTTP requests per second by service and HTTP method
sum(rate(http_requests_total[2m])) by (service, method)
3. Errors: Error Budget & 5xx Percentage
# HTTP 5xx error percentage relative to total traffic
(
sum(rate(http_requests_total{status=~"5.."}[5m]))
/
sum(rate(http_requests_total[5m]))
) * 100
4. Saturation: Container CPU & Memory Exhaustion
# Container CPU usage as a percentage of its Kubernetes CPU limit
(
sum(rate(container_cpu_usage_seconds_total{container!="POD", container!=""}[5m])) by (pod)
/
sum(kube_pod_container_resource_limits{resource="cpu"}) by (pod)
) * 100
๐ฃ The Silent Killer: High Cardinality & TSDB Destruction
In Prometheus, every unique combination of metric name and key-value label pairs forms an independent Time Series.
๐ Total Time Series = Unique Label_1 ร Unique Label_2 ร Unique Label_3 ร โฆ
The Incident: Accidental Dynamic Label Injection
A junior developer logs API metrics and adds user_id or order_id as a Prometheus label:
# TOXIC METRIC (High Cardinality):
http_requests_total{service="checkout", user_id="usr_8921471", order_id="ord_918247"} 1
- If your application has 1,000,000 active users, this single metric creates 1,000,000 unique time series in memory.
- The Disaster: Prometheus memory consumption explodes exponentially. The Head Block inside the TSDB cannot flush to disk. Prometheus runs out of memory (
OOMKilled) and enters a continuous crash loop. - The Rule of Thumb: Only use bounded, enumerable labels (e.g.
status_code,method,environment,region). Never include UUIDs, emails, timestamps, or IP addresses in Prometheus metric labels!
Real-Time Defense: ServiceMonitor metricRelabelings Filter
If an application inadvertently emits high-cardinality labels, Platform Architects neutralize them at scrape time before they pollute the Prometheus TSDB:
# ServiceMonitor metricRelabelings: Dropping toxic high-cardinality labels at scrape time
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: checkout-service-monitor
namespace: workloads
spec:
endpoints:
- port: metrics
path: /metrics
metricRelabelings:
# Strip unbounded identifiers before storing in TSDB memory
- action: labeldrop
regex: "(user_id|order_id|customer_email|session_id)"
๐ป Production Manifests: ServiceMonitor & Alerting Rules
1. Reusable ServiceMonitor Manifest
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: payment-service-monitor
namespace: monitoring
labels:
# Must match the Prometheus instance's serviceMonitorSelector!
release: prometheus-stack
spec:
selector:
matchLabels:
app: payment-service
namespaceSelector:
matchNames:
- workloads
endpoints:
- port: http-metrics
path: /metrics
interval: 15s
scrapeTimeout: 10s
# Drop unwanted noisy metrics before ingestion
metricRelabelings:
- action: drop
regex: "go_memstats_.*"
sourceLabels: [__name__]
2. Enterprise PrometheusRule (SLO Alerts)
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: payment-service-alerts
namespace: monitoring
labels:
role: alert-rules
release: prometheus-stack
spec:
groups:
- name: payment-service.rules
rules:
# Alert 1: High 5xx Error Rate
- alert: PaymentServiceHighErrorRate
expr: |
(
sum(rate(http_requests_total{service="payment-service", status=~"5.."}[5m]))
/
sum(rate(http_requests_total{service="payment-service"}[5m]))
) * 100 > 1.0
for: 3m
labels:
severity: critical
team: platform-core
annotations:
summary: "Payment Service HTTP 5xx error rate exceeds 1% (current: {{ $value }}%)"
description: "Over 1% of transactions are failing in the workloads namespace. Investigate immediately."
runbook_url: "https://wiki.corp.internal/runbooks/payment-5xx"
# Alert 2: High Latency Breached
- alert: PaymentServiceHighLatency
expr: |
histogram_quantile(
0.99,
sum(rate(http_request_duration_seconds_bucket{service="payment-service"}[5m])) by (le)
) > 0.500
for: 5m
labels:
severity: warning
team: payment-devs
annotations:
summary: "Payment Service p99 latency exceeds 500ms (current: {{ $value }}s)"
๐ ๏ธ Real-World Troubleshooting & Failure Modes
1. โTarget is DOWN in Prometheus Web UIโ
- Symptom: Navigate to
http://prometheus:9090/targets, and the endpoint showsState: DOWNwithconnection refusedorcontext deadline exceeded. - Root Cause 1 - Port Name Mismatch: The
ServiceMonitorspecifiesport: http-metrics, but the KubernetesServiceobject named the portmetricsorweb. They must match exactly. - Root Cause 2 - Network Policy Block: A Cilium or Calico NetworkPolicy is blocking ingress TCP traffic from the
monitoringnamespace to theworkloadsnamespace on the metric port.
2. Prometheus Recovering from OOMKilled Crash Loop
- Symptom: Prometheus pod boots, consumes 16GB of RAM in 30 seconds, and gets killed by the Linux kernel with Exit Code 137 (
OOMKilled). - Emergency Recovery Protocol:
# 1. Temporarily increase memory limit in Prometheus CRD kubectl patch prometheus prometheus-stack-kube-prom -n monitoring \ --type='json' -p='[{"op": "replace", "path": "/spec/resources/limits/memory", "value": "32Gi"}]' # 2. Check TSDB Head cardinality to find the offending metric # Access Prometheus container shell and run tsdb analyze tool promtool tsdb analyze /prometheus/data
๐ Knowledge Check & Real-World Interview Scenarios
A platform engineer writes an alert for high error rate using the following query:
rate(sum(http_requests_total{status="500"}[5m]))
Why is this mathematically and architecturally incorrect in Prometheus, and why must you ALWAYS write sum(rate(...)) instead?
โ Answer & Explanation
The Fatal Flaw: The order of operations in PromQL is critical!
- If you write
sum(...)first, you aggregate all counters across all pods into a single synthetic number before calculating the rate. - When any single pod restarts, its individual counter drops from 500 to 0.
- The outer
rate()sees the aggregated total drop suddenly, but becausesum()erased the identity of the individual time series,rate()cannot detect which pod restarted or how to apply counter-reset compensation. - The Result: The query produces massive false negative drops or wild calculation anomalies.
The Golden Rule: Always apply rate() first to each individual time series to handle counter resets properly, and then apply sum() across the calculated rates:
sum(rate(http_requests_total{status="500"}[5m]))
During a network switch failure in your primary AWS availability zone, 20 different microservices simultaneously lose connection to their database. Without Alertmanager grouping, 20 separate critical alerts trigger, sending 20 separate phone calls to the on-call engineer in 60 seconds (โAlert Fatigueโ).
How do Alertmanagerโs group_by, group_wait, group_interval, and inhibit_rules prevent alert fatigue during mass outages?
โ Answer & Explanation
group_by: ['alertname', 'cluster', 'zone']: Aggregates alerts sharing common labels into a single unified notification payload instead of 20 separate messages.group_wait: 30s: When an initial alert fires, Alertmanager pauses for 30 seconds to collect other related alerts that are about to fire, bundling them into one notification.group_interval: 5m: Rate-limits repeated notifications for the same group to once every 5 minutes.inhibit_rules: If a higher-level alert is already firing (e.g.ClusterNetworkDegradedorNodeDown), Alertmanager automatically mutes and suppresses all downstream application alerts (e.g.PaymentServiceHighErrorRate), immediately pinpointing the root cause without drowning the engineer in noise!