Prometheus and Alertmanager: Complete Setup for Production Monitoring

Running Prometheus and Alertmanager in production is straightforward until the first real outage at 2 AM. A single-instance Prometheus that worked fine in staging will run out of disk, drop targets during deploys, and flood your Slack with unactionable alerts when you scale to hundreds of nodes. After operating this stack across bare metal, VMs, and Kubernetes for several years, I've learned that production readiness comes down to deliberate choices around storage, discovery, alert routing, and operational hygiene. This guide covers the Prometheus and Alertmanager setup I now use as a baseline for reliable production monitoring, with configuration patterns that hold up under load and on-call pressure.

Designing Prometheus Storage and Retention for Production Workloads

In my experience, storage is where most Prometheus deployments fail first. The default 15-day retention with local TSDB storage is fine for experimentation, but production systems need predictable disk usage and query performance as cardinality grows. I've found that sizing starts with understanding your samples per second and average label cardinality, not just node count. A cluster with 200 exporters each exposing 800 time series at a 15s scrape interval will ingest very differently from one with a handful of high-cardinality application metrics.

For local storage, I provision dedicated SSD volumes and set both retention time and retention size. Retention size is the safer guardrail because it prevents disk pressure from killing the node, even if series churn spikes unexpectedly. I typically run with 30 days retention but cap size at 80% of the volume. Prometheus 2.x and later uses a TSDB with compaction and WAL; you want `storage.tsdb.min-block-duration` and `max-block-duration` at defaults unless you have a clear reason to tune them. What I do tune is the scrape interval for expensive jobs and the evaluation interval for recording rules.

Sizing Local Retention and Planning Remote Write

If you need retention beyond 30-45 days or want to survive single-node failure without losing history, local storage alone is insufficient. Prometheus is not designed for long-term durability by itself. In those cases I pair it with remote write to a long-term store like Thanos, Cortex, or Mimir, keeping Prometheus as a short-term, fast query engine. This keeps local queries snappy while offloading historical analysis and compliance retention. In my experience, trying to force 90+ days onto a single Prometheus instance leads to slow restarts, large WAL replays, and painful compaction.

Production prometheus.yml Skeleton

The following is a stripped-down but production-oriented `prometheus.yml` I use as a starting point. It enforces sane global defaults, persistence settings, and external labels that become critical for federation and alert deduplication.

global:
  scrape_interval: 30s
  evaluation_interval: 30s
  scrape_timeout: 10s
  external_labels:
    cluster: prod-us-central1
    replica: prom-0

storage:
  tsdb:
    retention.time: 30d
    retention.size: 150GB
    no-lockfile: false

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

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']

  - job_name: 'node-exporter'
    kubernetes_sd_configs:
      - role: endpoints
    relabel_configs:
      - source_labels: [__meta_kubernetes_endpoints_name]
        regex: 'node-exporter'
        action: keep
      - source_labels: [__meta_kubernetes_pod_node_name]
        target_label: instance

alerting:
  alertmanagers:
    - static_configs:
        - targets:
          - alertmanager-0:9093
          - alertmanager-1:9093
          - alertmanager-2:9093

Notice the explicit `alertmanagers` block with multiple targets. This allows Prometheus to push alerts to a highly available Alertmanager cluster. For containerized deployments, the Docker Documentation is a useful reference for volume mounts and resource constraints, especially when you need to guarantee WAL persistence across container restarts. If you are running on Kubernetes, the Kubernetes Documentation covers StatefulSets and persistent volumes, which are the correct primitives for running Prometheus as a stateful workload.

Configuring Service Discovery and Relabeling for Dynamic Environments

Static scrape configs don't survive autoscaling, rolling deploys, or ephemeral jobs. Production Prometheus relies heavily on service discovery and relabeling to keep targets accurate without manual edits. I've standardized on `kubernetes_sd_configs` for Kubernetes, `ec2_sd_configs` or `consul_sd_configs` for VMs, and `file_sd_configs` as a fallback for legacy systems that can't expose a native discovery API.

