Metrics, Monitoring, and Alerting: From SLIs to Alerts

Learn the RED and USE methods, SLIs/SLOs/SLAs, and how to build alerting systems that catch real problems. Includes examples for web services and databases.

published: reading time: 52 min read author: Geek Workbench updated: June 17, 2026
Quick Summary

This guide defines service-level indicators and objectives, distinguishes internal targets from customer SLAs and DORA delivery measures, and shows how to connect metrics to alerts. It includes Prometheus examples, a cardinality budget, and guidance for keeping request identifiers in logs or traces instead of metric labels.

Metrics, Monitoring, and Alerting: From SLIs to Production Alerts

Introduction

Monitoring helps teams detect failures, degradation, and capacity problems before users report them. Useful signals need clear definitions and alert thresholds tied to conditions someone can act on.

This guide covers SLIs, SLOs, alerting, dashboards, and service health metrics, with practical examples. It assumes familiarity with logs and metrics collection; for structured logging, see Logging Best Practices.

Core Concepts

SLIs are the actual metrics you measure. They define what “good” looks like for your service.

Common SLIs for Web Services

An SLI is a measurement definition: it states the eligible events, the good outcome, and the measurement window. A vague definition can reward the wrong behavior; for example, counting every non-5xx response as success may count an unavailable resource as healthy. The figures below are fictional examples used to show the calculation. They are not service benchmarks or recommended targets.

SLI Definition Target guidance
Availability Share of eligible requests that meet the success definition Set with service owners from user impact
Latency Share of eligible requests below a stated threshold, or a stated percentile Set from user expectations and observed workload
Throughput Requests handled per second Compare with expected demand and capacity
Error Rate Share of eligible requests that fail the success definition Define which failures matter to users

Plot the latency distribution before setting a target. A dependency calculation is only useful when the calls are all required on the user-facing path and failures are independent; real systems often have retries, fallbacks, and shared failure modes. Model those conditions instead of treating a product of advertised availability numbers as an end-to-end promise.

Worked SLI Definition

Suppose an orders API wants to measure successful GET /orders/{id} requests over a rolling 28-day window. Define eligible events as authenticated requests with a valid order ID. Define a good event as a response that returns the expected order representation within 300 ms. If 99,500 of 100,000 eligible requests meet that definition, the example SLI is 99.5% for that window. Those counts and the latency threshold are illustrative; a real service should choose its success criteria and target with product owners and user evidence.

The denominator is the count of eligible requests, not all network traffic. The numerator is the subset meeting both the response and latency criteria. Document treatment of client errors, cancellations, retries, and requests served from a cache so that instrumentation and alert rules use the same definition. Google’s SRE guidance on SLOs describes SLIs as carefully defined quantitative measures and recommends choosing measures that reflect user experience.

Measuring SLIs

Define SLIs precisely so they can be measured consistently:

# sli-config.yaml
service: api-gateway
environment: production

slis:
  - name: request_success_rate
    description: "Eligible order reads returning the documented successful response"
    query: |
      sum(rate(http_requests_total{service="api-gateway",route="/orders/{id}",status=~"2.."}[28d]))
      /
      sum(rate(http_requests_total{service="api-gateway",route="/orders/{id}",eligible="true"}[28d]))

  - name: requests_within_latency_threshold
    description: "Share of eligible order reads completed within 300 ms"
    query: |
      sum(rate(http_request_duration_seconds_bucket{service="api-gateway",route="/orders/{id}",le="0.3"}[28d]))
      /
      sum(rate(http_requests_total{service="api-gateway",route="/orders/{id}",eligible="true"}[28d]))

  - name: error_rate
    description: "Percentage of requests returning 5xx errors"
    query: |
      sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[5m]))
      /
      sum(rate(http_requests_total{service="api-gateway"}[5m]))

Service Level Objectives

An SLO is a target for an SLI over a stated window. Teams use it to make reliability decisions. An SLO can be internal; it becomes part of an SLA only when the service provider includes it in a customer agreement with defined remedies and exclusions.

Defining SLOs

An SLO combines an SLI, a target or threshold, and a time window. The values below are a fictional example, not a baseline for other services:

# SLO configuration
objectives:
  - display_name: "API Availability"
    sli: request_success_rate
    target: 99.9
    window: 30d
    description: "Example target for the eligible-request success ratio"

  - display_name: "API Latency"
    sli: requests_within_latency_threshold
    target: 95.0
    threshold_ms: 300
    window: 30d
    description: "Example: 95% of eligible requests complete within 300ms"

  - display_name: "API Error Rate"
    sli: error_rate
    target: 0.5
    threshold_percent: 0.5
    window: 30d
    description: "Example: 5xx responses stay below 0.5% of eligible requests"

Error Budgets

Error budgets convert SLO compliance into an operational policy. For the example 99.9% availability target over a 30-day time-based window, the allowed unavailability is 43.2 minutes. For request-based SLIs, calculate the allowed bad-request fraction instead of translating it to wall-clock downtime:

# Calculate error budget
def error_budget(slo_target, window_days=30):
    window_seconds = window_days * 24 * 60 * 60
    allowed_downtime = window_seconds * (1 - slo_target)
    return allowed_downtime

# 99.9% over 30 days = 43.2 minutes
budget = error_budget(0.999)
print(f"Monthly error budget: {budget / 60:.1f} minutes")
# Monthly error budget: 43.2 minutes

Error budgets tell you when you can be aggressive with releases (large budget remaining) and when you need to be careful (budget nearly exhausted).

flowchart TB
    subgraph "Error Budget Lifecycle"
        A["SLO Target\n99.9% = 43.2 min/month"]
        B["Error Budget\n= Allowed Downtime"]
        C["Budget Remaining\n= Good (deploy freely)"]
        D["Budget Burning\n= Sustained Burn (1x)"]
        E["Budget Critical\n= Fast Burn (14.4x)"]
        F["SLO Target Missed\n= Review policy"]
    end
    A --> B
    B --> C
    B --> D
    D --> E
    E --> F

SLO Alerting

Set up alerting before you burn through the budget:

# Example alert rule; the target and window must match the service SLO
- alert: SLOErrorBudgetBurning
  expr: |
    (
      sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[1h]))
      /
      sum(rate(http_requests_total{service="api-gateway"}[1h]))
    )
    > (1 - 0.999) * 14.4
  labels:
    severity: warning
  annotations:
    summary: "Error budget burning fast"
    description: "Example 14.4x burn-rate alert for this illustrative 99.9% SLO"

Multi-Window Burn-Rate Alerting

Burn-rate alerts compare the observed bad-event rate with the rate that would consume the budget exactly over the SLO window. The following starting points are from Google’s SRE workbook for a 99.9% SLO; use the paired short and long windows from that guidance, and adjust the policy for the service’s traffic and impact.

Long window Short window Burn rate Budget used over long window Example use
1 hour 5 minutes 14.4x 2% Fast burn; page
6 hours 30 minutes 6x 5% Medium burn; investigate
3 days 6 hours 1x 10% Sustained burn; review

Fast burn alert (1-hour and 5-minute windows)

# Multi-window burn-rate alerting rules
groups:
  - name: slo-burn-rate
    interval: 30s
    rules:
      # 1-hour window: Page immediately if burning 14.4x sustainable rate
      # At 99.9% SLO, sustainable error rate = 0.001
      # 14.4 * 0.001 = 0.0144 = 1.44% error rate
      - alert: SLOErrorBudgetFastBurn
        expr: |
          (
            sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[1h]))
            /
            sum(rate(http_requests_total{service="api-gateway"}[1h]))
          )
          > (1 - 0.999) * 14.4
          and
          (
            sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[5m]))
            /
            sum(rate(http_requests_total{service="api-gateway"}[5m]))
          )
          > (1 - 0.999) * 14.4
        labels:
          severity: page
          category: slo
          window: 1h
        annotations:
          summary: "Error budget burning fast - FAST PAGE"
          description: |
            Error budget is being consumed {{ $value | humanize }}x faster than sustainable.
            At this rate, your entire 30-day budget will be exhausted in about 50 hours.
            SLO: 99.9% | Current error rate: {{ $value | humanizePercentage }}
            Action: Page on-call immediately and investigate error spike.

