Monitoring & Alerting
A complete guide to Monitoring and Observability: metrics, Prometheus, Grafana, the RED/USE methods, four golden signals, and alert fatigue.
Imagine driving a car down a dark highway with a completely blacked-out dashboard. Without a speedometer, fuel gauge, or engine warning lights, you have no idea how fast you are traveling or whether your engine is overheating until the vehicle suddenly stalls on the road. In traditional IT setups, teams often operated in a similar blind spot. They frequently discovered their systems were down only when frustrated customers reported that the website was returning errors. Operations engineers then had to SSH into individual servers, run commands like `top` and `df -h`, and comb through raw text logs to guess what broke. Modern distributed software architectures consist of dozens or hundreds of microservices, background queues, and container clusters communicating across networks. Monitoring and Observability act as the instrument panel for this infrastructure, giving engineers real-time telemetry, clear health indicators, and proactive alerts before end users experience disruptions.
Definition
Monitoring is the automated collection, aggregation, and analysis of system metrics to verify whether systems are running as expected. Observability is a broader capability that measures how easily you can understand the internal state of a system based entirely on its external outputs: metrics, logs, and distributed traces.
Why It Matters
You cannot improve or fix what you cannot measure. In a distributed microservice setup, failures are rarely simple on-or-off events. Instead, one database query in one service might slow down from 50 milliseconds to 4,000 milliseconds, causing request queues to back up and trigger cascading timeouts across several other services. Monitoring and observability dramatically reduce Mean Time to Detect (MTTD) and Mean Time to Resolve (MTTR). They help teams spot performance slowdowns early, understand real user traffic patterns, plan server capacity, and measure reliability against Service Level Objectives (SLOs).
How It Works
Observability relies on core telemetry data types and structured analysis frameworks: 1. The Three Pillars of Observability: • Metrics: Numerical time-series data recorded at regular intervals (such as CPU utilization, request count, or memory usage). Metrics are lightweight, cheap to store, and ideal for real-time dashboards and threshold alerts. • Logs: Timestamped text records of discrete events that occurred inside an application. Logs provide rich context and are essential for detailed root-cause investigation. • Traces: Records that follow a single user request from start to finish as it travels through multiple microservices, background jobs, and databases (distributed tracing). 2. Telemetry Frameworks: • The RED Method (for Request-Driven Services and APIs): - Rate: The number of requests your service handles per second. - Errors: The number of failed requests per second (such as HTTP 5xx responses). - Duration: The time taken to process requests, usually tracked as latency percentiles. • The USE Method (for Infrastructure and Hardware Resources): - Utilization: The percentage of time a resource is busy (for example, CPU at 75%). - Saturation: The amount of extra work queued waiting for the resource (such as CPU run queue depth or disk wait queues). - Errors: The count of error events (such as dropped network packets or disk read errors). • The Four Golden Signals (from Google Site Reliability Engineering): Latency, Traffic, Errors, and Saturation. 3. Metric Types (Prometheus Model): • Counter: A value that only increases over time (such as `http_requests_total`). It resets to zero when a service restarts. • Gauge: A numerical value that can go up and down freely (such as memory usage or current temperature). • Histogram: Samples values (usually request durations or response sizes) and counts them in configured buckets to calculate percentiles (such as P50, P95, or P99). • Summary: Similar to histograms, calculating streaming quantiles on the client side. 4. Pull vs. Push Models: • Pull Model (Prometheus): The monitoring server scrapes metrics by making periodic HTTP requests to target endpoints (such as `/metrics`). This makes health checks and service discovery straightforward. • Push Model (StatsD, CloudWatch): Applications actively push metric packets over the network to a central collector, which is especially useful for short-lived serverless tasks like AWS Lambda functions.
Prometheus & Grafana Observability Architecture
Key Points
- Monitoring informs you when something is failing; Observability helps you discover WHY it failed.
- Use the RED method for services and APIs (Rate, Errors, Duration) and the USE method for hardware resources (Utilization, Saturation, Errors).
- Always evaluate latency percentiles (P95, P99) rather than averages, because an average can easily hide severe delays for a minority of users.
- Alert on symptoms that directly harm users (such as errors or timeouts) rather than non-critical causes (such as CPU reaching 80%).
- Prevent alert fatigue: if an alert does not require immediate human action, it belongs on a dashboard or ticket, not a middle-of-the-night phone page.
Steps
Instrument Applications with Standard Metrics
Add a standard Prometheus client library (such as `prom-client` in Node.js or `prometheus-client` in Python) to expose RED metrics on `/metrics`.
Deploy Prometheus with Service Discovery
Configure Prometheus using Kubernetes ServiceMonitors or scrape configurations to pull metrics automatically every 15 seconds.
Build Clear Grafana Dashboards
Create dashboards displaying the Four Golden Signals (Latency, Traffic, Errors, Saturation) with percentile views (P95 and P99).
Define Symptom-Based Alerting Rules
Write PromQL alerts that focus on real user impact (elevated 5xx error rates or high response latency) rather than internal causes like CPU spikes.
Configure Alert Routing & On-Call Schedules
Connect Alertmanager to on-call channels, ensuring critical issues notify the on-call engineer while informational warnings go to chat rooms.
Examples
The Hospital Cardiac Monitor Analogy
In an intensive care room, a heart monitor does not chime loudly for every single normal heartbeat. It alarms only when the patient's heart rate drops dangerously low or spikes too high. If the monitor sounded an alarm every five seconds for minor, harmless changes, the nurses would eventually turn down the volume (alert fatigue), risking missing a genuine emergency.
Real-World Examples
Preventing Traffic Spikes from Crashing APIs
During major product launches or holiday sales, e-commerce applications experience massive spikes in user traffic. By tracking RED metrics (incoming request rates and P99 response times) in Prometheus, automated scaling rules trigger new container replicas before connection queues fill up, avoiding site outages.
Technical Examples
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: api-service-alerts
namespace: production
labels:
role: alert-rules
spec:
groups:
- name: api.rules
rules:
# ── 1. SYMPTOM ALERT: High 5xx HTTP Error Rate ───────────────
- alert: APIHighErrorRate
# Calculate percentage of 5xx errors over 5-minute rolling window
expr: |
(
sum(rate(http_requests_total{status=~"5.."}[5m]))
/
sum(rate(http_requests_total[5m]))
) * 100 > 1.0
for: 2m # Condition must persist for 2 minutes to filter brief transient blips
labels:
severity: critical
tier: api
annotations:
summary: "High API Error Rate on {{ $labels.service }}"
description: "API 5xx error rate is currently {{ $value | printf '%.2f' }}% (threshold: 1.0%)."
runbook_url: "https://wiki.internal.example.com/runbooks/api-5xx-errors"
# ── 2. SYMPTOM ALERT: High P99 Latency (Degraded Experience) ─
- alert: APIHighP99Latency
# P99 latency across all requests exceeds 2.0 seconds
expr: |
histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le)) > 2.0
for: 3m
labels:
severity: warning
annotations:
summary: "Elevated P99 latency on {{ $labels.service }}"
description: "99% of requests take longer than {{ $value | printf '%.2f' }}s (threshold: 2.0s)."Metrics (Prometheus) vs Logs (Loki / Elasticsearch)
| Aspect | Metrics (Prometheus) | Logs (Loki / Elasticsearch) |
|---|---|---|
| Data Format | Numerical time-series (timestamps and floating-point values) | Structured text or JSON event records |
| Storage Cost | Very low; numbers compress efficiently on disk | Higher; text logs consume more disk space over time |
| Primary Purpose | Real-time alerting, dashboards, and trend visualization | Detailed root-cause analysis, debugging, and auditing |
| Query Speed | Milliseconds across millions of recorded points | Faster on specific time windows; slower on broad full-text searches |
| Granularity | Aggregated statistical views (counters and gauges) | Detailed individual events with complete stack traces |
Designing Actionable Alerts and Preventing Alert Fatigue
Advantages
- Proactive Problem Detection: Catch software errors and latency spikes before customers report them.
- Data-Driven Capacity Planning: Use historical metrics to predict when servers or databases need scaling.
- Objective Reliability Tracking: Measure system uptime and performance against Service Level Agreements (SLAs).
Limitations
- Storage and Network Costs: Retaining large volumes of granular metrics can become costly without proper retention policies.
- High Cardinality Trap: Using unique values (like user IDs or email addresses) as metric labels in Prometheus can drastically increase memory consumption.
Interview Questions
Explain the difference between the USE Method and the RED Method in observability.
The USE Method (Utilization, Saturation, Errors) is designed for hardware and resource components like CPUs, memory, disks, and network interfaces. Utilization measures how busy a resource is; Saturation measures queued work waiting for that resource; Errors measures hardware or driver faults. The RED Method (Rate, Errors, Duration) is designed for request-driven services and APIs. Rate measures incoming requests per second; Errors measures failed requests; Duration measures how long requests take to complete (latency percentiles). Engineering teams typically use RED for application layers and USE for underlying infrastructure.
Practice Questions
- Write a PromQL expression to calculate the 95th percentile latency of an API over a 10-minute window.
- Review an existing set of alerts: Identify any alerts that fire frequently without requiring immediate action, and adjust their thresholds.