Relabeling is where you enforce consistency. In every environment I relabel to normalize `instance`, `job`, and team ownership labels, drop high-cardinality junk like pod UID or container hash, and keep only the labels that help routing and querying. A common mistake is to ingest every label an exporter offers; this bloats storage and slows queries. I prefer to `labeldrop` or `labelkeep` aggressively at scrape time rather than trying to fix cardinality later.

Relabeling to Control Cardinality and Ownership

Two relabeling patterns have saved me the most operational pain. First, attaching a stable `team` or `service` label from discovery metadata so alerts can be routed correctly without relying on metric content. Second, hashing or dropping request-level labels such as `path`, `user_id`, or `status_code` buckets that explode when aggregating HTTP metrics. If you need per-endpoint visibility, consider aggregating at the application layer or via Custom Prometheus Exporters: Writing Metrics for Application-Specific Monitoring rather than exposing unbounded label values directly.

For blackbox probing or batch jobs, I use `file_sd_configs` with JSON files generated by Terraform or a CMDB sync. This pattern gives you Git-reviewed control over what gets scraped while still being dynamic. The Terraform Documentation has solid examples for templating those discovery files as part of infrastructure provisioning.

Wiring Alertmanager Clustering, Routing Trees, and Inhibition Rules

Alertmanager looks simple, but a single untuned instance will duplicate notifications and wake people for issues they can't act on. A production Alertmanager deployment is a three-node cluster with gossip-based high availability and a carefully designed routing tree. I run three replicas and configure Prometheus to send to all three; Alertmanager deduplicates via gossip. For persistence of silences and notification logs, use a stable mesh and ensure network policies allow TCP on port 9093 and gossip on 9094.

The routing tree is your most important design artifact. It determines who gets paged, via which channel, and when. I structure routes top-down: root route handles default receiver and group intervals, then child routes match on `severity`, `team`, and `cluster` labels. Keep `group_by` focused. Grouping by `alertname` and `cluster` works well; grouping by `instance` or `pod` fragments notifications and defeats deduplication. `group_wait` of 20-30s, `group_interval` of 3-5m, and `repeat_interval` of 3-4h for warning and 1h for critical is a balance I've found sustainable.

Clustering for High Availability and Deduplication

Cluster configuration lives outside `alertmanager.yml` itself; you start each instance with `--cluster.peer` flags pointing to the other members. What matters in the config file is that receivers are idempotent. If two Alertmanagers both fire a webhook, the downstream system should handle deduplication. For PagerDuty or Opsgenie receivers, this is native. For Slack or email, expect duplicate deliveries if clustering is misconfigured.

global:
  resolve_timeout: 5m
  slack_api_url: 'https://hooks.slack.com/services/XXX'

route:
  receiver: 'slack-warnings'
  group_by: ['alertname', 'cluster', 'team']
  group_wait: 30s
  group_interval: 4m
  repeat_interval: 4h
  routes:
    - match:
        severity: critical
      receiver: pagerduty-critical
      continue: true
    - match:
        team: platform
      receiver: slack-platform
      routes:
        - match:
            severity: warning
          receiver: slack-platform-warnings

receivers:
  - name: 'slack-warnings'
    slack_configs:
      - channel: '#alerts-warnings'
        send_resolved: true
        title: '[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .GroupLabels.alertname }}'
        text: '{{ range .Alerts }}{{ .Annotations.summary }} ({{ .Labels.instance }}){{ end }}'

  - name: 'pagerduty-critical'
    pagerduty_configs:
      - service_key: '<pagerduty-integration-key>'
        send_resolved: true
        severity: '{{ if eq .Status "firing" }}critical{{ else }}info{{ end }}'

inhibit_rules:
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname', 'cluster', 'instance']