Medium burn alert (6-hour and 30-minute windows)

# 6-hour window: Warning if burning 6x sustainable rate
# 6 * 0.001 = 0.006 = 0.6% error rate
- alert: SLOErrorBudgetMediumBurn
  expr: |
    (
      sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[6h]))
      /
      sum(rate(http_requests_total{service="api-gateway"}[6h]))
    )
    > (1 - 0.999) * 6
    and
    (
      sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[30m]))
      /
      sum(rate(http_requests_total{service="api-gateway"}[30m]))
    )
    > (1 - 0.999) * 6
  labels:
    severity: warning
    category: slo
    window: 6h
  annotations:
    summary: "Error budget burning - INVESTIGATE"
    description: |
      Error budget is being consumed {{ $value | humanize }}x faster than sustainable.
      At this rate, 5% of your 30-day budget will be burned in 6 hours.
      SLO: 99.9% | Current error rate: {{ $value | humanizePercentage }}
      Action: Investigate elevated error patterns during business hours.

Slow burn alert (3-day and 6-hour windows)

# 3-day window: sustained budget use (1x burn rate)
# For an illustrative 99.9% SLO, 1x is a 0.1% bad-event rate
- alert: SLOErrorBudgetSlowBurn
  expr: |
    (
      sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[3d]))
      /
      sum(rate(http_requests_total{service="api-gateway"}[3d]))
    )
    > (1 - 0.999) * 1
    and
    (
      sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[6h]))
      /
      sum(rate(http_requests_total{service="api-gateway"}[6h]))
    )
    > (1 - 0.999) * 1
  labels:
    severity: warning
    category: slo
    window: 3d
  annotations:
    summary: "Error budget slow leak - REVIEW"
    description: |
      Error budget is being consumed {{ $value | humanize }}x faster than sustainable.
      At this rate, about 10% of a 30-day budget is consumed in 3 days.
      SLO: 99.9% | Current error rate: {{ $value | humanizePercentage }}
      Action: Schedule reliability review; may indicate systemic issues.

Combined Multi-Window Alert

# Combined: Fire if ANY window exceeds threshold
# This catches both fast spikes and slow leaks
- alert: SLOErrorBudgetMultiWindowBurn
  expr: |
    (
      sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[1h]))
      /
      sum(rate(http_requests_total{service="api-gateway"}[1h]))
    )
    > (1 - 0.999) * 14.4
    and
    (
      sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[5m]))
      /
      sum(rate(http_requests_total{service="api-gateway"}[5m]))
    )
    > (1 - 0.999) * 14.4
    or
    (
      sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[6h]))
      /
      sum(rate(http_requests_total{service="api-gateway"}[6h]))
    )
    > (1 - 0.999) * 6
    and
    (
      sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[30m]))
      /
      sum(rate(http_requests_total{service="api-gateway"}[30m]))
    )
    > (1 - 0.999) * 6
    or
    (
      sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[3d]))
      /
      sum(rate(http_requests_total{service="api-gateway"}[3d]))
    )
    > (1 - 0.999) * 1
    and
    (
      sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[6h]))
      /
      sum(rate(http_requests_total{service="api-gateway"}[6h]))
    )
    > (1 - 0.999) * 1
  labels:
    severity: page
    category: slo
  annotations:
    summary: "Error budget burning across multiple time windows"
    description: |
      One or more configured time windows show an unsustainable error rate.
      The alert value is the error ratio from the firing expression, not the burn-rate multiplier.
      Action: On-call should investigate and consider declaring an incident.

Burn-Rate Alerting Template (Parameterizable)

# Template for burn-rate alerting with configurable SLO
# Use $slo_threshold as a template variable or replace manually
- alert: SLOBudgetBurnGeneric
  expr: |
    (
      sum(rate(http_requests_total{service="$service",status=~"5.."}[1h]))
      /
      sum(rate(http_requests_total{service="$service"}[1h]))
    )
    > (1 - $slo_threshold) * 14.4
    and
    (
      sum(rate(http_requests_total{service="$service",status=~"5.."}[5m]))
      /
      sum(rate(http_requests_total{service="$service"}[5m]))
    )
    > (1 - $slo_threshold) * 14.4
    or
    (
      sum(rate(http_requests_total{service="$service",status=~"5.."}[6h]))
      /
      sum(rate(http_requests_total{service="$service"}[6h]))
    )
    > (1 - $slo_threshold) * 6
    and
    (
      sum(rate(http_requests_total{service="$service",status=~"5.."}[30m]))
      /
      sum(rate(http_requests_total{service="$service"}[30m]))
    )
    > (1 - $slo_threshold) * 6
    or
    (
      sum(rate(http_requests_total{service="$service",status=~"5.."}[3d]))
      /
      sum(rate(http_requests_total{service="$service"}[3d]))
    )
    > (1 - $slo_threshold) * 1
    and
    (
      sum(rate(http_requests_total{service="$service",status=~"5.."}[6h]))
      /
      sum(rate(http_requests_total{service="$service"}[6h]))
    )
    > (1 - $slo_threshold) * 1
  for: 5m
  labels:
    severity: page
    category: slo
  annotations:
    summary: "Error budget burning for {{ $labels.service }} (SLO: {{ $labels.slo_target }})"
    description: |
      Multi-window burn-rate alert for {{ $labels.service }}.
      SLO: {{ $labels.slo_target }}% | Windows: 1h / 6h / 3d
      Refer to incident runbook: {{ $labels.runbook_url }}

Error Budget Dashboard

{
  "dashboard": {
    "title": "SLO Error Budget Dashboard",
    "panels": [
      {
        "title": "Error Budget Remaining",
        "type": "gauge",
        "targets": [
          {
            "expr": "(1 - ((sum(rate(http_requests_total{service=\"api-gateway\",status=~\"5..\"}[30d])) / sum(rate(http_requests_total{service=\"api-gateway\"}[30d]))) / (1 - 0.999))) * 100",
            "legendFormat": "Budget Remaining %"
          }
        ],
        "fieldConfig": {
          "defaults": {
            "min": 0,
            "max": 100,
            "unit": "percent",
            "thresholds": {
              "mode": "absolute",
              "steps": [
                { "value": 0, "color": "red" },
                { "value": 25, "color": "orange" },
                { "value": 50, "color": "yellow" },
                { "value": 75, "color": "green" }
              ]
            }
          }
        }
      },
      {
        "title": "Burn Rate by Window",
        "type": "graph",
        "targets": [
          {
            "expr": "(sum(rate(http_requests_total{service=\"api-gateway\",status=~\"5..\"}[1h])) / sum(rate(http_requests_total{service=\"api-gateway\"}[1h]))) / (1 - 0.999)",
            "legendFormat": "1h Burn Rate"
          },
          {
            "expr": "(sum(rate(http_requests_total{service=\"api-gateway\",status=~\"5..\"}[6h])) / sum(rate(http_requests_total{service=\"api-gateway\"}[6h]))) / (1 - 0.999)",
            "legendFormat": "6h Burn Rate"
          },
          {
            "expr": "(sum(rate(http_requests_total{service=\"api-gateway\",status=~\"5..\"}[3d])) / sum(rate(http_requests_total{service=\"api-gateway\"}[3d]))) / (1 - 0.999)",
            "legendFormat": "3d Burn Rate"
          }
        ],
        "gridPos": { "x": 0, "y": 8, "w": 12, "h": 8 }
      },
      {
        "title": "Projected Budget Exhaustion (Hours)",
        "type": "stat",
        "targets": [
          {
            "expr": "((1 - (sum(rate(http_requests_total{service=\"api-gateway\",status=~\"5..\"}[30d])) / sum(rate(http_requests_total{service=\"api-gateway\"}[30d])))) * 30 * 24) / ((sum(rate(http_requests_total{service=\"api-gateway\",status=~\"5..\"}[1h])) / sum(rate(http_requests_total{service=\"api-gateway\"}[1h]))) / (1 - 0.999))",
            "legendFormat": "Hours remaining"
          }
        ],
        "gridPos": { "x": 12, "y": 8, "w": 6, "h": 4 }
      },
      {
        "title": "Error Rate vs SLO Target",
        "type": "timeseries",
        "targets": [
          {
            "expr": "sum(rate(http_requests_total{service=\"api-gateway\",status=~\"5..\"}[5m])) / sum(rate(http_requests_total{service=\"api-gateway\"}[5m])) * 100",
            "legendFormat": "Current Error Rate %"
          },
          {
            "expr": "(1 - 0.999) * 100",
            "legendFormat": "SLO Target Error Rate %"
          }
        ],
        "gridPos": { "x": 18, "y": 8, "w": 6, "h": 8 }
      }
    ]
  }
}

