Server Monitoring and Alerting Setup
Designs a complete server monitoring, alerting, and dashboard plan tailored to your specific infrastructure.
Example run
Generated by Claude Opus 5.5 on November 24, 2026
Inputs used
- Server environment
- Hybrid cloud: AWS EC2 (us-east-1) running a Kubernetes cluster (EKS 1.29) with 3 control-plane-managed node groups, plus 6 standalone EC2 instances (Ubuntu 22.04) for legacy batch jobs and a self-hosted PostgreSQL 15 primary/replica pair. Services are containerized (Docker), deployed via Helm, behind an AWS ALB. No on-prem servers.
- Preferred tooling
- Prometheus + Alertmanager + Grafana (self-hosted in-cluster via kube-prometheus-stack Helm chart), node_exporter and cAdvisor for host/container metrics, Loki + Promtail for log aggregation, Blackbox Exporter for synthetic/endpoint checks. PagerDuty for on-call paging.
- Number of hosts
- ~45 hosts total: 32 EKS worker nodes (m5.xlarge, across 3 node groups: general, batch, memory-optimized) + 6 standalone EC2 instances for batch/cron workloads + 3 PostgreSQL nodes (1 primary, 2 replicas) + 4 bastion/ops utility boxes. Expected to grow to ~60 nodes within 6 months.
- Critical services and SLOs
- 1) checkout-api (Go service, 12 pods): SLO 99.9% monthly availability, p95 latency < 300ms, p99 < 800ms, error rate < 0.5% over 5m. 2) payment-gateway-proxy (calls Stripe): SLO 99.95% availability, p95 latency < 500ms, error rate < 0.1% (hard page on breach). 3) product-catalog-api: SLO 99.5% availability, p95 latency < 400ms. 4) postgres-primary: SLO 99.95% uptime, replication lag < 10s, connection pool utilization < 80%. 5) order-fulfillment-worker (async queue consumer via SQS): SLO: queue backlog < 500 messages, processing lag < 2 min.
- Notification channels
- PagerDuty (primary paging, two escalation policies: "Platform-OnCall-Primary" and "DB-OnCall"), Slack #sre-alerts (all severities, auto-posted via PagerDuty integration) and #incidents (critical-only, with war-room thread auto-created), email digest to sre-team@example.com for daily/weekly summaries, Microsoft Teams channel "SRE-Leadership" for post-incident reports. On-call rotation is weekly, managed in PagerDuty, with secondary escalation to the on-call lead (Priya Nandakumar) after 15 minutes of no ack, then to engineering manager Marcus Webb after 30 minutes.
Observability Design: Hybrid EKS + EC2 Production Stack
This is a complete draft that you can deploy as written. Several decisions depend on details I don't have yet, so I've flagged each assumption inline as [A#]. The questions that would change the design are listed at the end, most important first. Please answer them before we finalize.
0. Architecture at a Glance
┌──────────────── External (outside AWS) ────────────────┐
│ Synthetic checks (Checkly/Grafana SM/CloudWatch │
│ Synthetics in us-west-2) ──► PagerDuty (direct) │
│ Dead-man's switch (Healthchecks.io / DMS) ◄── Watchdog │
└─────────────────────────────────────────────────────────┘
EKS (us-east-1)
├─ monitoring node group (NEW, tainted, 2× r6i.xlarge across 2 AZs)
│ ├─ Prometheus ×2 (HA pair) + Thanos sidecar ──► S3 (long-term)
│ ├─ Alertmanager ×3 (gossip cluster) ──► PagerDuty / Slack / heartbeat
│ ├─ Grafana (OSS) ─► Thanos Query, Loki
│ ├─ Loki (S3 backend, compactor retention) + Loki ruler
│ └─ YACE (CloudWatch: SQS, ALB, EBS, EC2 status checks)
├─ DaemonSets on all node groups: node_exporter, Alloy (replaces Promtail)
└─ kube-state-metrics, Blackbox Exporter, prometheus-adapter / KEDA
Standalone EC2 (batch ×6, Postgres ×3, bastion ×4)
├─ node_exporter (systemd) — scraped via ec2_sd_configs (tag: monitoring=node-exporter)
├─ postgres_exporter on PG hosts (pg_monitor role, local socket)
└─ Alloy (journald + /var/log/postgresql + /var/log/auth.log) ──► Loki via internal NLB
Platform flags to address before rollout:
- EKS 1.29 is out of support. Its standard support ended March 2025 and extended support ended March 2026. AWS force-upgrades clusters that are past extended support, so please confirm your actual version [A1].
- Promtail is end-of-life. It was deprecated in 2025 and reached EOL in early 2026. Plan to migrate to Grafana Alloy using
alloy convert --source-format=promtail. The rest of this design assumes Alloy, but the pipelines are equivalent. - Prometheus needs dedicated nodes. A batch job on the shared node pool can trigger the OOM killer against Prometheus, which leaves you without monitoring at the worst possible moment. The 2 monitoring nodes add to your 45→60 node growth projection.
1. Golden Signals → Concrete Metrics
| Layer | Latency | Traffic | Errors | Saturation |
|---|---|---|---|---|
| Edge (ALB) | TargetResponseTime p95/p99 per target group (YACE) |
RequestCount per TG |
HTTPCode_ELB_5XX_Count (ALB-generated, e.g. no healthy targets), HTTPCode_Target_5XX_Count |
UnHealthyHostCount, RejectedConnectionCount |
| checkout-api / catalog | http_request_duration_seconds_bucket by service, route, le [A2] |
rate(http_requests_total[5m]) by service/route |
code=~"5.." ratio; also Go panic log lines |
HPA current/max replicas, CPU throttling ratio, Go go_goroutines, go_sched_latencies_seconds, DB client pool wait (go_sql_wait_duration_seconds_total, go_sql_in_use_connections) |
| payment-gateway-proxy | Own request latency + upstream Stripe latency (stripe_request_duration_seconds by endpoint) [A3] |
Requests/s; Stripe calls/s | Proxy 5xx and timeouts, Stripe 5xx/429. Card declines are excluded (business outcome, not error) | Circuit-breaker state, Stripe 429 rate (rate-limit headroom), outbound connection pool |
| PostgreSQL | Query latency (pg_stat_statements mean/max exec time, top-N), replication replay lag |
rate(pg_stat_database_xact_commit+rollback) TPS, rows fetched/returned |
rate(pg_stat_database_xact_rollback), deadlocks, FATAL/PANIC logs, WAL archive failures |
Connections ÷ max_connections, replication lag (s and bytes), disk %, EBS queue length/IOPS vs provisioned, XID age, replication-slot retained WAL |
| order-fulfillment-worker (SQS) | ApproximateAgeOfOldestMessage (processing lag); in-app job_duration_seconds |
NumberOfMessagesSent vs NumberOfMessagesDeleted |
Worker processing failures (app counter), DLQ ApproximateNumberOfMessagesVisible |
ApproximateNumberOfMessagesVisible (backlog), worker replica count vs KEDA max |
| Kubernetes | Pod startup time, scheduling latency | Pods/deployments churn | CrashLoopBackOff, OOMKilled, failed probes | Node allocatable vs requests, pods/node vs max-pods (58 on m5.xlarge with default VPC CNI), pending pods |
| Hosts (all 45) | Disk await (node_disk_read/write_time_seconds_total ÷ ops) |
Network bytes/pps | NIC errors/drops, ENA *_allowance_exceeded, EC2 status checks |
CPU (incl. steal), MemAvailable, PSI (node_pressure_*), disk %, inodes, conntrack |
Why ALB and app metrics: app metrics go silent when pods are dead or unreachable. The ALB still sees the failure (502/503 with no healthy targets) and still counts the traffic.
2. System Metrics, Service Health, Logs
2.1 System metrics (node_exporter everywhere)
- Enable these collectors:
systemd(standalone EC2),pressure,ethtool(ENA allowance counters, which matter on m5),textfile(batch job results),processes,filesystem. - On k8s nodes, alert on symptoms: pressure, evictions, throttling. Raw CPU% on a bin-packed k8s node is normal and is not paged on.
- On standalone EC2 and PG hosts, classic USE alerts apply: CPU, memory, disk, network.
- EBS volume health comes from YACE using
VolumeQueueLength,VolumeReadOps/WriteOpsvs provisioned IOPS, andBurstBalanceif any volume is gp2 [A4].
2.2 Service/process health
- k8s workloads: kube-state-metrics provides replicas available vs desired, restarts,
last_terminated_reason, HPA status, and PDB disruptions allowed. - Standalone daemons:
node_systemd_unit_state{state="failed"}, with a whitelist of units (postgresql@15-main,cron,node_exporter,alloy, batch services). - Batch/cron jobs: each job wrapper writes
batch_job_last_success_timestamp_seconds{job_name}andbatch_job_last_exit_codeto/var/lib/node_exporter/textfile/*.promusing an atomicmv. Alerts fire on freshness, not just failure: a job that never ran emits no failure signal. Avoid Pushgateway for this, because stale pushes look healthy. - Synthetics:
- Blackbox
http_2xxprobes run in-cluster against internal service URLs and the public ALB hostname. - An external check, outside us-east-1 and outside the cluster, hits
/healthzon checkout and catalog plus a synthetic "add to cart → quote" flow (Phase 3). It pages PD directly, so it still works when the cluster is down.
- Blackbox
- Meta-monitoring: the always-firing
Watchdogalert goes to a dead-man's switch, which pages PD if the heartbeat stops for 5 min. This catches the case where the in-cluster stack dies along with the cluster.
2.3 Log/event monitoring (Loki + Alloy)
- Sources:
- Container stdout from all namespaces.
- journald on EC2.
/var/log/postgresql/*.logwithlog_min_duration_statement=500ms,log_lock_waits=on,log_autovacuum_min_duration=1s,log_checkpoints=on./var/log/auth.logon bastions.- Kubernetes events via Alloy
loki.source.kubernetes_events.
- Labels: keep them low-cardinality:
cluster, namespace, app, container, host, level. Never usepod_ip,user_id, ortrace_idas labels; use structured metadata or line filters instead. - Loki ruler alerts. Logs complement metrics here; they never replace SLO alerts:
sum by (app) (count_over_time({namespace="prod"} |= "panic:" [5m])) > 0: Go panics.count_over_time({job="postgres"} |~ "PANIC|could not write|No space left" [5m]) > 0pages DB.count_over_time({job="postgres"} |= "FATAL" [5m]) > 20goes to Slack. This is usually auth failures or too many connections.{job="journal"} |~ "EXT4-fs error|I/O error|Out of memory: Killed"goes to Slack, or pages DB if it is on a PG host.- Bastion
sshdfailed-auth spikes and successful root/unknown-user logins go to Slack. Also route them to your security channel if you have one [A5].
- PCI hygiene: payment-gateway-proxy is almost certainly in PCI scope [A6].
- Drop or redact PAN-like patterns at the Alloy stage (
stage.replacewith a Luhn-candidate regex) as defense-in-depth. - Retain proxy and bastion logs for 12 months, with 3 months immediately queryable (PCI DSS 10.5.1).
- Drop or redact PAN-like patterns at the Alloy stage (
3. Alerting Philosophy, Thresholds, and Anti-Fatigue Rules
3.1 Severity tiers
| Severity | Meaning | Delivered to | Expected response |
|---|---|---|---|
critical |
User-facing SLO at imminent risk, payments impacted, or data-integrity risk | PagerDuty high urgency (phone/SMS/push). PD posts to #sre-alerts and #incidents with war-room thread | 24/7, ack ≤ 5 min target |
warning |
Needs a human within the business day; budget eroding slowly; capacity trending | Alertmanager → Slack #sre-alerts (no PD incident) [A7] | Business hours, ticket |
info |
Context and trends | Dashboards + daily digest only | None |
3.2 Anti-fatigue and anti-flapping mechanisms
- Page on symptoms, not causes.
- Only these page: SLO burn, hard SLO breaches, data-integrity/HA risk, and loss of monitoring.
- CPU, memory, and pod restarts on stateless services never page by themselves.
- Multi-window, multi-burn-rate SLO alerts (Google SRE Workbook).
- The long window proves significance and the short window proves the problem is still happening.
- This gives fast detection plus fast reset, with no flapping on spikes.
- Minimum-traffic guards. At 3 a.m., 1 error in 20 requests is a 5% error rate. Every ratio alert requires a minimum request rate, or falls back to an absolute error count.
for:durations and hysteresis.- Warning thresholds are lower and slower; critical thresholds are higher and faster.
keep_firing_for(Prometheus ≥ 2.42) on hard-page alerts prevents resolve/re-trigger storms.
predict_linearfor capacity. Disk alerts fire on "fills in 4h", not on "85% full on a 2 TB volume that grows 1 GB/month".- Grouping and inhibition.
- Alerts are grouped by
alertname, service, cluster. - Critical inhibits matching warnings.
- A node being down inhibits pod-level warnings on that node.
- Postgres primary down inhibits replication-lag and connection alerts.
- Alerts are grouped by
- Noise tuning of kube-prometheus-stack defaults.
- Disable scraping of the EKS-managed control plane (etcd, scheduler, controller-manager). It is unreachable on EKS and causes permanent
TargetDown. - Disable kube-proxy scraping unless you rebind its metrics to
0.0.0.0. - Turn off
KubeCPUOvercommitandKubeMemoryOvercommit; capacity is covered by dashboards.
- Disable scraping of the EKS-managed control plane (etcd, scheduler, controller-manager). It is unreachable on EKS and causes permanent
- Every page carries
runbook_urlanddashboard_url. An alert without a runbook does not ship. - Monthly alert review.
- Any page that did not lead to action gets tuned or demoted.
- Target < 2 pages per on-call shift-day on average.
- Track MTTA and pages per week on the Alert Health dashboard.
3.3 Reconciling your stated SLO numbers with alert behavior
- checkout-api "error rate < 0.5% over 5m": for a 99.9% SLO, 0.5% is a 5× burn, which exhausts the monthly budget in about 6 days.
- I've set the raw 0.5%/5m breach as a warning.
- Paging happens on 14.4× burn (fast) and 6× burn (slow).
- If you want 0.5%/5m to page, say so. It will page more often, mostly on transient blips [Q3].
- payment-gateway-proxy "< 0.1% hard page": implemented as specified. It is a 5m window with a 2m
forand a minimum-traffic guard; below the guard it falls back to ≥ 10 errors in 5m.- Because the 99.95% budget is only 0.05%, a fast burn of 14.4× works out to a 0.72% error rate, so the 0.1% rule always fires first.
- Burn-rate rules are still kept for budget reporting and slow-burn tickets.
- Histogram buckets: Go's
client_golangdefault buckets (.25, .5, 1, …) contain no 0.3 or 0.8.histogram_quantilewould interpolate p95 between 250 and 500 ms, which makes the 300 ms alert imprecise.- Add buckets
0.1, 0.2, 0.3, 0.4, 0.5, 0.8, 1, 2or enable native histograms [A2].
3.4 Metric + Alert Table
Windows are written as threshold / for. "Page-P" means the PD service on escalation policy Platform-OnCall-Primary, and "Page-DB" means DB-OnCall. "Slack" means #sre-alerts.
Service SLOs
| Metric | Source | Warning | Critical | Action |
|---|---|---|---|---|
| checkout-api error-budget burn (5xx ratio, 99.9%) | App metrics via ServiceMonitor | 3× burn over 1d & 2h, or 1× over 3d & 6h → Slack + ticket | 14.4× over 1h & 5m (for 2m) or 6× over 6h & 30m (for 15m) → Page-P |
Runbook: recent deploy? → helm rollback; check PG, payment, ALB panels |
| checkout-api raw error ratio | App | > 0.5% / 5m (traffic ≥ 1 rps) → Slack | (covered by burn rate) | Early signal; check route breakdown |
| checkout-api p95 / p99 latency | App histogram | p95 > 300ms / 10m | p99 > 800ms / 10m or p95 > 300ms / 30m → Page-P | Check DB pool wait, PG slow queries, CPU throttling, HPA at max |
| payment-gateway-proxy error ratio | App (excl. declines) | > 0.05% / 10m → Slack | > 0.1% / 5m, for 2m, keep_firing_for 10m (or ≥ 10 errors/5m at low traffic) → Page-P hard |
Split own vs Stripe (upstream label); check status.stripe.com; verify circuit breaker; no auto-restart |
| payment-gateway-proxy burn (99.95%) | App | 3× over 1d & 2h → Slack | (superseded by 0.1% rule) | Budget reporting |
| payment-gateway-proxy p95 latency | App + Stripe upstream histogram | > 400ms / 10m | > 500ms / 15m → Page-P | If upstream Stripe latency is the cause, it's informational for vendor escalation; own latency → scale/investigate |
| Stripe 429 rate | App | > 0 sustained 10m → Slack | > 1% of Stripe calls / 5m → Page-P | Rate-limit headroom; check retry storms |
| product-catalog-api burn (99.5%) | App | 6× over 6h & 30m → Slack + ticket | 14.4× over 1h & 5m → Page-P | Lower tier: only fast burn pages |
| product-catalog-api p95 | App | > 400ms / 15m | > 800ms / 15m → Page-P | Cache hit rate, DB, pod saturation |
| ALB 5xx (ELB-generated) / unhealthy hosts | YACE (CloudWatch) | UnHealthyHostCount > 0 / 5m |
ELB 5xx > 1% of requests / 5m → Page-P | Catches "no pods" cases invisible to app metrics |
External synthetic /healthz (checkout, catalog) |
External synthetic provider → PD | 1 location failing / 3m | ≥ 2 locations failing / 2m → Page-P | Independent of cluster health |
| TLS cert expiry | Blackbox probe_ssl_earliest_cert_expiry |
< 21d → Slack | < 7d → Page-P (business-hours urgency) | ACM auto-renew failure? DNS validation record? |
PostgreSQL (all critical alerts go to Page-DB)
| Metric | Source | Warning | Critical | Action |
|---|---|---|---|---|
Primary availability (absent(pg_replication_is_replica == 0)) |
postgres_exporter | — | No primary reachable / 1m → Page-DB | Runbook: failover decision is human (unless Patroni) [Q2] |
Split brain (count(pg_replication_is_replica == 0) > 1) |
postgres_exporter | — | > 1 primary / 1m → Page-DB | Fence the old primary immediately |
Replication lag (pg_replication_lag_seconds on replicas) |
postgres_exporter | > 5s / 2m | > 10s / 3m → Page-DB | Check replica I/O, long queries on replica (hot_standby_feedback), network |
Streaming replicas connected (pg_stat_replication count on primary) |
postgres_exporter (custom query) | < 2 / 5m | 0 / 2m → Page-DB | No replica means no HA |
Connection utilization (Σ pg_stat_activity_count ÷ max_connections) |
postgres_exporter | > 70% / 10m | > 80% / 5m → Page-DB | Find the offending app (by datname, usename); check KEDA worker count; PgBouncer [Q2] |
| Longest transaction / idle-in-txn age | postgres_exporter (pg_stat_activity_max_tx_duration) |
> 5m / 5m | > 30m / 5m → Page-DB | Blocks vacuum and causes bloat; terminate after confirming owner |
| XID wraparound age | Custom query age(datfrozenxid) |
> 1.0B | > 1.5B → Page-DB | Manual VACUUM FREEZE plan |
| Replication slot retained WAL | Custom query on pg_replication_slots |
Inactive slot > 30m or > 10 GB | > 50 GB or data disk predicted full in 4h → Page-DB | Classic disk-fill cause; drop or repair the slot consumer |
| WAL archiving | pg_stat_archiver_failed_count, last_archived_age |
Failures > 0 / 15m | Last successful archive > 30m → Page-DB | PITR at risk; check S3/WAL-G credentials [Q2] |
| Last successful base backup age | Backup tool metric (textfile) | > 26h | > 50h → Page-DB (low urgency overnight) | Re-run backup; check tool logs |
| PG data volume space | node_exporter on PG hosts | Predicted full in 24h or < 20% | Predicted full in 4h or < 10% → Page-DB | Slots, WAL, bloat, log dir |
| EBS saturation (PG volume) | YACE VolumeQueueLength, IOPS vs provisioned |
IOPS > 85% of provisioned / 30m | — (ticket) | Raise gp3 IOPS/throughput |
| Deadlocks | pg_stat_database_deadlocks |
> 5 / 10m → Slack | — | App lock ordering |
Queue (order-fulfillment-worker)
| Metric | Source | Warning | Critical | Action |
|---|---|---|---|---|
SQS backlog (ApproximateNumberOfMessagesVisible) |
YACE | > 300 / 10m | > 500 / 10m → Page-P | Is KEDA at max? Worker errors? DB slow? |
Processing lag (ApproximateAgeOfOldestMessage) |
YACE (plus in-app gauge, Phase 2) | > 60s / 5m | > 120s / 5m → Page-P | Same; note CloudWatch delay (§10) |
| Stalled consumer (backlog > 0 and deleted == 0) | YACE | — | 10m → Page-P | Workers crashed or poisoned message; check DLQ |
| DLQ depth | YACE | > 0 → Slack | > 50 or growing for 30m → Page-P | Inspect and redrive manually; never auto-purge |
Kubernetes
| Metric | Source | Warning | Critical | Action |
|---|---|---|---|---|
| Critical deployment available replicas vs desired | kube-state-metrics | < 100% / 10m | checkout/payment < 70% / 5m → Page-P | Rollout stuck? Node loss? PDB? |
| CrashLoopBackOff / restarts | kube-state-metrics | > 3 restarts / 15m → Slack | (escalates via the replicas rule) | Logs → last deploy |
| OOMKilled | kube-state-metrics last_terminated_reason |
Any in 1h → Slack | — | Raise memory request/limit, check leak |
| CPU throttling ratio | cAdvisor | > 25% of periods / 15m on critical services | — | Raise/remove CPU limits; Go ≥ 1.25 honors cgroup limits for GOMAXPROCS (else use automaxprocs) |
| Node NotReady | kube-state-metrics | 1 node / 5m | > 10% of a node group / 5m → Page-P | AZ issue? Autoscaler? |
| Pending / unschedulable pods | kube-state-metrics | > 0 / 15m | Critical namespace pending / 10m → Page-P | Capacity, max-pods, taints |
| HPA at max replicas | kube-state-metrics | At max / 15m → Slack | — (latency SLO will page) | Raise max; check DB connection headroom first |
| Pods per node vs max-pods | kube-state-metrics | > 85% → Slack | — | Enable VPC CNI prefix delegation |
| ENA allowance exceeded (bw/pps/conntrack) | node_exporter ethtool | rate > 0 / 15m → Slack | — | Upsize instance or spread pods |
| Conntrack utilization | node_exporter | > 75% / 10m | > 90% / 5m → Page-P | Packet drops imminent |
Hosts
| Metric | Source | Warning | Critical | Action |
|---|---|---|---|---|
| Memory available | node_exporter | < 10% / 15m | < 5% / 5m on PG/batch hosts → Page (DB for PG hosts, P otherwise) | Swap/OOM risk; k8s nodes: warning only (kubelet evicts) |
| Disk space (non-PG) | node_exporter | Predicted full in 24h or < 15% | Predicted full in 4h and < 10% → Page-P | Logrotate, docker prune on batch hosts |
| Inodes | node_exporter | < 15% | < 5% → Page-P | Batch temp files |
Disk I/O busy (rate(io_time)) |
node_exporter | > 80% / 30m → Slack | — | Correlate with EBS metrics |
| CPU busy / steal (standalone hosts only) | node_exporter | > 85% / 30m; steal > 10% / 15m | — | Batch scheduling, right-size |
Host unreachable (up{job="node-exporter"} == 0) |
Prometheus | Batch/bastion host / 5m | PG host / 2m → Page-DB | Check EC2 status checks |
| EC2 status check failed | YACE / CloudWatch alarm | — | 5m → auto-recover + Slack | §6 automation |
| Clock offset | node_timex_offset_seconds |
> 50ms | > 500ms → Slack (Page-DB if on PG) | chrony / Amazon Time Sync |
| Batch job freshness | textfile collector | Last success > 1.5× schedule | > 3× schedule (or SLA-critical job missed) → Page-P [Q10] | Re-run, check logs |
| Failed systemd units (whitelisted) | node_exporter systemd | Any / 5m → Slack | postgresql* failed → Page-DB |
journalctl -u |
Logs (Loki ruler)
| Metric | Source | Warning | Critical | Action |
|---|---|---|---|---|
| Go panics | Loki ruler | Any / 5m → Slack | (crash/replica alerts escalate) | Stack trace → owner |
PG PANIC / No space left / could not write |
Loki ruler | — | Any / 5m → Page-DB | Data integrity |
| Kernel OOM / EXT4 / I/O errors | Loki ruler (journald) | Any → Slack | On PG host → Page-DB | Hardware/EBS issue |
| Bastion auth anomalies | Loki ruler | > 20 failures / 5m → Slack (+ security) | — | Review source IPs |
Monitoring the monitoring
| Metric | Source | Warning | Critical | Action |
|---|---|---|---|---|
| Watchdog heartbeat | Alertmanager → dead-man's switch | — | Missing / 5m → Page-P (via DMS → PD) | Monitoring is down; check cluster |
| Alertmanager notification failures | alertmanager_notifications_failed_total |
> 0 / 10m → Slack | PD integration failing / 10m → heartbeat also fails | Rotate keys, check egress |
| Prometheus rule eval failures / TSDB head series | Prometheus self-metrics | Eval failures > 0 / 10m; head series > 1.5M | Prometheus OOM restarts > 2 / 1h → Page-P | Cardinality hunt (topk by metric name) |
| Loki ingestion / Alloy dropped entries | Loki/Alloy self-metrics | > 0 / 15m → Slack | — | Rate limits, labels |
4. Routing and Escalation
4.1 Alertmanager routing
team="db"+critical→ PD integration key for the "PostgreSQL" service, which uses escalation policy DB-OnCall.critical(everything else) → PD key for the "Platform – Production" service, which uses Platform-OnCall-Primary. In Phase 2, split this into one PD service per business service (checkout, payments, catalog, fulfillment) on the same escalation policy. That gives per-service MTTA/MTTR analytics and service-level maintenance windows.warning→ Slack #sre-alerts directly from Alertmanager. It creates no PD incident, so it cannot page and doesn't skew PD analytics [A7/Q4].Watchdog→ dead-man's-switch webhook every 1m.- Timing:
group_wait 30s(10s for critical),group_interval 5m,repeat_interval 1hfor critical and 12h for warning.
4.2 PagerDuty configuration
- Platform-OnCall-Primary
- L1: weekly primary rotation, notified immediately.
- L2: Priya Nandakumar, if unacked at 15 min.
- L3: Marcus Webb, if unacked at 30 min after trigger (L2 timeout = 15 min). Please confirm "30 min" means from trigger, not 30 min after Priya [Q5].
- Repeat the policy 2× if still unacked.
- DB-OnCall: same structure with the DB rotation as L1. I've assumed Priya and Marcus are also L2/L3 for DB [Q5].
- Payment hard-page recommendation: 15 minutes unacked is a long time for a payments outage. Consider a separate escalation policy for the payments service with 5-min L1→L2 timeouts, or add a secondary on-call rotation as L2 so Priya becomes L3.
- Ack timeout: 30 min re-trigger, so an acked-and-forgotten incident re-alerts.
- Event Orchestration: map
details.priorityfrom alert labels to PD priority. P1 covers payment hard-page, checkout fast burn, PG primary down, and split brain; P2 covers the rest of critical. - Slack:
- The PD Slack integration posts all PD incidents to #sre-alerts.
- A PD Incident Workflow triggered on P1/P2 or high-urgency posts to #incidents and creates the war-room thread, with responders, runbook, and dashboard links pre-filled.
- Deliberate double-page: a PG primary outage pages DB-OnCall (cause) and Platform (checkout symptom). Both responders are genuinely needed, so I don't inhibit across teams. The runbook tells Platform to check the PG incident first.
4.3 Non-paging channels
-
Daily/weekly email digest to sre-team@example.com. Alertmanager isn't built for digests, and Grafana OSS lacks scheduled reports (that feature is Enterprise/Cloud). Use a small CronJob that queries:
- Prometheus
ALERTSand the SLO recording rules (budget remaining, burn per service), - PD's analytics API (pages, MTTA, MTTR, top noisy alerts).
It renders HTML and sends via Amazon SES.
- Prometheus
-
Teams "SRE-Leadership": post-incident reports are posted from the PD postmortem step through a Teams Workflows webhook. Legacy O365 connectors are retired. Keep this out of the alert path entirely.
5. Dashboards, Retention, Capacity Planning
| Dashboard | Audience | Key panels / KPIs | Question it answers |
|---|---|---|---|
| 1. SLO Overview | Everyone, leadership | Per service: 30d availability, error budget remaining (%), current burn rate (1h/6h), latency SLI (% requests < threshold), budget burn-down chart | "Are we meeting our promises, and how much risk can we take this month?" |
2. Service RED (templated $service) |
On-call | RPS by route, error ratio by route/code, p50/p95/p99 vs SLO line, pods ready vs desired, HPA, CPU throttling, memory vs limit, DB pool wait, deploy annotations | "Is this service healthy, and did the last deploy change anything?" |
| 3. Payments | On-call, payments team | Proxy vs Stripe upstream latency, errors by Stripe error type, 429s, circuit-breaker state, decline rate (business KPI, separate from errors) | "Is it us or Stripe?" |
| 4. PostgreSQL | DB on-call | Primary/replica topology (pg_replication_is_replica), lag (s + bytes), connections by db/user/state vs max, TPS, cache hit ratio, top queries (pg_stat_statements), locks/blocked, XID age, slot WAL, archiver status, backup age, disk + EBS IOPS/throughput vs provisioned |
"Is the DB healthy and is HA intact?" |
| 5. Queue / Fulfillment | On-call | Backlog, age of oldest, sent vs deleted rate, DLQ depth, worker replicas vs KEDA max, processing duration, failure rate | "Are orders flowing, and how far behind are we?" |
| 6. Kubernetes Cluster & Capacity | SRE | Per node group: allocatable vs requested vs used CPU/mem, pods/node vs 58, pending pods, autoscaler events, node count trend, top-10 over-requesting workloads | "Do we have room, and are requests realistic?" |
7. Host USE (Node Exporter Full, filtered by role) |
On-call | CPU/steal, mem/PSI, disk space/IO/await, network/ENA allowance, conntrack | "Is this box the problem?" |
| 8. Batch & Cron | SRE | Last success per job, duration trend, exit codes, schedule adherence heatmap | "Did the nightly jobs run?" |
| 9. Capacity Planning (30/90/180-day) | SRE, leadership | predict_linear 30/90d for PG disk, node count, Prometheus series, Loki ingest GB/day; peak RPS per service vs pod count; cost per node group (OpenCost, Phase 3) |
"When do we hit limits on the road to 60 nodes?" |
| 10. Alert Health & Meta-monitoring | SRE lead | Pages/week by alert, % actionable, MTTA/MTTR, noisiest alerts, Prometheus/Loki/Alertmanager self-health, scrape failures | "Is our alerting trustworthy and humane?" |
5.1 Retention
| Data | Hot | Long-term | Notes |
|---|---|---|---|
| Prometheus (local) | 15d, retentionSize 150 GB |
— | HA pair |
| Thanos (S3) | raw 30d | 5m downsampled 180d, 1h downsampled 2y | Year-over-year capacity and SLO history. Amazon Managed Prometheus is a lower-ops alternative [Q11] |
| Loki — general app/system logs | 30d | — | Compactor retention |
| Loki — payment-proxy + bastion auth + PG | 90d queryable | 12 months (S3 lifecycle → Glacier IR after 90d) | PCI 10.5.1 [A6] |
| PD incidents / postmortems | Indefinite | — |
5.2 Prometheus sizing estimate (verify after Phase 1)
- Active series today: about 500–700k. That breaks down as node_exporter at ~1k/node, cAdvisor plus kube-state-metrics at roughly 150–250 series per pod, and app histograms.
- Active series at 60 nodes: about 0.9–1.1M.
- Memory: roughly 8–12 GiB RAM per replica.
- Disk: about 3–5 GB/day at a 30s scrape interval, so 15d fits in a 200 Gi gp3 PVC.
- Monitoring nodes: 2× r6i.xlarge (32 GiB) is sufficient.
- Cardinality guard: set
sample_limitper ServiceMonitor, and drop high-cardinality cAdvisor series such ascontainer_tasks_state,container_memory_failures_total, and per-interface network series for pause containers.
5.3 Capacity planning views
- Node group headroom: (allocatable − requests) per group, with a "nodes needed at current growth" projection.
- Max-pods ceiling: 32 nodes × 58 pods. Enable prefix delegation before growth makes this the binding constraint.
- PG disk days-to-full:
predict_linearover 30d. - PG connection headroom: max_connections − Σ(app pool max × replicas). This is critical before raising any HPA or KEDA max.
- Monitoring self-capacity: series growth, Loki GB/day.
6. Automated Responses (Safe Only)
| Trigger | Automation | Why it's safe / guardrails |
|---|---|---|
| CPU/RPS on checkout, catalog, payment-proxy | HPA (min 12 for checkout; scale on CPU or RPS via prometheus-adapter) + PDB minAvailable: 75% |
Bounded min/max; stabilization window 300s on scale-down to prevent thrash |
| SQS backlog | KEDA aws-sqs-queue scaler on order-fulfillment-worker (target ~50 msgs/pod) |
maxReplicaCount is capped by PG connection headroom. Otherwise autoscaling turns a backlog into a DB outage |
| Unschedulable pods | Cluster Autoscaler or Karpenter per node group | Node group max sizes are set to the 60-node plan; alert on reaching max |
| Process hang/crash | Liveness + startup probes (k8s); systemd Restart=on-failure with StartLimitBurst for exporters and batch daemons |
Liveness checks only process health. They never check DB or Stripe dependencies, which would cause restart storms |
| EC2 system status check failure | CloudWatch alarm with EC2 recover action on standalone and PG hosts |
Same instance ID, IP, and EBS. Notifies Slack. Use on replicas freely; on the primary, recovery is safe because it doesn't promote anything |
| Batch host disk > 85% | Scheduled docker image prune -af --filter until=72h, logrotate, journald SystemMaxUse= |
Only known-safe paths; never on PG hosts |
| Long-running/idle transactions | Server-side settings, not alert-driven kills: idle_in_transaction_session_timeout=10min, per-role statement_timeout for app roles |
Declarative and predictable; excludes replication/maintenance roles |
Deliberately not automated:
- Postgres failover from an alert. This risks split brain. The exception is Patroni with a proper DCS [Q2].
- Restarting payment-proxy on error rate. A Stripe outage would trigger a restart storm while the dependency is still down.
- Scaling on error rate. Errors don't mean you need more capacity.
- DLQ purge or redrive. Messages represent orders, so a human decides.
- Rolling back deploys automatically. Defer this to Phase 3 with Argo Rollouts / Flagger analysis using the same SLO queries, canary-only.
7. Rollout Plan
Phase 1: Must-Have (weeks 0–3) — "Never miss a real outage"
- Create the dedicated monitoring node group. Run Prometheus ×2 and Alertmanager ×3 with anti-affinity across AZs.
- Disable EKS control-plane and kube-proxy scrapes, and prune the noisy defaults.
- Set up Watchdog → dead-man's switch → PD and external synthetics → PD.
- Bring the EC2 fleet under monitoring:
- node_exporter on all 13 standalone hosts, scraped via
ec2_sd_configs(IRSA role, SG rules for 9100 and 9187). - postgres_exporter on all 3 PG hosts.
- node_exporter on all 13 standalone hosts, scraped via
- Deploy YACE for SQS, ALB, EBS, and EC2 status checks.
- Fix the histogram buckets in checkout and payment-proxy [A2], and confirm card declines aren't counted as 5xx.
- Add SLO recording rules and page-tier alerts for checkout, payment (hard page), PG primary/lag/connections/disk, SQS backlog/lag/stall, and ALB.
- Configure Alertmanager routing, the PD services and escalation policies, and the #incidents workflow.
- Write runbooks for every page-tier alert.
- Run a game day covering:
- killing a checkout pod set,
- stopping PG on a replica,
- pausing the worker,
- blocking egress to Stripe in staging.
Phase 2: Should-Have (weeks 3–8) — "Understand and prevent"
- Add Thanos for long-term metrics, and move Loki to an S3 backend with per-stream retention.
- Migrate Promtail to Alloy on all hosts.
- Add Loki ruler alerts and PAN redaction.
- Complete the deep PG checks: XID age, replication slots, archiver, backups,
pg_stat_statements. - Enable VPC CNI prefix delegation, and add the ENA allowance and conntrack alerts.
- Deploy KEDA for the worker, and tune HPA and PDBs.
- Instrument batch jobs with textfile metrics and add freshness alerts.
- Build dashboards 1–8 as code (Grafana provisioning / Grafonnet in git).
- Split PD services per business service, and ship the daily/weekly digest job.
- Add the in-app oldest-message-age gauge for the worker, which removes the CloudWatch delay.
- Start the monthly alert-quality review.
Phase 3: Nice-to-Have (weeks 8–16) — "Optimize and automate"
- Generate SLOs with Sloth or Pyrra (including latency-SLI burn rates), replacing the hand-written rules.
- Add tracing with Tempo and exemplars linking latency panels to traces; this matters most for checkout → payment → Stripe.
- Add a synthetic transaction for the checkout flow, and an external Stripe-path canary using test mode.
- Add OpenCost dashboards and capacity forecasting for the 60-node plan.
- Add canary analysis and auto-rollback with Argo Rollouts/Flagger using the SLO queries.
- Add PD Runbook Automation for diagnostic-only actions: gather pod logs, top PG queries, and SQS stats into the incident.
- Run chaos experiments with AWS FIS (AZ loss, PG replica loss) to verify the alerts fire.
8. Config Snippet — values-prod.yaml for kube-prometheus-stack
This was written against recent kube-prometheus-stack (Prometheus ≥ 2.42 / v3, Alertmanager ≥ 0.26, prometheus-operator ≥ 0.70). Key paths occasionally move between chart majors, so diff it against helm show values for your version.
# values-prod.yaml — kube-prometheus-stack
# Assumptions: app metrics named http_requests_total / http_request_duration_seconds_bucket
# with labels {service, code}; YACE deployed separately exporting aws_sqs_* with
# dimension_QueueName; EC2 hosts tagged monitoring=node-exporter, role=<postgres|batch|bastion>,
# pg_cluster=pg-main on PG hosts.
defaultRules:
create: true
disabled:
KubeCPUOvercommit: true # capacity handled via dashboards, not pages
KubeMemoryOvercommit: true
# EKS control plane is AWS-managed and not scrapeable -> avoid permanent TargetDown noise
kubeEtcd: { enabled: false }
kubeScheduler: { enabled: false }
kubeControllerManager: { enabled: false }
kubeProxy: { enabled: false } # EKS binds metrics to 127.0.0.1 by default
prometheus:
serviceAccount:
annotations:
# IRSA role with ec2:DescribeInstances (for ec2_sd_configs)
eks.amazonaws.com/role-arn: arn:aws:iam::<ACCOUNT_ID>:role/prometheus-ec2-sd
prometheusSpec:
replicas: 2
retention: 15d
retentionSize: 150GB
scrapeInterval: 30s
evaluationInterval: 30s
externalLabels:
cluster: prod-use1
ruleSelectorNilUsesHelmValues: false
serviceMonitorSelectorNilUsesHelmValues: false
podMonitorSelectorNilUsesHelmValues: false
probeSelectorNilUsesHelmValues: false
nodeSelector: { workload: monitoring }
tolerations:
- { key: dedicated, operator: Equal, value: monitoring, effect: NoSchedule }
podAntiAffinity: hard
resources:
requests: { cpu: "1", memory: 8Gi }
limits: { memory: 14Gi }
storageSpec:
volumeClaimTemplate:
spec:
storageClassName: gp3
accessModes: ["ReadWriteOnce"]
resources: { requests: { storage: 200Gi } }
# Phase 2: Thanos sidecar -> S3 (key layout varies by chart version)
# thanos:
# objectStorageConfig:
# existingSecret: { name: thanos-objstore, key: objstore.yml }
additionalScrapeConfigs:
- job_name: ec2-node-exporter
ec2_sd_configs:
- region: us-east-1
port: 9100
filters:
- { name: "tag:monitoring", values: ["node-exporter"] }
- { name: "instance-state-name", values: ["running"] }
relabel_configs:
# Reuse the node-mixin default rules/dashboards, which select job="node-exporter"
- target_label: job
replacement: node-exporter
- source_labels: [__meta_ec2_tag_Name]
target_label: instance
- source_labels: [__meta_ec2_tag_role]
target_label: role
- source_labels: [__meta_ec2_instance_id]
target_label: instance_id
- source_labels: [__meta_ec2_availability_zone]
target_label: az
- job_name: postgres-exporter
ec2_sd_configs:
- region: us-east-1
port: 9187
filters:
- { name: "tag:role", values: ["postgres"] }
- { name: "instance-state-name", values: ["running"] }
relabel_configs:
- source_labels: [__meta_ec2_tag_Name]
target_label: instance
- source_labels: [__meta_ec2_tag_pg_cluster]
target_label: pg_cluster
# NOTE: do NOT derive primary/replica from tags — tags go stale after failover.
# Use pg_replication_is_replica at query time instead.
alertmanager:
alertmanagerSpec:
replicas: 3
nodeSelector: { workload: monitoring }
tolerations:
- { key: dedicated, operator: Equal, value: monitoring, effect: NoSchedule }
podAntiAffinity: hard
# Mounted at /etc/alertmanager/secrets/<secret-name>/<key>
secrets:
- alertmanager-pagerduty # keys: platform, db
- alertmanager-slack # key: sre-alerts
- alertmanager-heartbeat # key: url
config:
global:
resolve_timeout: 5m
inhibit_rules:
- source_matchers: ['severity="critical"']
target_matchers: ['severity="warning"']
equal: [alertname, service, cluster]
- source_matchers: ['alertname="PostgresNoPrimary"']
target_matchers: ['alertname=~"PostgresReplicationLag.*|PostgresConnectionUtilization.*"']
equal: [pg_cluster]
- source_matchers: ['alertname="KubeNodeNotReady"']
target_matchers: ['severity="warning"']
equal: [node]
route:
receiver: slack-sre-alerts
group_by: [alertname, service, cluster]
group_wait: 30s
group_interval: 5m
repeat_interval: 12h
routes:
- receiver: heartbeat
matchers: ['alertname="Watchdog"']
group_wait: 0s
group_interval: 1m
repeat_interval: 1m
- receiver: "null"
matchers: ['alertname="InfoInhibitor"']
- receiver: pd-db-oncall
matchers: ['team="db"', 'severity="critical"']
group_wait: 10s
repeat_interval: 1h
- receiver: pd-platform-primary
matchers: ['severity="critical"']
group_wait: 10s
repeat_interval: 1h
- receiver: slack-sre-alerts
matchers: ['severity=~"warning|info"']
receivers:
- name: "null"
- name: heartbeat
webhook_configs:
- url_file: /etc/alertmanager/secrets/alertmanager-heartbeat/url
send_resolved: false
- name: pd-platform-primary
pagerduty_configs:
- routing_key_file: /etc/alertmanager/secrets/alertmanager-pagerduty/platform
severity: critical
description: '{{ .CommonLabels.alertname }}: {{ .CommonAnnotations.summary }}'
details:
service: '{{ .CommonLabels.service }}'
priority: '{{ .CommonLabels.priority }}'
runbook: '{{ .CommonAnnotations.runbook_url }}'
dashboard: '{{ .CommonAnnotations.dashboard_url }}'
send_resolved: true
- name: pd-db-oncall
pagerduty_configs:
- routing_key_file: /etc/alertmanager/secrets/alertmanager-pagerduty/db
severity: critical
description: '{{ .CommonLabels.alertname }}: {{ .CommonAnnotations.summary }}'
details:
pg_cluster: '{{ .CommonLabels.pg_cluster }}'
priority: '{{ .CommonLabels.priority }}'
runbook: '{{ .CommonAnnotations.runbook_url }}'
dashboard: '{{ .CommonAnnotations.dashboard_url }}'
send_resolved: true
- name: slack-sre-alerts
slack_configs:
- api_url_file: /etc/alertmanager/secrets/alertmanager-slack/sre-alerts
channel: '#sre-alerts'
send_resolved: true
title: '[{{ .Status | toUpper }}] {{ .CommonLabels.alertname }} ({{ .CommonLabels.severity }})'
text: >-
{{ .CommonAnnotations.summary }}
Runbook: {{ .CommonAnnotations.runbook_url }}
Dashboard: {{ .CommonAnnotations.dashboard_url }}
additionalPrometheusRulesMap:
slo-recording:
groups:
- name: sli-recording
interval: 30s
rules:
- record: service:requests:rate5m
expr: sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api"}[5m]))
- record: service:request_errors:ratio_rate5m
expr: |
sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api",code=~"5.."}[5m]))
/ sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api"}[5m]))
- record: service:request_errors:ratio_rate30m
expr: |
sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api",code=~"5.."}[30m]))
/ sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api"}[30m]))
- record: service:request_errors:ratio_rate1h
expr: |
sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api",code=~"5.."}[1h]))
/ sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api"}[1h]))
- record: service:request_errors:ratio_rate2h
expr: |
sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api",code=~"5.."}[2h]))
/ sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api"}[2h]))
- record: service:request_errors:ratio_rate6h
expr: |
sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api",code=~"5.."}[6h]))
/ sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api"}[6h]))
- record: service:request_errors:ratio_rate1d
expr: |
sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api",code=~"5.."}[1d]))
/ sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api"}[1d]))
- record: service:request_errors:ratio_rate3d
expr: |
sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api",code=~"5.."}[3d]))
/ sum by (service) (rate(http_requests_total{service=~"checkout-api|payment-gateway-proxy|product-catalog-api"}[3d]))
- record: service:request_latency_seconds:p95_5m
expr: histogram_quantile(0.95, sum by (service, le) (rate(http_request_duration_seconds_bucket{service=~"checkout-api|payment-gateway-proxy|product-catalog-api"}[5m])))
- record: service:request_latency_seconds:p99_5m
expr: histogram_quantile(0.99, sum by (service, le) (rate(http_request_duration_seconds_bucket{service=~"checkout-api|payment-gateway-proxy|product-catalog-api"}[5m])))
slo-alerts:
groups:
- name: checkout-api
rules:
- alert: CheckoutErrorBudgetFastBurn
expr: |
service:request_errors:ratio_rate1h{service="checkout-api"} > (14.4 * 0.001)
and service:request_errors:ratio_rate5m{service="checkout-api"} > (14.4 * 0.001)
for: 2m
labels: { severity: critical, team: platform, priority: P1 }
annotations:
summary: "checkout-api burning error budget at >14.4x (2% of monthly budget per hour)"
runbook_url: https://runbooks.example.com/checkout-api/error-budget-burn
dashboard_url: https://grafana.example.com/d/svc-red?var-service=checkout-api
- alert: CheckoutErrorBudgetSlowBurn
expr: |
service:request_errors:ratio_rate6h{service="checkout-api"} > (6 * 0.001)
and service:request_errors:ratio_rate30m{service="checkout-api"} > (6 * 0.001)
for: 15m
labels: { severity: critical, team: platform, priority: P2 }
annotations:
summary: "checkout-api burning error budget at >6x (5% of monthly budget per 6h)"
runbook_url: https://runbooks.example.com/checkout-api/error-budget-burn
dashboard_url: https://grafana.example.com/d/svc-red?var-service=checkout-api
- alert: CheckoutErrorBudgetTicket
expr: |
(service:request_errors:ratio_rate1d{service="checkout-api"} > (3 * 0.001)
and service:request_errors:ratio_rate2h{service="checkout-api"} > (3 * 0.001))
or
(service:request_errors:ratio_rate3d{service="checkout-api"} > 0.001
and service:request_errors:ratio_rate6h{service="checkout-api"} > 0.001)
for: 1h
labels: { severity: warning, team: platform }
annotations:
summary: "checkout-api steadily consuming error budget — ticket"
runbook_url: https://runbooks.example.com/checkout-api/error-budget-burn
- alert: CheckoutLatencyP99Breach
expr: |
service:request_latency_seconds:p99_5m{service="checkout-api"} > 0.8
and on (service) service:requests:rate5m{service="checkout-api"} > 1
for: 10m
labels: { severity: critical, team: platform, priority: P2 }
annotations:
summary: "checkout-api p99 {{ $value | humanizeDuration }} > 800ms SLO"
runbook_url: https://runbooks.example.com/checkout-api/latency
dashboard_url: https://grafana.example.com/d/svc-red?var-service=checkout-api
- name: payment-gateway-proxy
rules:
- alert: PaymentGatewayErrorRateBreach
# Hard page: >0.1% over 5m with min-traffic guard; low-traffic fallback = >=10 errors/5m
expr: |
(
service:request_errors:ratio_rate5m{service="payment-gateway-proxy"} > 0.001
and on (service) service:requests:rate5m{service="payment-gateway-proxy"} >= 0.5
)
or on (service)
(
sum by (service) (increase(http_requests_total{service="payment-gateway-proxy",code=~"5.."}[5m])) >= 10
and on (service) service:requests:rate5m{service="payment-gateway-proxy"} < 0.5
)
for: 2m
keep_firing_for: 10m
labels: { severity: critical, team: platform, priority: P1 }
annotations:
summary: "payment-gateway-proxy error rate breached 0.1% SLO — payments impacted"
runbook_url: https://runbooks.example.com/payment-gateway-proxy/errors
dashboard_url: https://grafana.example.com/d/payments
- name: postgres
rules:
- alert: PostgresNoPrimary
expr: absent(pg_replication_is_replica{pg_cluster="pg-main"} == 0)
for: 1m
labels: { severity: critical, team: db, priority: P1, pg_cluster: pg-main }
annotations:
summary: "No reachable PostgreSQL primary in pg-main"
runbook_url: https://runbooks.example.com/postgres/no-primary
dashboard_url: https://grafana.example.com/d/postgres
- alert: PostgresSplitBrain
expr: count by (pg_cluster) (pg_replication_is_replica == 0) > 1
for: 1m
labels: { severity: critical, team: db, priority: P1 }
annotations:
summary: "More than one PostgreSQL primary detected in {{ $labels.pg_cluster }}"
runbook_url: https://runbooks.example.com/postgres/split-brain
- alert: PostgresReplicationLagWarning
expr: pg_replication_lag_seconds and on (instance) (pg_replication_is_replica == 1) > 5
for: 2m
labels: { severity: warning, team: db }
annotations:
summary: "Replica {{ $labels.instance }} lag {{ $value | humanizeDuration }}"
runbook_url: https://runbooks.example.com/postgres/replication-lag
- alert: PostgresReplicationLagCritical
expr: (pg_replication_lag_seconds and on (instance) (pg_replication_is_replica == 1)) > 10
for: 3m
labels: { severity: critical, team: db, priority: P2 }
annotations:
summary: "Replica {{ $labels.instance }} lag {{ $value | humanizeDuration }} > 10s SLO"
runbook_url: https://runbooks.example.com/postgres/replication-lag
dashboard_url: https://grafana.example.com/d/postgres
- alert: PostgresConnectionUtilizationCritical
expr: |
sum by (instance, pg_cluster) (pg_stat_activity_count)
/ on (instance, pg_cluster) max by (instance, pg_cluster) (pg_settings_max_connections) > 0.80
for: 5m
labels: { severity: critical, team: db, priority: P2 }
annotations:
summary: "{{ $labels.instance }} connections at {{ $value | humanizePercentage }} of max"
runbook_url: https://runbooks.example.com/postgres/connections
- alert: PostgresDataVolumeFillingUp
expr: |
predict_linear(node_filesystem_avail_bytes{role="postgres",mountpoint="/var/lib/postgresql"}[6h], 4 * 3600) < 0
and node_filesystem_avail_bytes{role="postgres",mountpoint="/var/lib/postgresql"}
/ node_filesystem_size_bytes{role="postgres",mountpoint="/var/lib/postgresql"} < 0.25
for: 15m
labels: { severity: critical, team: db, priority: P2 }
annotations:
summary: "PG data volume on {{ $labels.instance }} predicted full within 4h"
runbook_url: https://runbooks.example.com/postgres/disk-full
- name: order-fulfillment-queue
rules:
- alert: OrderQueueBacklogCritical
expr: max by (dimension_QueueName) (aws_sqs_approximate_number_of_messages_visible_maximum{dimension_QueueName="order-fulfillment"}) > 500
for: 10m
labels: { severity: critical, team: platform, service: order-fulfillment-worker, priority: P2 }
annotations:
summary: "Order queue backlog {{ $value }} > 500 SLO"
runbook_url: https://runbooks.example.com/order-fulfillment/backlog
dashboard_url: https://grafana.example.com/d/fulfillment
- alert: OrderProcessingLagCritical
expr: max by (dimension_QueueName) (aws_sqs_approximate_age_of_oldest_message_maximum{dimension_QueueName="order-fulfillment"}) > 120
for: 5m
labels: { severity: critical, team: platform, service: order-fulfillment-worker, priority: P2 }
annotations:
summary: "Oldest order message is {{ $value | humanizeDuration }} old (> 2m SLO)"
runbook_url: https://runbooks.example.com/order-fulfillment/lag
- alert: OrderWorkerStalled
expr: |
max by (dimension_QueueName) (aws_sqs_approximate_number_of_messages_visible_maximum{dimension_QueueName="order-fulfillment"}) > 0
and on (dimension_QueueName)
sum by (dimension_QueueName) (aws_sqs_number_of_messages_deleted_sum{dimension_QueueName="order-fulfillment"}) == 0
for: 10m
labels: { severity: critical, team: platform, service: order-fulfillment-worker, priority: P2 }
annotations:
summary: "Order queue has messages but nothing is being consumed"
runbook_url: https://runbooks.example.com/order-fulfillment/stalled
The postgres_exporter metric names used above (pg_replication_is_replica, pg_replication_lag_seconds, pg_stat_activity_count, pg_settings_max_connections) come from the built-in collectors of recent postgres_exporter releases. XID age, slot-retained WAL, and streaming replica count need custom queries.
9. Common Pitfalls and How This Design Avoids Them
| Pitfall | How this design avoids it |
|---|---|
| Monitoring dies with the thing it monitors (in-cluster Prometheus during a cluster outage) | Watchdog → external dead-man's switch; external synthetics page PD directly |
Permanent TargetDown noise on EKS from unscrapeable control-plane components |
etcd, scheduler, controller-manager, and kube-proxy scrapes disabled |
Default node rules silently ignore EC2 hosts because node-mixin selects job="node-exporter" |
EC2 scrape job relabels job to node-exporter |
| Stale primary/replica labels after failover (from EC2 tags) | Role derived at query time from pg_replication_is_replica; split-brain alert added |
False replication-lag alerts on an idle primary (now() - last_replay_timestamp) |
Exporter lag metric returns 0 when receive LSN = replay LSN; filtered to replicas |
| Imprecise p95/p99 from default Go histogram buckets | Buckets at 0.3/0.4/0.5/0.8 required in Phase 1, or native histograms |
| Card declines counted as payment errors, leading to constant hard pages | Error definition excludes 402/decline outcomes; declines tracked as a business KPI |
| Ratio alerts paging on low traffic | Minimum-traffic guards plus absolute-count fallback |
| Flapping on spiky error rates | Multi-window burn rates, for:, keep_firing_for, warning/critical hysteresis |
| CloudWatch delay making the 2-min processing-lag SLO undetectable in time (SQS metrics arrive minutes late) | YACE alerts as the backstop; in-app oldest-age gauge in Phase 2 for real-time detection |
| Autoscaling moves the bottleneck to Postgres | KEDA/HPA max replicas sized against PG connection headroom; PgBouncer recommended |
| Inactive replication slot fills the PG disk | Slot retained-WAL alert plus predict_linear disk alert |
| Cardinality explosion (path/user labels, cAdvisor) | sample_limit, metric drops, head-series alert, route templates instead of raw paths |
| HA Prometheus sends duplicate pages | Operator-managed replica label; both Prometheus instances send to all 3 Alertmanagers, which deduplicate |
| CPU% pages on bin-packed k8s nodes | CPU is warning-only on standalone hosts; k8s uses throttling, pressure, and pending pods |
| Pages with no runbook | runbook_url is mandatory; monthly actionable-rate review |
| Promtail EOL / EKS 1.29 out of support | Flagged; Alloy migration in Phase 2; version check up front |
10. Assumptions and Questions
Assumptions made
- [A1] Your EKS version is supported in practice (1.29 is past extended support).
- [A2] Services expose
http_requests_total{service,code}andhttp_request_duration_seconds_bucket. - [A3] payment-gateway-proxy emits Stripe upstream metrics.
- [A4] PG volumes are gp3.
- [A5] There is no separate security channel.
- [A6] payment-gateway-proxy is in PCI scope.
- [A7] Warnings may go directly from Alertmanager to Slack.
- Postgres runs streaming replication with
pg_cluster=pg-main, and the data directory is on/var/lib/postgresql. - The SQS queue is named
order-fulfillment, is a standard (non-FIFO) queue, and has a DLQ.
Questions before finalizing, most important first
- Instrumentation: what metric names, labels, and histogram buckets do the Go services expose today? Is there OpenTelemetry anywhere?
- Postgres HA and tooling: what manages failover (Patroni, repmgr, or manual)? Which backup/WAL archiving tool do you use (pgBackRest or WAL-G)? Is there PgBouncer? Does "connection pool utilization < 80%" mean server connections vs
max_connections, PgBouncer pools, or the app-sidedatabase/sqlpool? - Error definitions and traffic: what counts as a payment error, and is my "exclude declines" assumption right? What are typical and off-peak request rates per service (to calibrate traffic guards)? Should checkout's 0.5%/5m breach page rather than warn?
- Slack path: must every alert flow through PagerDuty, or is it acceptable for warnings to go straight from Alertmanager to Slack?
- Escalation timing: is Marcus at 30 min from trigger, or 30 min after Priya? Does DB-OnCall escalate to the same people? Would you accept faster (5-min) escalation for payments?
- Compliance: is PCI DSS (or SOC 2) in scope? Are there log retention mandates beyond what I assumed?
- Versions: what are your actual EKS, kube-prometheus-stack chart, Prometheus, and Alertmanager versions? Are you OK migrating Promtail to Alloy?
- External monitoring budget: which synthetic/heartbeat provider is acceptable (Checkly, Grafana Synthetic Monitoring, Healthchecks.io, or CloudWatch Synthetics)?
- Grafana edition: OSS or Enterprise/Cloud? This changes how reports and email digests are built.
- Batch jobs: how are they scheduled (cron, systemd timers, Airflow)? Which jobs have business SLAs that justify paging?
- Long-term storage: do you prefer self-run Thanos, Grafana Mimir, or Amazon Managed Prometheus, given cost and ops trade-offs?
- SQS details: is the queue FIFO? Does a DLQ exist, and what is the visibility timeout vs typical processing time?
- Service ownership: are there per-service teams who should own pages (e.g., payments, catalog), or does Platform own everything?
Once you answer these, especially questions 1–5, I'll finalize the thresholds, produce the remaining PrometheusRules (catalog, k8s, hosts, Loki ruler), and deliver the YACE, Alloy, and KEDA configs plus the runbook templates.
Related prompts
Ansible Automation Playbook Creator
Generates production-ready, idempotent Ansible playbooks and roles for any infrastructure automation or configuration task.
Cybersecurity Audit Specialist
Run a structured cybersecurity audit of an organization, prioritizing risks and producing an actionable remediation roadmap.
Kubernetes Resource Diagnostics
Diagnoses a failing Kubernetes resource and returns root cause plus a step-by-step fix.
DevOps Automation Specialist
Acts as a DevOps engineer to design, optimize, and troubleshoot CI/CD pipelines, infrastructure as code, and cloud automation.