Using Inhibition to Reduce Storm Noise

Inhibition rules prevent warning alerts from firing when a critical alert covering the same failure is already active. For example, if `InstanceDown` is firing, inhibit `HighCPU` or `KubePodCrashLooping` warnings that are side effects. I've found that two or three well-chosen inhibition rules cut notification volume by 30-40% during major incidents without hiding root cause. Keep `equal` labels tight so you don't suppress alerts for unrelated instances.

Templating Actionable Alerts and Tuning for Signal Versus Noise

Prometheus rules are only as good as their thresholds and context. An alert without a runbook link, query, and clear impact statement will be ignored or, worse, cause an engineer to guess remediation. Every alert I ship must have `summary`, `description`, and `runbook_url` annotations, and must be routed to a team that can actually fix it. A generic alerts file that pages everyone is how on-call burnout starts.

For tuning, prefer `for: 5m` or longer for most alerts to avoid flapping during deployments or transient spikes. Use recording rules to pre-aggregate expensive queries, especially those joining `kube_pod_info` or `container_cpu` metrics. I keep recording rules in a separate file and evaluate them every 2m, then build alerts on the recorded series. This lowers evaluation latency from seconds to milliseconds on large clusters.

groups:
  - name: infrastructure.rules
    interval: 30s
    rules:
      - record: instance:node_cpu_utilisation:avg5m
        expr: 1 - avg without (cpu,mode) (rate(node_cpu_seconds_total{mode="idle"}[5m]))

      - alert: InstanceDown
        expr: up == 0
        for: 5m
        labels:
          severity: critical
          team: platform
        annotations:
          summary: "Instance {{ $labels.instance }} down"
          description: "Job {{ $labels.job }} has been unreachable for >5m (value: {{ $value }})."
          runbook_url: "https://runbooks.internal/instance-down"
          dashboard: "https://grafana.internal/d/instance?var-instance={{ $labels.instance }}"

      - alert: HighCPUUtilisation
        expr: instance:node_cpu_utilisation:avg5m > 0.85
        for: 10m
        labels:
          severity: warning
          team: platform
        annotations:
          summary: "High CPU on {{ $labels.instance }}"
          description: "CPU utilisation >85% for 10m, current {{ $value | humanizePercentage }}."

Metrics alone are rarely enough for root cause. When you correlate alerts with logs, structured context fields shorten investigation dramatically. If you are centralizing logs alongside metrics, review Structured Logging: JSON Format, Context Fields and Log Aggregation to ensure your log fields align with Prometheus labels like `trace_id` or `request_id`. For deeper request flows, pairing metrics with Distributed Tracing with Jaeger and Grafana Tempo: Setup and Best Practices gives you the missing latency breakdown that metrics cannot provide.

Securing and Hardening the Prometheus and Alertmanager Stack

Exposing Prometheus or Alertmanager to the open internet without authentication is a recurring incident I still encounter. Both components historically lacked built-in auth, so you need to front them with a reverse proxy, TLS, and authentication, or use the newer native TLS and basic auth support in Prometheus 2.24+. I terminate TLS at nginx or Traefik, enforce mTLS for scrape traffic where possible, and lock down the admin API.

Network policies and firewall rules should restrict who can scrape and who can push alerts. In Kubernetes, I apply NetworkPolicies that allow scraping only from the Prometheus namespace and allow Alertmanager traffic only from Prometheus replicas. I also disable or protect the `/-/reload` and `/api/v1/admin/tsdb` endpoints. For retention of sensitive alert data, consider that Alertmanager stores silences and notification state on disk; encrypt those volumes and back them up.

Authentication, TLS, and Endpoint Exposure

Enable `web.config.file` for Prometheus and Alertmanager to configure TLS certificates and basic auth users. Rotate scrape credentials via Kubernetes Secrets or Vault Agent, and avoid hardcoding bearer tokens in config files. If you use service monitors via Prometheus Operator, those Secrets can be referenced declaratively and rotated without restarts when mounted correctly. I've found that adding auth at the edge and keeping internal scrape traffic on a private network strikes the right balance between security and operational simplicity.