Observability Hooks for Metrics Monitoring

This section defines what to log, measure, trace, and alert for metrics monitoring systems themselves.

Log (What to Emit)

Event Fields Level
Scrape target added target, job, endpoint INFO
Scrape target removed target, job, reason INFO
Alert state change alert_name, old_state, new_state, duration INFO
Recording rule evaluation error rule_name, error ERROR
Alert evaluation error alert_name, error ERROR
Remote write failure remote_url, error, retry_count WARN
TSDB checkpoint created checkpoint_size, duration DEBUG

Measure (Metrics to Collect)

Metric Type Description
prometheus_tsdb_head_samples Gauge Samples in TSDB head
prometheus_tsdb_head_chunks Gauge Chunks in TSDB head
prometheus_tsdb_head_duration_seconds Gauge Time head has existed
prometheus_target_scrapes_total Counter Total scrape attempts
prometheus_target_scrapes_failed_total Counter Failed scrape attempts
prometheus_target_scrapes_exceeded_target_limit_total Counter Targets exceeding limit
prometheus_remote_write_requests_total Counter Remote write requests
prometheus_remote_write_requests_failed_total Counter Failed remote write requests
prometheus_alertmanager_alerts_total Counter Alerts sent to Alertmanager
prometheus_alerting_rules_evaluated_total Counter Rule evaluations
prometheus_notifications_queue_length Gauge Pending notifications
prometheus_http_request_duration_seconds Histogram HTTP request latency

Trace (Correlation Points)

Operation Trace Attribute Purpose
Scrape cycle scrape.job, scrape.target Track scrape performance
Remote write remote_write.endpoint, remote_write.status Monitor write health
Alert evaluation alert.name, alert.severity Correlate alerts

Alert (When to Page for Monitoring System Itself)

The thresholds in the table and the sample rules below illustrate how to connect an alert to an operational response. They are not Prometheus defaults; set each failure rate, duration, queue size, and latency limit from the monitoring service’s SLO and measured behavior.

Alert Condition Severity Purpose
Prometheus Down Prometheus instance unreachable P1 Critical Monitoring unavailable
TSDB Head Growing Head chunks > 2 weeks of data P2 High Storage issue
Scrape Failure Rate Scrape failures > 10% for 10 min P2 High Missing metrics
Remote Write Failing Remote write failures > 5% P1 Critical Backup missing
Alert Queue Full Pending alerts > 100 P3 Medium Notification delay
High Cardinality Cardinality > configured limit P3 Medium Memory pressure

Metrics Monitoring System Observability Template

# monitoring-system-observability.yaml
groups:
  - name: prometheus-self-monitoring
    rules:
      # Prometheus instance down
      - alert: PrometheusDown
        expr: up{job="prometheus"} == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Prometheus instance {{ $labels.instance }} is down"
          description: "Prometheus monitoring is unavailable. Investigate immediately."

      # TSDB head growing unbounded
      - alert: PrometheusTSDBHeadOld
        expr: prometheus_tsdb_head_min_time{job="prometheus"} < (time() - 3600 * 24 * 14)
        for: 1h
        labels:
          severity: warning
        annotations:
          summary: "Prometheus TSDB head is more than 2 weeks old"
          description: "TSDB head has not compacted in 2 weeks. Check storage and compaction settings."

      # High scrape failure rate
      - alert: PrometheusScrapeFailureRate
        expr: |
          sum(rate(prometheus_target_scrapes_failed_total{job="prometheus"}[10m]))
          /
          sum(rate(prometheus_target_scrapes_total{job="prometheus"}[10m])) > 0.1
        for: 10m
        labels:
          severity: high
        annotations:
          summary: "Prometheus scrape failure rate above 10%"
          description: "{{ $value | humanizePercentage }} of scrapes are failing."

      # Remote write failures
      - alert: PrometheusRemoteWriteFailing
        expr: |
          sum(rate(prometheus_remote_write_requests_failed_total[5m]))
          /
          sum(rate(prometheus_remote_write_requests_total[5m])) > 0.05
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "Prometheus remote write failure rate above 5%"
          description: "Remote write to long-term storage is failing. Historical metrics at risk."

      # Notification queue backing up
      - alert: PrometheusNotificationQueueFull
        expr: prometheus_notifications_queue_length{job="prometheus"} > 100
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Prometheus alert notification queue is backing up"
          description: "{{ $value }} alerts pending delivery. Alertmanager may be unreachable."

      # High HTTP request latency
      - alert: PrometheusHighQueryLatency
        expr: |
          histogram_quantile(0.95,
            sum(rate(prometheus_http_request_duration_seconds_bucket{job="prometheus"}[5m])) by (le)
          ) > 2
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "Prometheus query latency above 2 seconds (p95)"
          description: "Query performance is degraded. Check TSDB load and query complexity."

      # Burn-rate alerting for SLO itself (meta-monitoring)
      - alert: SLOBurnRateAlertMetaMonitoring
        expr: |
          (
            sum(rate(prometheus_target_scrapes_failed_total{job="prometheus"}[1h]))
            /
            sum(rate(prometheus_target_scrapes_total{job="prometheus"}[1h]))
          ) > 0.01
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Prometheus monitoring quality degraded"
          description: "Scrape failure rate is {{ $value | humanizePercentage }}. Monitoring accuracy reduced."

DORA Metrics for Delivery Performance

DORA’s current software delivery model uses five metrics. They describe delivery throughput and instability; they are not substitutes for user-facing SLIs or service reliability SLOs. See the current DORA metrics guide for definitions and measurement context.

Metric What it measures
Change lead time Time from a code change being committed to its successful production deployment
Deployment frequency How often changes are deployed to production
Failed deployment recovery time Time to recover when a production deployment causes a failure that requires intervention
Change fail rate Share of production deployments that require immediate intervention, such as rollback or hotfix
Deployment rework rate Share of deployments that were unplanned work to address a production issue

Do not set universal target values for these measures. Compare a team’s trend with its own service context and use the results to choose process improvements, not to rank individuals. Keep the measurement window and definitions consistent when comparing periods.

Measuring DORA Metrics

Collect production deployment, commit, incident, and remediation events from the systems that own those records. Document the event boundaries before calculating rates:

change lead time = successful production deployment time - commit time
deployment frequency = production deployments during the selected period
failed deployment recovery time = recovery time - failed deployment time
change fail rate = deployments requiring immediate intervention / production deployments
deployment rework rate = unplanned remediation deployments / all production deployments

The event definitions matter. A deployment to staging is not a production deployment; a routine planned release is not rework; and recovery from a service incident unrelated to a deployment is not failed deployment recovery time.

Connecting DORA to SLOs

DORA metrics and SLOs answer different questions. DORA describes how software changes move through production and how deployments behave. An SLI measures a user-facing service outcome, and an SLO sets the target for that outcome. They can be reviewed together: annotate SLO burn-rate charts with deployment events, then investigate whether a deployment caused user-visible impact. Correlation alone does not prove causation, and an SLO breach can occur without a recent deployment.

Use an error-budget policy agreed with the service’s stakeholders. Do not apply an arbitrary remaining-budget percentage as a universal release gate; choose a response based on user impact, risk, and the service’s documented policy.

Monitoring Cost Optimization

Monitoring cost depends on how many time series you store, how often you sample them, how long you retain them, and what your backend charges for storage and queries. Estimate those inputs from the deployed system and bill rather than assuming a generic retention schedule or scrape interval.

Every distinct label combination creates a time series. For example, 20 route templates × 5 methods × 6 status classes × 4 regions can produce up to 2,400 combinations before other labels are counted. Treat that as a planning calculation, not a capacity guarantee. Do not put request IDs, user IDs, or other unbounded values in metric labels; keep request IDs in logs or traces, or use exemplars where the metrics backend supports them. Prometheus documents the same high-cardinality warning in its label naming guidance.

