Monitoring & Alerting
Observability

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

1. Instrument Application
The application exposes standard metrics at an HTTP endpoint such as `/metrics`
2. Service Discovery
Prometheus queries Kubernetes APIs or cloud registries to automatically discover running service instances
3. Scrape Interval
Prometheus fetches metric data from target endpoints at regular intervals (such as every 15 seconds)
4. Time Series Storage
Collected metrics are compressed and saved to an optimized time-series database on disk
5. Rule Evaluation
Prometheus continuously evaluates PromQL alerting rules against incoming data points
6. Alertmanager Routing
Alertmanager groups, silences, and routes urgent alerts to on-call tools like PagerDuty or Slack
7. Grafana Dashboards
Engineers inspect live visual dashboards to spot traffic trends, errors, and latency spikes

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

  1. 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`.

  2. Deploy Prometheus with Service Discovery

    Configure Prometheus using Kubernetes ServiceMonitors or scrape configurations to pull metrics automatically every 15 seconds.

  3. Build Clear Grafana Dashboards

    Create dashboards displaying the Four Golden Signals (Latency, Traffic, Errors, Saturation) with percentile views (P95 and P99).

  4. 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.

  5. 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

Production Prometheus Alerting Rules Manifest (YAML & PromQL)yaml
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)."
This manifest defines practical alerting rules using PromQL: `APIHighErrorRate` calculates the error percentage, requires the problem to persist for two minutes (`for: 2m`) to prevent false alarms on single transient glitches, sets a critical severity, and provides a direct link to an incident runbook.

Metrics (Prometheus) vs Logs (Loki / Elasticsearch)

AspectMetrics (Prometheus)Logs (Loki / Elasticsearch)
Data FormatNumerical time-series (timestamps and floating-point values)Structured text or JSON event records
Storage CostVery low; numbers compress efficiently on diskHigher; text logs consume more disk space over time
Primary PurposeReal-time alerting, dashboards, and trend visualizationDetailed root-cause analysis, debugging, and auditing
Query SpeedMilliseconds across millions of recorded pointsFaster on specific time windows; slower on broad full-text searches
GranularityAggregated statistical views (counters and gauges)Detailed individual events with complete stack traces

Designing Actionable Alerts and Preventing Alert Fatigue

Alert fatigue is a common danger for on-call teams: when alerts fire constantly for non-critical warnings, engineers become desensitized and can easily miss real emergencies. Guidelines for actionable alerts: 1. Every Pager Alert Must Be Actionable: If an alert wakes someone up at 3:00 AM, there must be a clear, urgent action that person needs to take. If an issue can safely wait until normal working hours, route it to an email summary or chat channel instead. 2. Include Runbook Links: Every alert definition should link directly to documentation describing how to verify and troubleshoot the problem (`runbook_url`). 3. Alert on Symptoms, Not Underlying Causes: Do not page someone simply because CPU usage reached 90% if users are experiencing zero errors and sub-100ms response times. Page when user experience degrades (such as elevated error rates or unacceptable latency).

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

  1. Write a PromQL expression to calculate the 95th percentile latency of an API over a 10-minute window.
  2. Review an existing set of alerts: Identify any alerts that fire frequently without requiring immediate action, and adjust their thresholds.