Operating Day-Two: Upgrades, Backups, and Federation Strategies

Day-two operations determine whether your monitoring remains reliable after six months. For upgrades, I pin Prometheus and Alertmanager versions and test rule evaluation changes in a staging environment that mirrors production label sets. Between major versions, query behavior and flag deprecations can break recording rules, so run `promtool check rules` and `promtool check config` in CI before rolling out.

Backups focus on configuration and metadata, not just TSDB blocks. I snapshot alert rules, dashboards, Alertmanager silences, and the Prometheus config itself to Git. For TSDB data, I snapshot the volume using the storage provider's mechanism and test restore by spinning up a second Prometheus that replays the WAL. Block storage snapshots are far more reliable than trying to `tar` a running TSDB directory. If you also manage centralized log storage, make sure your backup and lifecycle policies align with the guidance in ELK Stack Architecture: Elasticsearch, Logstash and Kibana at Scale, so metrics retention and log retention don't drift into compliance gaps.

Topology Pattern Best For Retention Model Operational Complexity
Single Prometheus + 3-node Alertmanager Small to medium clusters, <500k active series Local TSDB only, 15-30 days Low
HA Pair with Deduplication Require immediate failover without data loss concerns Local TSDB on each replica, deduplicated in query Medium
Federation (Hierarchical) Multi-cluster or multi-region aggregation Edge: 2-6h, Global: 30d aggregated Medium-High
Remote Write to Thanos/Mimir/Cortex Long-term retention, global query, downsampling Local: 2-4h to 7d, Long-term: months to years High

Federation is often misapplied. I only federate when I need a global view across clusters without centralizing every raw sample. In that pattern, edge Prometheus servers keep high-resolution data for a few hours, and a global Prometheus scrapes `/federate` from each edge for aggregated recording rules like `cluster:cpu:ratio` or SLO burn rates. For high-cardinality or long-term needs, remote write to an object-storage-backed system scales better than federation and avoids the cardinality explosion that federated scraping can introduce.

Frequently Asked Questions

How many Prometheus replicas do I need for high availability?

Two replicas with identical configuration are usually sufficient for high availability in most environments. Both scrape the same targets and Alertmanager deduplicates notifications, so you can lose one replica without missing alerts. Add a third only if you need rolling upgrades without losing quorum for remote write or if you run Thanos sidecars with strict quorum requirements.

What scrape and evaluation intervals should I use in production?

Start with 30s scrape and 30s evaluation intervals as defaults. Use 15s only for latency-sensitive or low-cardinality jobs where faster detection matters. For high-cardinality application metrics or expensive exporters like kube-state-metrics, 60s reduces load significantly. Recording rules that feed SLO dashboards can evaluate every 60s without losing useful signal.

How do I stop Alertmanager from spamming Slack during deployments?

Use a combination of `group_wait`, `group_interval`, and `repeat_interval` to rate-limit notifications, add `for: 5m` on alerts to ride out rollouts, and create silences or inhibition rules for known deployment windows. A common pattern is to inhibit `PodCrashLooping` warnings when `KubeDeploymentReplicasUnavailable` is firing, and to set `group_by` so related alerts land in a single Slack message.

When should I move from local storage to remote write with Thanos or Mimir?

Consider remote write when you need retention longer than 30-45 days, global query across clusters, or protection against local disk loss. If restarts take minutes due to WAL replay, queries are slow on historical data, or you need downsampling for cost-efficient long-term storage, a remote-write-based architecture is the cleaner path. Keep local retention short (2-7 days) once remote write is in place to keep restarts fast.

Related Articles

References & Standards: Kubernetes Documentation · Docker Documentation · Terraform Documentation