Retention should match the questions the data must answer, the backend’s storage model, and any contractual or legal retention requirements. If long-term trends matter, test whether downsampled or pre-aggregated data preserves the detail your reports need before deleting raw samples.

Choose scrape intervals based on how quickly a signal must be detected and how much collection load the target can support. Verify that the interval can detect the incidents your alerts are meant to catch; a slower interval can delay detection, while a faster one increases collection and storage work.

Review series count, sample rate, retention, and query load together. Change one setting at a time and confirm that alerts, dashboards, and investigations still have the data they need.

Controlling Cardinality

Every unique combination of label values creates a new time series. Prometheus recommends avoiding labels with unbounded values such as user IDs or email addresses. Request IDs belong in logs or traces, where they can connect an individual request without creating one metric series per request.

# Check cardinality per metric
topk(10,
  count by (__name__) (
    {__name__=~".+"}
  )
)

# Identify high-cardinality label combinations
count by (job, __name__) (
  {__name__="http_requests_total"}
)

Set a series budget for each service using the expected label-value combinations and the storage capacity available to that service. Revisit it after load tests or instrumentation changes; there is no universal safe series count for every metric or Prometheus deployment.

  • Keep route labels normalized to route templates rather than raw paths or IDs.
  • Keep request IDs, user IDs, and session IDs out of metric labels.
  • Use logs, traces, or supported exemplars when operators need to pivot from an aggregate metric to one request.
  • Use recording rules for repeated aggregations when they reduce query work without hiding needed detail.

Retention and Downsampling

Long retention periods multiply storage costs. Use downsampling to preserve historical patterns at lower resolution.

# prometheus.yml
rule_files:
  - /etc/prometheus/rules/*.yml

scrape_configs:
  - job_name: "federate"
    metrics_path: /federate
    params:
      match[]:
        - '{__name__=~"job:.+"}'
    rule_files:
      - /etc/prometheus/rollups.yml
# rollups.yml - pre-computed aggregations
groups:
  - name: hourly_rollups
    interval: 1h
    rules:
      - record: job:http_requests_total:hourly_rate
        expr: |
          sum by (job, status) (
            rate(http_requests_total[1h])
          )

Retention is a service decision, not a universal schedule. Keep raw data for the incident and debugging window your team needs, then retain rollups only when they still answer a defined capacity, product, or compliance question. Check the monitoring backend’s retention and downsampling behavior before adopting this pattern.

Scrape Interval Tuning

Frequent scrapes improve resolution but increase resource usage. Match scrape intervals to alert requirements.

Decision need Choose an interval that…
Incident alerting Detects the failure within the response time your SLO policy requires
Capacity trends Captures changes quickly enough to inform provisioning decisions
Slow-moving state Avoids collecting faster than the signal changes, while retaining enough history for diagnosis

Validate the chosen interval with the actual scrape load, alert expressions, and backend retention settings.

Multi-Region Monitoring Strategies

Running monitoring across regions means dealing with network latency, aggregation headaches, and the question of whether to set SLOs per region or globally.

Federation Architecture

Federation allows hierarchical collection where regional Prometheus servers scrape local targets, then a global Prometheus federation scrapes the regional instances.

# Regional Prometheus (scapes local targets)
scrape_configs:
  - job_name: "local-services"
    static_configs:
      - targets: ["app-us-east-1:9090", "db-us-east-1:9090"]

# Global Prometheus (federates regional)
scrape_configs:
  - job_name: "federate-us-east-1"
    metrics_path: /federate
    params:
      match[]:
        - '{__name__=~"job:.+"}'
    static_configs:
      - targets: ["prometheus-us-east-1:9090"]

Considerations:

  • Network latency affects metric freshness; use longer evaluation intervals for federated data
  • Not all metrics need global aggregation; filter with match[] rules
  • Cross-region bandwidth costs money; only federate what you need

Regional vs Global SLOs

A user in Frankfurt cares about Frankfurt availability, not your global average. Global SLOs can hide regional outages entirely.

Approach Pros Cons
Global SLO only Simpler reporting Masks regional issues
Regional SLOs Reflects user experience More dashboards to manage
Both Accurate + simple reporting Requires good tooling

For global services, set regional SLOs per region plus a composite global SLO. Alert on regional SLOs to catch degradation early.

Synthetic Monitoring from Multiple Locations

Real-user monitoring and synthetic checks from multiple geographic points catch regional issues that internal metrics miss.

import requests
import time

# Run synthetic checks from multiple regions
REGIONS = ["us-east-1", "eu-west-1", "ap-southeast-1"]

def synthetic_check_region(region):
    start = time.time()
    try:
        resp = requests.get(
            f"https://api.example.com/health",
            timeout=5,
            headers={"X-Region": region}
        )
        duration = time.time() - start
        # Report per-region metrics
        metrics.gauge(f"health_check_{region}_duration", duration)
        metrics.gauge(f"health_check_{region}_success", 1 if resp.status == 200 else 0)
    except Exception as e:
        metrics.gauge(f"health_check_{region}_success", 0)

Route alerts based on both regional synthetic checks and internal metrics. A regional synthetic failure plus elevated internal latency in the same region strongly indicates a regional outage.

Service Level Agreements

SLAs are contractual commitments to customers, often backed by financial penalties. They are usually less aggressive than SLOs.

SLA vs SLO

Aspect SLA SLO
Audience Customers Internal
Enforced by Contracts, penalties Team discipline
Target Usually less strict Usually more strict
Consequences Financial Operational

Don’t set SLAs until you have SLOs you are confident you can meet. Adding contractual SLAs before you understand your system’s behavior is asking for trouble.

Building Dashboards

Dashboards translate metrics into actionable information. Good dashboards answer specific questions. Bad dashboards show everything and answer nothing.

Dashboard Design Principles

Start each dashboard with its intended user and the question it should answer. An on-call view needs current service health and links to detailed traces; a planning view may need longer trends and capacity context. Keep those views separate when one page becomes hard to scan, and link between them so an operator can move from the alert to the evidence.

Group panels by the operational question they answer. During an incident, place traffic, error, and latency signals together so the operator can see whether they changed at the same time. Separate unrelated concerns such as dependency upgrades and live request health unless they serve the same decision.

Put each metric beside its target and time range. Deployment and configuration annotations can help explain a change, but they show timing rather than cause. Calibrate colors and thresholds to the service’s SLO or capacity plan instead of copying defaults.

Remove panels that no longer support a decision. A useful dashboard makes its main signals easy to find; there is no universal panel count that fits every service. Keep legends and labels when they help interpret the data, and remove decoration that adds no information.

Example Dashboard Panels

# Grafana dashboard JSON (abbreviated)
{
  "dashboard":
    {
      "title": "API Gateway Overview",
      "panels":
        [
          {
            "title": "Request Rate",
            "type": "graph",
            "targets":
              [
                {
                  "expr": "sum(rate(http_requests_total{service='api-gateway'}[5m])) by (service)",
                  "legendFormat": "{{service}}",
                },
              ],
            "gridPos": { "x": 0, "y": 0, "w": 12, "h": 8 },
          },
          {
            "title": "Error Rate",
            "type": "stat",
            "targets":
              [
                {
                  "expr": "sum(rate(http_requests_total{service='api-gateway',status=~'5..'}[5m])) / sum(rate(http_requests_total{service='api-gateway'}[5m])) * 100",
                  "legendFormat": "Error %",
                },
              ],
            "fieldConfig":
              {
                "defaults":
                  {
                    "thresholds":
                      {
                        "mode": "absolute",
                        "steps":
                          [
                            { "value": 0, "color": "green" },
                            { "value": 0.1, "color": "yellow" },
                            { "value": 1, "color": "red" },
                          ],
                      },
                  },
              },
            "gridPos": { "x": 12, "y": 0, "w": 6, "h": 4 },
          },
          {
            "title": "P95 Latency",
            "type": "gauge",
            "targets":
              [
                {
                  "expr": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket{service='api-gateway'}[5m])) by (le)) * 1000",
                  "legendFormat": "p95 ms",
                },
              ],
            "gridPos": { "x": 18, "y": 0, "w": 6, "h": 4 },
          },
        ],
    },
}

Essential Dashboard Sections

At a glance: Show the health indicators the on-call engineer needs first, such as the service SLI, error rate, latency distribution, and request volume. Include the target and trend so the current value has context.

Request metrics: Show rate, errors, and latency by route template or endpoint group. An aggregate can hide a failing route, so let operators inspect the breakdowns that matter to the service’s SLO.

Infrastructure metrics: CPU, memory, disk, and network help explain application symptoms. Show latency separately from throughput, and set utilization alerts from measured saturation behavior and the time needed to add capacity.

Application Metrics: Business-specific metrics like queue depths, cache hit rates, or background job counts. These vary by service but are often the most actionable signals for product teams. Queue depth for message consumers tells you whether work is backing up faster than workers can process it. Cache hit ratio tells you whether your application is reading from disk instead of memory. Background job queue depth and processing rate tell you whether batch work is keeping up with arrival rate. Define these for your specific application architecture rather than using generic infrastructure metrics.

Dependency health: Show connection-pool use, errors, and latency for databases, caches, and external APIs. Compare those signals with the dependency’s own published SLO when one is available; a high utilization value matters when it causes waits or threatens a documented capacity limit.

Alert Design

Alerts should wake someone up only when they need to act. Too many alerts cause fatigue; too few cause outages.

Alert Severity Levels

Severity levels only work if your organization agrees on what they mean. Decide which alerts page immediately, which need prompt investigation, and which can wait for normal support hours. If teams route every alert through the same escalation path, severity labels stop helping.

Severity Response expectation Examples
P1 Critical Immediate on-call response Complete outage, data loss, security breach
P2 High Prompt investigation by the owning team Degraded performance affecting users
P3 Medium Work during normal support hours Minor degradation, non-critical failures
P4 Low Track and schedule Predictable issues, capacity planning

These response expectations are team policy, not universal standards. Reassess severity using actual user impact when an alert fires; the same infrastructure condition can carry different urgency in a test environment and a customer-facing service.

One common mistake: assigning severity based on infrastructure metrics rather than user impact. “Disk 90% full” might be P1 if it is the last shard of a critical database, or P4 if it is a test environment. Same metric, different severity. Always tie severity to business or user impact, not to the raw metric value.

Alert Quality Checklist

Before creating an alert, ask:

  • Does this indicate a real problem affecting users?
  • Is the root cause something we can fix?
  • Is the alert actionable? Can the recipient do something about it?
  • Is the alert specific? Does it point toward the likely cause?
  • Is the threshold calibrated? Are we alerting on symptoms or causes?

Alerting on symptoms leads to noise. Alerting on causes requires understanding your system well enough to know what indicates true problems.

Example Alert Rules

The thresholds and evaluation windows in these snippets are fictional examples. Replace them with criteria tied to the service’s SLO, workload, and response time; do not copy them as defaults.

# Prometheus alerting rules
groups:
  - name: api-gateway
    rules:
      # High error rate
      - alert: APIGatewayHighErrorRate
        expr: |
          sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[5m]))
          /
          sum(rate(http_requests_total{service="api-gateway"}[5m])) > 0.01
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "API Gateway error rate above 1%"
          description: "Error rate is {{ $value | humanizePercentage }} over the last 5 minutes"

      # Latency degradation
      - alert: APIGatewayHighLatency
        expr: |
          histogram_quantile(0.95,
            sum(rate(http_request_duration_seconds_bucket{service="api-gateway"}[5m])) by (le)
          ) > 1
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "API Gateway P95 latency above 1 second"
          description: "P95 latency is {{ $value | humanizeDuration }}"

      # Slow queries
      - alert: DatabaseSlowQueries
        expr: |
          rate(django_dbqueries_total{type="slow"}[5m]) > 10
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "More than 10 slow queries per second"
          description: "Database is experiencing query performance issues"

Alert Routing

Route alerts to the right people based on severity and service:

# Alertmanager configuration
route:
  receiver: default
  routes:
    - match:
        severity: critical
      receiver: pagerduty
      continue: true
    - match:
        service: database
      receiver: database-oncall
    - match:
        severity: warning
      receiver: slack-warnings
    - match:
        severity: info
      receiver: none # Don't alert, just log

receivers:
  - name: pagerduty
    pagerduty_configs:
      - service_key: xxx
        severity: critical
  - name: slack-warnings
    slack_configs:
      - channel: "#alerts-warning"
  - name: database-oncall
    pagerduty_configs:
      - service_key: yyy
        routing_key: database-team

Blackbox Monitoring

Blackbox monitoring tests your service from the outside, independent of application metrics. It catches failures that internal metrics miss.

Prometheus Blackbox Exporter

# blackbox.yml
modules:
  http_2xx:
    prober: http
    http:
      valid_http_versions: ["HTTP/1.1", "HTTP/2"]
      method: GET
      fail_if_ssl: false
# Prometheus scrape config
scrape_configs:
  - job_name: "blackbox-http"
    metrics_path: /probe
    params:
      module: [http_2xx]
    static_configs:
      - targets:
          - https://api.example.com/health
    relabel_configs:
      - source_labels: [__address__]
        target_label: __param_target
      - source_labels: [__param_target]
        target_label: instance
      - target_label: __address__
        replacement: blackbox-exporter:9115

Synthetic Transactions

Run synthetic transactions regularly to catch degradation before users notice:

import requests
import time

def synthetic_checkout():
    start = time.time()

    # 1. Create cart
    cart_resp = requests.post('https://api.example.com/carts', timeout=5)
    cart_id = cart_resp.json()['id']

    # 2. Add item
    requests.post(f'https://api.example.com/carts/{cart_id}/items',
                  json={'product_id': 'PROD123', 'quantity': 1}, timeout=5)

    # 3. Checkout
    checkout_resp = requests.post(f'https://api.example.com/carts/{cart_id}/checkout',
                                   timeout=10)

    duration = time.time() - start

    # Report metrics
    metrics.histogram('synthetic_checkout_duration', duration)
    metrics.gauge('synthetic_checkout_success', 1 if checkout_resp.status == 200 else 0)

Capacity Planning

Monitoring helps predict when you need more capacity.

Capacity planning should start before a resource becomes saturated. Choose review intervals based on how quickly demand changes and how long provisioning takes; a threshold is useful only when it leaves enough time to respond.

Use a demand metric that matches the workload, such as requests per second for a request-driven service or queued work for a batch system. Compare equivalent periods when seasonality matters, and break the result down by route or workload class when different parts of the service grow at different rates. Avoid extrapolating from a short burst as if it were sustained demand.

Prometheus’s predict_linear() can extend a recent trend toward a threshold, but the projection assumes that trend continues. Use it as a planning signal, not a promised exhaustion date. Set thresholds and safety margins from the resource’s saturation behavior and the time required to add capacity. Evaluate CPU, memory, storage, and connection pools separately, then investigate the earliest plausible constraint.

Storage projections should include data growth, retention, compression, and replica policies. Monitor actual usage over a representative period, update the estimate when those policies change, and assign an owner to review the forecast before the remaining headroom conflicts with provisioning lead time.

Scaling Thresholds

The KEDA values below are placeholders. Derive replica limits, queue or request thresholds, and query windows from load tests and provisioning time.

# KEDA scaled object for event-driven scaling
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: api-gateway-scaler
  namespace: production
spec:
  scaleTargetRef:
    name: api-gateway
  minReplicaCount: 3
  maxReplicaCount: 100
  triggers:
    - type: prometheus
      metadata:
        serverAddress: http://prometheus:9090
        metricName: http_requests_per_second
        threshold: "1000"
        query: sum(rate(http_requests_total{service="api-gateway"}[2m]))

When to Use Metrics-Based Monitoring

When to Use Metrics-Based Monitoring:

  • Real-time system health monitoring and alerting
  • Capacity planning and trend analysis
  • SLO/SLA tracking and error budget management
  • Correlation with business metrics (revenue, conversions)
  • Long-term historical analysis and reporting
  • Infrastructure and application layer monitoring

When Not to Use Metrics-Based Monitoring:

  • Debugging specific request failures (use logs)
  • Understanding request flow across services (use tracing)
  • One-off troubleshooting of transient issues
  • Monitoring low-volume events that do not aggregate well
  • Situations where you need the full context of a single operation

Trade-off Analysis

Aspect Metrics Monitoring Log Analysis Distributed Tracing
Latency Detection Aggregate patterns Per-request detail Request-level timing
Root Cause Correlation difficult Full context available Causal chain is clear
Storage Cost Low (aggregated) High (raw events) Medium (spans)
Query Flexibility High (PromQL/SQL) Medium (text search) Low (structured)
Historical Analysis Excellent Limited by cost Poor
Real-time Alerting Excellent Poor Good
Debug Single Request Poor Excellent Excellent
Capacity Planning Excellent Poor Poor

Production Failure Scenarios

Failure Impact Mitigation
Prometheus scrape failure Gaps in metrics; missing visibility Configure remote_write to backup; alert on target down; use Prometheus federation
Alert fatigue Teams ignore alerts; real issues missed Regularly review alert quality; remove stale alerts; tune thresholds
Metric cardinality explosion Prometheus OOM; query performance degraded Limit label cardinality; use recording rules; segment by service
Alert routing failure Critical alerts not delivered; extended outages Test alert routing; use multiple notification channels; on-call rotation
Dashboard data source outage No visibility for teams; blind decision making Configure backup data sources; cache dashboard definitions
SLO target chronically missed Customer trust erosion; potential SLA penalties Investigate root causes; adjust SLO targets if unrealistic; build error budget alerts

Common Pitfalls / Anti-Patterns

Common Pitfalls

1. Alerting on Symptoms Without Context

# Bad: Alerts on symptoms
- alert: HighCPU
  expr: cpu_usage > 80
  # Fires constantly without context

# Good: Alert with actionable context
- alert: HighCPUOnCriticalService
  expr: cpu_usage{service="api-gateway"} > 80 and rate(http_requests_total{service="api-gateway"}[5m]) > 1000
  # Only fires when it matters

2. Missing Alert Aggregation

A single failure can trigger many related alerts. Use grouping, inhibition, and routing to consolidate them:

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

3. SLOs That Do Not Reflect User Experience

Setting SLOs on backend metrics instead of user-visible metrics creates false confidence. SLOs should measure what users experience, not internal implementation details.

4. Dashboard Overload

More panels do not mean better monitoring. Each dashboard should answer specific questions. If you need to scroll, you have too many panels.

5. No Alert Testing

Alerts that never fire in production may have broken queries. Test alerts periodically by simulating conditions that should trigger them.

6. Ignoring Alert Fatigue

If engineers start ignoring alerts, real problems get missed. Review and tune alerts regularly. Remove alerts that no longer serve a purpose.

Observability Checklist

Core Metrics (Golden Signals)

The four golden signals—latency, traffic, errors, and saturation—are a useful starting point for service monitoring. Google’s SRE book explains how they help operators understand request health and resource pressure.

Latency deserves special attention because not all slow responses are failures. A report endpoint and an authentication endpoint may have different user expectations. Track latency distributions rather than averages, which can hide tail behavior. Separate successful slow responses from failed fast responses; they point to different problems.

Traffic measures demand in requests per second. It tells you whether your service is seeing normal load, unexpected spikes, or silent drops. Sudden traffic drops often mean upstream failures (your users cannot reach you), while traffic spikes might indicate attack traffic or a viral feature. Correlate traffic changes with error rate and latency changes to distinguish “lots of users having a good experience” from “lots of users having a bad experience.”

Track explicit errors such as 5xx responses and exceptions, as well as successful responses that miss the user’s latency or correctness expectations. Express failure as a share of eligible requests, not an absolute count: the same error count can mean very different things at different traffic levels.

Saturation describes pressure on a finite resource. Monitor queue depth, memory pressure, connection pools, and disk I/O alongside demand and latency. A utilization threshold only helps if it leaves enough time to respond and matches that resource’s measured behavior.

  • Latency: p50, p95, p99 response times
  • Traffic: requests per second, throughput
  • Errors: error rate (4xx, 5xx), success rate
  • Saturation: CPU, memory, disk, queue depths

Infrastructure Metrics

Infrastructure metrics answer “why is the application slow?” when application-level signals show degradation. The application layer tells you something is wrong; the infrastructure layer tells you why.

Host-level metrics cover the bare metal or VM your services run on. CPU use must be read alongside run queue, throttling, latency, and workload; a percentage alone does not show whether a host is out of capacity. Memory pressure can appear in swap activity or OOM events. Disk I/O and network saturation can add waits or timeouts to dependent services.

Container-level metrics matter in Kubernetes, Docker Compose, and ECS. A container that exceeds its memory limit may be terminated, so track OOM events and restarts. CPU throttling can also cause latency spikes that look like application bugs in distributed traces.

Kubernetes metrics add the orchestration layer perspective. Pod status reveals immediate problems (CrashLoopBackOff, ImagePullBackOff) but node conditions reveal underlying issues (MemoryPressure, DiskPressure, PIDPressure). Namespace quotas prevent runaway workloads from consuming all cluster resources, but you need to monitor quota utilization to know when to increase limits. Review resource request vs. actual usage regularly — over-requested resources waste money, under-requested resources cause throttling.

  • Host-level: CPU utilization, memory usage, disk I/O, network throughput
  • Container-level: resource limits, restart counts, OOM kills
  • Kubernetes: pod status, node conditions, namespace quotas

Application Metrics (RED/USE)

Application metrics sit closest to your users. Infrastructure metrics tell you why the system is struggling; application metrics tell you how users experience that struggle. The RED method (Rate, Errors, Duration) covers request-driven services; the USE method (Utilization, Saturation, Errors) covers resource-driven services. Most real-world systems need both.

Rate captures demand patterns that infrastructure metrics cannot show. Tracking requests by normalized route, method, or status class can reveal load changes and unexpected traffic. Review those dimensions against a cardinality budget, and investigate traffic anomalies alongside errors and latency.

Application errors include exceptions, failed database queries, upstream timeouts, and malformed responses. Not all errors are HTTP 5xx; a successful status with missing or incorrect data may still violate the user’s expectation. Segment failures by useful, bounded categories and review their impact before prioritizing fixes.

Duration histograms let you compare typical request time with tail behavior. Use percentiles such as p50, p95, or p99 where they help answer a specific question, and compare endpoints against their own SLOs rather than treating one percentile as a universal reliability threshold.

Application utilization includes connection pools, thread pools, and memory allocation. Watch wait time and rejected work alongside pool use. For background jobs, compare arrival and processing rates; a queue depth only has meaning in the context of how quickly that queue should drain.

Saturation at the application layer includes backpressure signals: HTTP 429 responses, circuit breaker state (open/half-open/closed), and throttling events. When your service starts sending 429 responses, users are experiencing degradation even if their requests eventually succeed. Circuit breaker state changes indicate upstream dependency problems propagating through your service graph. Track throttling events to catch auto-scaling lag before it becomes a user-visible incident.

  • Rate: requests per second by endpoint, method, status
  • Errors: error counts and rates by type, service, endpoint
  • Duration: histogram of request latencies with percentiles
  • Utilization: resource usage, queue lengths, connection pool stats
  • Saturation: backpressure indicators, throttling events

SLO/SLA Metrics

An SLI is the measured user outcome; an SLO is the service team’s target for that SLI; an SLA is a contractual promise with defined remedies and exclusions. A request-based SLI should state which requests count, what counts as good, and the measurement window. Choose separate indicators when availability, latency, or different endpoint classes affect users in different ways.

For burn-rate alerting, Google SRE publishes example multi-window starting points for a 99.9% SLO: 14.4x over one hour and five minutes, 6x over six hours and 30 minutes, and 1x over three days and six hours. These are configuration examples, not universal thresholds; low-traffic services and different SLO windows need different treatment. See the SRE workbook.

  • Define eligible events, good events, and the SLI window.
  • Agree on SLO targets with the service’s stakeholders.
  • Keep customer contract language and remedies in the SLA documentation.
  • Test burn-rate alerts against the SLI and window they claim to measure.

Alerting Rules

  • Page on user-impacting SLO burn that requires immediate response.
  • Notify the owning team about sustained degradation that needs investigation.
  • Alert on resource saturation when it threatens the service’s capacity or SLO.
  • Keep alert severity tied to user impact and the response action, not a copied threshold.

Security Checklist

  • Metrics endpoint (/metrics) not exposed publicly
  • Prometheus access authenticated (if external)
  • Alert manager notifications do not contain sensitive data
  • Dashboard links to internal systems use authenticated proxies
  • No API keys or secrets visible in dashboard URLs
  • Alert routing logs audited
  • Metrics cardinality limits enforced to prevent DoS
  • Remote write connections use TLS
  • Dashboard snapshots sanitized before sharing

Failure Scenarios

Illustrative scenario: alert storm from a bad threshold

A rule compares a latency histogram measured in seconds with a threshold interpreted as milliseconds. The unit mismatch makes it fire for ordinary traffic.

The mistake can pass review if nobody tests the rule against healthy and failing data. Validate alert expressions before deployment, add rule tests to CI where supported, and use grouping and inhibition to limit duplicate notifications.

Illustrative scenario: metrics disappear from a global view

A network partition interrupts federation from regional Prometheus servers. Regional dashboards remain available while the central view has gaps.

Check federation health and identify which view is authoritative during the outage. A remote-write backend may be a better fit for some deployments, but test its failure and recovery path before depending on it.

Security and Compliance Notes

Monitoring systems observe everything, which means they also observe sensitive operations. Security for observability infrastructure protects the data collected and ensures the monitoring system itself does not become a vulnerability.

Metrics Endpoint Protection

The /metrics endpoint on applications exposes operational data. Depending on what your application measures, this can include request rates, error patterns, and business metrics. External exposure of /metrics can reveal operational details to attackers performing reconnaissance.

Configure your application to require authentication or network-level restrictions on the metrics endpoint. For Prometheus, use network policies to restrict scrape access:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: prometheus-scrape
  namespace: monitoring
spec:
  podSelector:
    matchLabels:
      app: myapp
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              name: prometheus
      ports:
        - port: 9090

For Kubernetes, annotate pods to exclude sensitive metrics from default scrape targets when the standard metrics would reveal business-sensitive information.

Alert Notification Security

Alert notifications sent via Slack, PagerDuty, or email should not contain sensitive data. A notification that says “Production database connection pool exhausted” is fine. A notification that says “User XYZ’s password hash is 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8” is a data breach.

Audit your alert messages and notification channels. Review what information appears in PagerDuty incidents, Slack messages, and email alerts. Remove any sensitive data from alert content. Use ticket systems for detailed information rather than exposing it in notifications.

Access Control for Monitoring Data

Dashboards and alert rules should be access-controlled. Not every team member needs to see production metrics for unrelated services. Role-based access ensures that only authorized personnel can view sensitive operational data.

Cloud monitoring platforms (CloudWatch, GCP Operations, Azure Monitor) integrate with IAM. Use service accounts with minimal permissions for monitoring components. Avoid using user credentials for automated monitoring access.

TLS for Monitoring Connections

Scrape configurations, remote write operations, and dashboard connections should use TLS. Without TLS, metrics traffic can be intercepted or modified. Configure Prometheus, Grafana, and other monitoring components to use TLS endpoints.

For self-signed certificates in development, explicitly configure the monitoring system to trust the certificate rather than disabling certificate verification.

Log Retention and Privacy

Monitoring generates logs that may contain personally identifiable information (PII). Audit what data your logs capture and ensure that log retention policies comply with applicable privacy regulations (GDPR, CCPA). Anonymize or drop PII before ingestion where possible.

Compliance Considerations

For regulated environments, monitoring audit logs themselves may be subject to compliance requirements. Track who accessed what monitoring data and when. Ensure that monitoring data retention policies meet regulatory minimums.

High-availability monitoring prevents gaps in visibility that could hide security incidents. If your monitoring goes down during an attack, you lose the ability to detect and respond to it. Replicate monitoring infrastructure across availability zones and set up alerts for monitoring component failures.

Quick Recap Checklist

  • Define SLIs from user-visible outcomes and measure them consistently.
  • Set SLOs that reflect user needs and use error budgets to guide release decisions.
  • Use RED for request-driven services and USE for underlying resources.
  • Alert on actionable symptoms and burn rates, not isolated raw thresholds.
  • Monitor the monitoring pipeline, data quality, and cardinality as well as the application.

Interview Questions

These questions assess practical knowledge of metrics, monitoring, and alerting systems.

1. Explain the difference between RED and USE methods. When would you use each?

Expected answer points:

  • RED (Rate, Errors, Duration) focuses on request-driven services like APIs; USE (Utilization, Saturation, Errors) focuses on resource utilization
  • Use RED for services where you measure request/response patterns
  • Use USE for infrastructure resources like CPU, memory, disk
  • Most systems need both: USE for underlying resources, RED for user-facing services
2. What is an error budget, and how does it inform alerting strategy?

Expected answer points:

  • Error budget is the allowed amount of downtime/errors within an SLO window (e.g., 99.9% over 30 days = 43.2 minutes)
  • Burn rate alerts trigger when errors consume budget faster than sustainable
  • Google SRE's example burn rates for a 99.9% SLO include 14.4x over paired 1h/5m windows, 6x over 6h/30m, and 1x over 3d/6h
  • Large remaining budget allows aggressive deployments; exhausted budget requires stability focus
3. What are the Four Golden Signals, and why are they important?

Expected answer points:

  • Latency: how long operations take (distinguish slow from failed)
  • Traffic: demand on the system (requests per second)
  • Errors: rate of failures (distinguish 4xx from 5xx)
  • Saturation: how full the system is (CPU, memory, queue depth)
  • Google SRE book defines these as minimum signals every service should monitor
4. How would you design a multi-window burn-rate alerting system?

Expected answer points:

  • Configure multiple time windows: 1h (fast burn, page immediately), 6h (medium burn, warning), 3d (slow leak, investigate)
  • Choose burn rates and paired windows from the SLO policy; Google's example for 99.9% uses 14.4x (1h/5m), 6x (6h/30m), and 1x (3d/6h)
  • Combine with OR logic to fire if any window exceeds threshold
  • Set severity based on burn rate: page for fast burn, warning for medium/slow
5. What is the difference between SLIs, SLOs, and SLAs?

Expected answer points:

  • SLI (Service Level Indicator): the actual metric you measure (e.g., error rate percentage)
  • SLO (Service Level Objective): the target you commit to internally (e.g., 99.9% availability)
  • SLA (Service Level Agreement): contractual commitment to customers, often with penalties
  • A team may set its internal SLO with margin inside the contractual SLA; the service agreement defines remedies and exclusions
6. What metrics would you collect to monitor a PostgreSQL database?

Expected answer points:

  • Connection pool usage (active connections / max connections)
  • Query performance (slow query rate, p95/p99 latency per query type)
  • Replication lag for read replicas
  • Buffer cache hit ratio and memory pressure
  • Disk I/O ( WAL writes, table scans, index usage)
  • Locking and contention metrics
  • Database size and table bloat
7. How do you avoid alert fatigue while ensuring critical issues are paged?

Expected answer points:

  • Every alert must be actionable: someone must know what to do when paged
  • Alert on causes, not symptoms (e.g., database connection pool exhausted, not just "high latency")
  • Use severity levels appropriately: P1 for page-worthy, P2/P3 for warning channels
  • Regularly review alert quality: remove stale alerts, tune thresholds
  • Use alert grouping and inhibition to consolidate related alerts
8. What is blackbox monitoring, and when would you use it over whitebox?

Expected answer points:

  • Blackbox monitoring tests services from outside (synthetic transactions, endpoint health checks)
  • Whitebox monitoring collects internal metrics (application logs, infrastructure metrics)
  • Blackbox catches failures that internal metrics miss (network partitions, DNS issues)
  • Use both: blackbox for user-experience validation, whitebox for root cause analysis
  • Blackbox exporter with Prometheus probes endpoints for availability and response correctness
9. How would you implement capacity planning using metrics?

Expected answer points:

  • Track usage trends over weeks and months using rate comparisons (7d vs 7d offset)
  • Use predict_linear() in PromQL to forecast when resources will saturate
  • Monitor scaling thresholds with tools like KEDA that scale based on Prometheus metrics
  • Set capacity alerts from the resource's measured saturation behavior and the time required to add capacity
  • Consider both horizontal (add replicas) and vertical (bigger instances) scaling paths
10. What considerations are unique to multi-region monitoring deployments?

Expected answer points:

  • Data aggregation strategy: federate regional Prometheus instances to central global view
  • Network latency between regions affects metric freshness; account for scrape intervals
  • Separate SLOs per region vs global SLOs (users care about their region)
  • Alert routing must account for on-call schedules across timezones
  • Remote write costs increase with cross-region bandwidth; compress and batch appropriately
  • Synthetic monitoring from multiple geographic locations catches regional degradation
11. How would you decide on appropriate SLO targets for a new service?

Expected answer points:

  • Start with what users actually experience - not internal implementation details
  • Analyze historical data: availability, latency distributions from existing monitoring
  • Consider business context: revenue impact of downtime, user expectations
  • Set targets tighter than SLAs (if SLAs exist) to give buffer for error budget
  • Iterate and adjust: SLOs should be achievable - unrealistic SLOs create false confidence
  • Align with similar services in your stack for consistency
12. Explain how you would monitor a microservices architecture. What challenges arise that do not exist in monolithic systems?

Expected answer points:

  • Need distributed tracing to understand request flow across services
  • Service mesh metrics (Envoy, Istio) provide sidecar proxy telemetry
  • Challenge: determining which service is the root cause when latency propagates
  • Challenge: network latency between services adds to end-to-end latency
  • Use trace correlation IDs to link requests across service boundaries
  • RED/USE methods apply per service, but need aggregation across service dependencies
  • Container orchestration metrics (Kubernetes) add another monitoring layer
13. What is the difference between Push and Pull metrics collection? When would you choose each?

Expected answer points:

  • Pull model (Prometheus): scraping occurs from a central collector hitting target endpoints
  • Push model (StatsD, Wavefront): agents send metrics to a central collector
  • Pull advantages: easier to target validation, no need to manage agent deployment, easier to detect unmonitored targets
  • Push advantages: works better for short-lived jobs, NAT traversal easier, clients control emission rate
  • Use pull for long-lived services that expose /metrics endpoints
  • Use push for batch jobs, serverless functions, or fire-and-forget workloads
14. How would you design a monitoring system to detect anomalies without relying on static thresholds?

Expected answer points:

  • Use adaptive thresholds based on historical patterns (seasonal variations, growth trends)
  • Implement anomaly detection algorithms: rolling standard deviation, exponential smoothing
  • Leverage machine learning models trained on normal behavior patterns
  • Use multivariate analysis to correlate multiple signals rather than single metrics
  • Start with simpler approaches: deviation from rolling average, rate of change
  • Combine with SLO burn-rate alerts as a complementary approach
15. How do you handle monitoring for services that experience bursty traffic patterns?

Expected answer points:

  • Use longer aggregation windows to avoid false positives during idle periods
  • Set baseline detection that learns traffic patterns over time
  • Separate alert rules for burst windows vs normal operation windows
  • Use percentiles (p95, p99) instead of averages to handle outliers
  • Consider autoscaling correlation: if traffic spikes and latency degrades, alert on the combination
  • Alert on error rates and saturation more than absolute request rates
16. What are recording rules in Prometheus, and when would you use them?

Expected answer points:

  • Recording rules pre-compute frequently needed expressions and save them as new time series
  • Use to reduce query load: expensive aggregations run once, results queried repeatedly
  • Use to reduce cardinality: pre-aggregate high-cardinality data into lower cardinality
  • Essential for dashboard queries that run frequently (every 10-30s)
  • Use for metrics derived from multiple sources that are expensive to join at query time
  • Example: record job:http_requests_total:rate5m instead of computing sum(rate(http_requests_total[5m])) by (job) on every dashboard refresh
17. How would you structure alerting for a service that has both latency-sensitive and throughput-sensitive workloads?

Expected answer points:

  • Separate alert rules for latency SLIs vs throughput SLIs
  • Use different time windows: latency might need faster alerting (1-5 min), throughput might tolerate longer
  • Latency-sensitive path: alert on p95/p99 latency exceeding thresholds, not just averages
  • Throughput-sensitive path: alert when RPS drops below minimum threshold
  • Consider resource saturation (CPU, connections) as leading indicators for both
  • Alert severity might differ: latency breach page immediately, throughput drop warn first
18. Describe how you would implement meta-monitoring (monitoring the monitoring system itself).

Expected answer points:

  • Track Prometheus itself: up/down, TSDB head age, scrape success rates
  • Monitor alertmanager: are alerts being received, are notifications being sent
  • Track metric gaps: use prometheus_tsdb_head_samples to detect compaction issues
  • Build an error budget for monitoring quality: if scrape failures exceed threshold, alert
  • Use federation cross-checks: compare data between federated Prometheus instances
  • External probing: use blackbox exporter to verify monitoring system endpoints
19. What is the relationship between DORA metrics and SLO-based alerting? How would you use them together?

Expected answer points:

  • DORA's current five metrics describe delivery throughput and instability; SLIs and SLOs describe user-facing service reliability
  • Review deployment events beside SLO burn charts to investigate possible impact, but treat timing as a clue rather than proof of cause
  • Use each framework for its own question and compare trends without turning one into a proxy for the other
20. How would you approach setting up alerting for a third-party API dependency?

Expected answer points:

  • Blackbox monitoring: synthetic transactions hitting the third-party endpoint
  • Track latency percentiles from your service's perspective (not just availability)
  • Monitor error rates when calling third-party API (5xx, timeouts, connection failures)
  • Set circuit breaker thresholds: if third-party failure rate exceeds X%, route around it
  • Alert on dependency health rather than just availability - degraded performance matters
  • Use multi-location monitoring to distinguish between your issue and provider issue

Further Reading

Conclusion

Key Takeaways:

  • Start with the four golden signals: latency, traffic, errors, saturation
  • Define SLOs that reflect user experience, not internal metrics
  • Use error budgets to prioritize reliability work
  • Alert on symptoms with context, not raw numbers
  • Every alert should be actionable: someone should know what to do
  • Review and tune alerts regularly to avoid fatigue

Copy/Paste Checklist:

# Availability SLO query
1 - (
  sum(rate(http_requests_total{status=~"5.."}[30d]))
  /
  sum(rate(http_requests_total[30d]))
)

# Error budget burning alert
(
  sum(rate(http_requests_total{service="api-gateway",status=~"5.."}[1h]))
  /
  sum(rate(http_requests_total{service="api-gateway"}[1h]))
) > (1 - 0.999) * 0.1

# P95 latency with context
histogram_quantile(0.95,
  sum(rate(http_request_duration_seconds_bucket{service="api-gateway"}[5m])) by (le)
) > 1

# Dashboard variable template
sum(rate(http_requests_total{service=~"$service"}[$interval])) by (service)

# Alert routing with grouping
route:
  receiver: default
  group_by: ['alertname', 'cluster', 'service']
  group_wait: 30s
  continue: true
  routes:
    - match:
        severity: critical
      receiver: pagerduty

Effective monitoring combines the right metrics, clear SLOs, thoughtful alerts, and actionable dashboards. Start with the four golden signals: latency, traffic, errors, and saturation. Define SLOs that reflect what users actually care about. Build alerts that fire only when someone needs to act.

For deeper observability into distributed systems, our Distributed Tracing guide covers request flow across services. The Prometheus & Grafana guide provides hands-on examples for implementing these patterns.

Category

Related Posts

Designing Production Alerts: Signals and Thresholds

Choose user-focused alert signals, set workload-specific thresholds, and use SLO burn rates without treating examples as universal defaults.

#data-engineering #alerting #monitoring

Database Monitoring: Metrics, Tools, and Alerting

Monitor PostgreSQL with user-facing latency, connection and lock pressure, replication lag, and disk headroom. Includes versioned system-view examples and alert guidance.

#database #monitoring #observability

Alerting in Production: Paging, Runbooks, and On-Call

Set paging policy, maintain actionable runbooks, support healthy on-call rotations, and turn post-incident reviews into concrete follow-up.

#alerting #monitoring #on-call