Grafana 입문 2편 — Prometheus + PromQL 깊이 (Pull · Exporter · Alertmanager)

2026-05-18Grafana 입문에서 운영까지

Grafana 입문 2편. Prometheus + PromQL 깊이 — Pull model (scrape) vs Push, Service Discovery (Kubernetes · Consul · EC2 · DNS · File), Exporter 표준 (node · mysqld · redis · blackbox · custom), Time Series Database 의 구조 (sample · label · series), PromQL (instant vs range vector · rate · irate · increase · histogram_quantile · aggregation · subquery · offset), Recording Rule (사전 계산), Alertmanager (grouping · inhibition · silence · receiver). 메트릭 의 모든 기반 자리.

📚 Grafana 입문에서 운영까지 · 2편 — Prometheus + PromQL 깊이 (Pull · Exporter · Alertmanager)

이 글은 Grafana 입문에서 운영까지 시리즈 2편이에요. 1편3 pillar 의 큰 그림 다음 — Metrics 의 모든 기반 자리.

이번 글의 범위

Prometheus = Grafana 의 가장 흔한 datasource(Grafana 가 데이터를 끌어오는 원천). 시계열 DB + PromQL(시계열 질의 언어) + Alert. 모니터링 의 de-facto 표준(사실상 업계 표준). 이 글 = Prometheus 의 모든 핵심 + PromQL 의 깊이.

자리 자산
수집 Pull model · scrape · Service Discovery
데이터 모델 sample · label · series · TSDB
Query PromQL (rate · histogram · aggregation)
Alert Alertmanager 의 routing · grouping

Pull Model — Prometheus 의 첫 결정

Pull vs Push

Push model (전통적):
  Service → 직접 monitoring 서버에 send
  - 예: StatsD · Datadog Agent
  - 장점: monitoring 서버가 service 위치 모름 OK
  - 단점: service down 시 알 수 없음 (그냥 hit 안 옴)

Pull model (Prometheus):
  Monitoring 서버 → Service 의 /metrics endpoint 호출
  - 장점: service 의 health 자체 = scrape 성공/실패 로 감지
  - 단점: monitoring 서버가 모든 service 위치 알아야

여기서 scrape(주기적으로 /metrics 를 긁어오는 호출) 가 Prometheus 의 동작 단위.

Pull 의 장점 깊이

1. Service 의 health check 자동
   - scrape 실패 = service down 표시
   - up{job="api"} == 0 → 자동 alert

2. 중복 발견 (multiple Prometheus)
   - 같은 service 를 여러 Prometheus 가 scrape 가능
   - 그 결과 = consistent (push 는 한 곳)

3. Service 의 코드 단순
   - 단순 /metrics endpoint 만
   - HTTP 의 GET handler 한 줄
   - "어디로 send 할지" 코드 없음

Push Gateway — 예외 자리

Pull 의 한계:
  - Batch job · cron job 의 짧은 수명
  - scrape 전에 끝남 → metric 누락

해결: Push Gateway
  Batch job → Push Gateway 로 push
  Prometheus → Push Gateway 를 scrape (pull)

→ 짧은 수명 job 의 metric 도 수집

여기서 시험 함정 — Push Gateway 는 전체 monitoring 의 push 대안 X. batch · cron 만. 일반 service = Pull 이 표준.

Service Discovery — 자동 발견

Service Discovery(서비스 위치를 자동으로 찾아오는 메커니즘) 는 동적 인프라 의 필수.

정적 vs 동적

정적 config:
  scrape_configs:
    - job_name: 'api'
      static_configs:
        - targets: ['api1:8080', 'api2:8080', 'api3:8080']

→ instance 추가/삭제 시 config 수정 + reload 필요
→ Kubernetes 의 auto-scaling 환경 X

Service Discovery 의 종류

1. Kubernetes SD
   - Pod · Service · Endpoint 자동 발견
   - kubernetes_sd_configs
   - Annotation 기반 (prometheus.io/scrape: "true")

2. Consul SD
   - Consul 의 service registry 활용
   - consul_sd_configs

3. EC2 SD (AWS)
   - EC2 인스턴스 자동 발견
   - Tag 기반 filter

4. DNS SD
   - DNS SRV/A record 의 endpoint
   - dns_sd_configs

5. File SD
   - JSON/YAML 파일 watching
   - 외부 시스템 의 endpoint 동적 update

6. 기타: Azure, GCE, OpenStack, Marathon, Docker Swarm, ...

Kubernetes SD 예

# Prometheus config
scrape_configs:
  - job_name: 'kubernetes-pods'
    kubernetes_sd_configs:
      - role: pod
    relabel_configs:
      # prometheus.io/scrape: "true" annotation 만 수집
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
        action: keep
        regex: true
      # 동적 port 설정
      - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
        action: replace
        regex: ([^:]+)(?::\d+)?;(\d+)
        replacement: $1:$2
        target_label: __address__
      # namespace 라벨 추가
      - source_labels: [__meta_kubernetes_namespace]
        target_label: namespace
      # pod name 라벨
      - source_labels: [__meta_kubernetes_pod_name]
        target_label: pod

복잡해 보여도 한 번 설정 으로 수백 pod 자동 발견 + 추적. relabel_configs(수집 전에 라벨을 재가공하는 규칙) 가 동적 발견 의 두뇌.

Exporter — 메트릭 노출

Exporter 의 의미

대부분 시스템 = Prometheus 형식 metric 노출 X. Exporter(외부 시스템 metric 을 Prometheus 형식으로 바꿔주는 어댑터) 가 번역기:

[MySQL]                [Prometheus]
  ↓ (mysql protocol)
[mysqld_exporter]  →  /metrics endpoint
                       ↑ (scrape)
                  [Prometheus 서버]

공식 표준 Exporter

- node_exporter         OS · 하드웨어 metric (CPU · 메모리 · 디스크)
- mysqld_exporter       MySQL
- postgres_exporter     PostgreSQL
- redis_exporter        Redis
- nginx-prometheus-exporter  Nginx
- haproxy_exporter      HAProxy
- blackbox_exporter     HTTP · TCP · ICMP 의 health check
- snmp_exporter         네트워크 장비
- jmx_exporter          Java JMX (JVM · Kafka · Cassandra)
- kafka_exporter        Apache Kafka
- mongodb_exporter      MongoDB
- elasticsearch_exporter Elasticsearch

Application 의 Native Instrumentation

Native Instrumentation(애플리케이션 코드 자체에 metric 코드를 박는 방식) 은 exporter 없이 직접 노출.

Prometheus Client Library:
  - Java (Micrometer · simpleclient)
  - Python (prometheus_client)
  - Go (prometheus/client_golang)
  - Node.js (prom-client)
  - Ruby · Rust · .NET · ...

코드 예 (Python):
from prometheus_client import Counter, Histogram, start_http_server

REQUESTS = Counter('http_requests_total', 'Total HTTP requests', ['method', 'endpoint', 'status'])
LATENCY = Histogram('http_request_duration_seconds', 'HTTP request duration', ['endpoint'])

@app.middleware('http')
async def metrics_middleware(request, call_next):
    start = time.time()
    response = await call_next(request)
    elapsed = time.time() - start

    REQUESTS.labels(
        method=request.method,
        endpoint=request.url.path,
        status=response.status_code
    ).inc()
    LATENCY.labels(endpoint=request.url.path).observe(elapsed)

    return response

# /metrics endpoint 자동 노출
start_http_server(8000)

Blackbox Exporter — health check

# Prometheus config
scrape_configs:
  - job_name: 'blackbox'
    metrics_path: /probe
    params:
      module: [http_2xx]
    static_configs:
      - targets:
        - https://example.com
        - 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

→ 외부에서 URL 의 응답 시간 · status code 자동 모니터.

Data Model — Sample · Label · Series

Time Series 의 단위

Time Series (TS):
  {metric_name, label_1, label_2, ...}  →  [(t1, v1), (t2, v2), (t3, v3), ...]

예:
  http_requests_total{method="GET", endpoint="/api/users", status="200"}
    → (10:00:00, 1234)
       (10:00:15, 1240)
       (10:00:30, 1248)
       ...

각 unique label combination = 별도 time series.

Metric Type 4 종

1. Counter
   - 단조증가 (감소 X)
   - reset 시 0 으로
   - 예: http_requests_total

2. Gauge
   - 자유 변동 (증가 · 감소 · 0)
   - 예: cpu_usage_percent · memory_used_bytes

3. Histogram
   - 분포 측정 (latency · response size)
   - bucket 별 카운트
   - 예: http_request_duration_seconds_bucket{le="0.1"}

4. Summary
   - Histogram 비슷 (분포 측정)
   - quantile 의 *client-side 계산* (Histogram 은 server-side)
   - 대부분 case = Histogram 권장

Cardinality 의 함정

Cardinality(라벨 조합 의 가짓수, 곧 series 수) 가 Prometheus 운영 의 최대 변수.

높은 cardinality (위험):
  http_requests_total{user_id="12345"}  → 모든 user 마다 새 series
  http_requests_total{request_id="abc"} → 매 request 마다 새 series
  http_requests_total{path="/api/products/12345"} → 모든 상품 마다

낮은 cardinality (안전):
  http_requests_total{method="GET", status="200", route="/api/products/:id"}

여기서 정말 중요한 시험 함정 — dimension 의 cardinality 관리가 Prometheus 운영 의 가장 중요한 자리. 잘못 박힌 label 한 개 = 수백만 series 폭증 → 메모리 폭발Prometheus down.

Label 의식

좋은 label:
  - method · status · region · environment · service
  - finite 한 값들 (10~100 종)

나쁜 label:
  - user_id · request_id · session_id (수백만 unique)
  - timestamp · UUID
  - URL 의 dynamic part (/products/12345)

해결:
  - dynamic 값 = path normalization (/products/:id)
  - high cardinality 의식
  - Recording Rule 의 aggregation

PromQL — Query Language

Instant Vector vs Range Vector

Instant Vector:
  http_requests_total
  → 지금 순간의 모든 time series 의 값

Range Vector:
  http_requests_total[5m]
  → 지난 5분 동안의 모든 sample

→ 대부분 PromQL 함수 가 Range Vector 입력

rate · irate · increase

1. rate(): 평균 초당 변화율
   rate(http_requests_total[5m])
   → 지난 5분 평균 RPS

2. irate(): 마지막 2개 sample 의 변화율
   irate(http_requests_total[5m])
   → 가장 최근 짧은 변화율 (그래프 의 지터 큼)

3. increase(): 지난 시간 동안 총 증가량
   increase(http_requests_total[1h])
   → 지난 1시간 동안 누적 요청 수

여기서 함정 — rate 의 time windowscrape_interval 의 약 4배 권장. scrape 15s → rate 1m 권장.

histogram_quantile

# Histogram 의 p99 latency
histogram_quantile(
  0.99,
  sum(rate(http_request_duration_seconds_bucket[5m])) by (le)
)

→ 지난 5분의 p99 응답시간

le (less-than-or-equal) = histogram bucket 의 상한. by (le) 로 bucket 별 합산 후 quantile 계산.

Aggregation

sum: 합계
sum(rate(http_requests_total[5m]))
sum by (status) (rate(http_requests_total[5m]))
sum without (instance) (rate(http_requests_total[5m]))

avg: 평균
avg(node_cpu_seconds_total)

max · min: 최대 · 최소
max(node_memory_used_bytes) by (instance)

count: 개수
count(up == 1) by (job)

topk · bottomk: 상위 · 하위
topk(5, http_requests_total)

Functions 의 종합

시간 의식:
  - time()              현재 Unix timestamp
  - timestamp(v)        sample 의 timestamp
  - offset 5m           5분 전 의 값
  - @ <timestamp>       특정 시각 의 값

비교:
  - up == 1
  - http_requests_total > 100

수학:
  - sqrt(x) · ln(x) · log2(x) · exp(x)
  - abs(x) · sgn(x) · clamp(x, min, max)
  - round(x) · ceil(x) · floor(x)

vector matching:
  - http_requests_total / http_requests_total{status="200"}
  - on(method) · ignoring(status) · group_left · group_right

Subquery — 함수 안의 query

Subquery(질의 안에서 또 다른 시계열을 만들어 다시 집계하는 문법) 는 임시 series 를 즉석 생성.

# 지난 1시간 동안 의 5분 rate 의 평균
avg_over_time(
  rate(http_requests_total[5m])[1h:1m]
)

# [5m] 은 rate 의 window
# [1h:1m] 은 subquery (1시간 동안 1분 마다 sample)

복잡 한 분석 의 핵심 도구. 너무 자주 사용 X (성능 부담).

실전 예 — 표준 5 Query

# 1. RPS by status
sum(rate(http_requests_total[5m])) by (status)

# 2. Error rate
sum(rate(http_requests_total{status=~"5.."}[5m])) /
sum(rate(http_requests_total[5m]))

# 3. p99 latency
histogram_quantile(0.99,
  sum(rate(http_request_duration_seconds_bucket[5m])) by (le)
)

# 4. CPU usage (per instance)
100 - (avg by (instance) (
  rate(node_cpu_seconds_total{mode="idle"}[5m])
) * 100)

# 5. Disk usage
(node_filesystem_size_bytes - node_filesystem_free_bytes) /
node_filesystem_size_bytes * 100

이 5 query = 대부분 dashboard 의 기본. 익숙 해지면 PromQL 의 90%.

Recording Rule — 사전 계산

Recording Rule 의 자리

Recording Rule(자주 쓰는 PromQL 을 미리 계산해 새 metric 으로 저장) 이 dashboard 의 속도 비결.

복잡한 query 가 자주 실행:
  histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, service))

→ Dashboard 마다 매번 계산 = 느림 + Prometheus 부담

해결: Recording Rule
  - 자주 사용 query 를 *사전 계산*
  - 결과 = 새 metric 으로 저장
  - Dashboard 는 새 metric 만 query (빠름)

설정

# /etc/prometheus/rules/api.yml
groups:
  - name: api_recording_rules
    interval: 30s    # 30초 마다 평가
    rules:
      - record: job:http_request_p99:rate5m
        expr: |
          histogram_quantile(0.99,
            sum(rate(http_request_duration_seconds_bucket[5m])) by (le, job)
          )

      - record: job:http_error_rate:rate5m
        expr: |
          sum(rate(http_requests_total{status=~"5.."}[5m])) by (job) /
          sum(rate(http_requests_total[5m])) by (job)

이후 dashboard 에서 job:http_request_p99:rate5m 만 query.

Naming Convention

level:metric:operation

예:
  - instance:node_cpu:rate5m
  - job:http_request_p99:rate5m
  - cluster:memory_used:sum

Alertmanager — Alert 의 Routing

Prometheus + Alertmanager 의 분리

Alertmanager(alert 를 묶고 라우팅·통보 까지 책임지는 별도 컴포넌트) 가 Prometheus 와 역할 분담.

Prometheus:
  - Alert Rule 정의 + 평가
  - 조건 충족 시 → Alertmanager 에 alert send

Alertmanager:
  - 받은 alert 의 grouping · routing
  - Notification (Slack · PagerDuty · Email · ...)
  - Silence · Inhibition

Alert Rule

# /etc/prometheus/rules/alerts.yml
groups:
  - name: api_alerts
    rules:
      - alert: HighErrorRate
        expr: job:http_error_rate:rate5m > 0.05    # 5% error rate
        for: 5m                                     # 5분 지속
        labels:
          severity: critical
          team: backend
        annotations:
          summary: "Error rate above 5% for {{ $labels.job }}"
          description: "Current error rate: {{ $value | humanizePercentage }}"

      - alert: HighLatency
        expr: job:http_request_p99:rate5m > 1
        for: 10m
        labels:
          severity: warning
          team: backend
        annotations:
          summary: "p99 latency > 1s for {{ $labels.job }}"

Alertmanager Config

# /etc/alertmanager/alertmanager.yml
route:
  receiver: 'default-slack'
  group_by: ['alertname', 'cluster', 'service']
  group_wait: 30s          # 새 alert 그룹 의 첫 notification 까지
  group_interval: 5m       # 같은 그룹 의 추가 alert 의 notification 사이
  repeat_interval: 4h      # 같은 alert 반복 notification 사이
  routes:
    # critical → PagerDuty
    - match:
        severity: critical
      receiver: 'pagerduty-oncall'
      continue: true    # 다음 route 도 평가

    # backend team → 전용 Slack
    - match:
        team: backend
      receiver: 'slack-backend'

    # frontend team → 전용 Slack
    - match:
        team: frontend
      receiver: 'slack-frontend'

receivers:
  - name: 'default-slack'
    slack_configs:
      - channel: '#alerts-general'
        api_url: 'https://hooks.slack.com/services/XXX'

  - name: 'pagerduty-oncall'
    pagerduty_configs:
      - service_key: 'YOUR_SERVICE_KEY'

  - name: 'slack-backend'
    slack_configs:
      - channel: '#alerts-backend'

  - name: 'slack-frontend'
    slack_configs:
      - channel: '#alerts-frontend'

inhibit_rules:
  # critical alert 가 활성 시 같은 service 의 warning 무시
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname', 'cluster', 'service']

Grouping · Inhibition · Silence

1. Grouping
   - 같은 cluster · service 의 여러 alert = 한 notification
   - "10 instance 모두 down" → "1 alert" (10번 X)

2. Inhibition
   - 더 심각한 alert 가 활성 = 덜 심각한 alert 무시
   - "cluster down" → "instance error" alert 무시

3. Silence
   - 특정 라벨 매칭 의 alert 일시 mute
   - 배포 · 점검 시 사용
   - UI 또는 API

함정 정리

사고 1: Cardinality 폭발

원인 — user_id · request_id 를 label 박음 → series 수백만 → 메모리 폭발 → Prometheus down.

해결high cardinality 의식. Recording Rule 의 aggregation + dynamic 값 normalization.

사고 2: scrape_interval 의 너무 짧음

원인 — scrape_interval = 1s → Prometheus 부담 폭증 + 저장소 빠르게 채움.

해결15s ~ 30s 가 표준. 5s 이하 는 매우 특수.

사고 3: rate() 의 너무 짧은 window

원인rate(http_requests_total[1m]) 인데 scrape_interval 15s → window 안에 4 sample 만 → 불안정.

해결 — rate window = scrape_interval × 4 이상. 15s scrape → 1m rate.

사고 4: Histogram 의 bucket 정의 잘못

원인 — bucket = [0.1, 0.5, 1, 5, 10] 같이 coarse. p99 가 [1, 5] 사이면 정확도 X.

해결기대 latency 의 분포 에 맞춤. 일반 web = [.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10].

사고 5: Recording Rule 의 interval 너무 짧음

원인 — interval 5s → Prometheus 부담.

해결30s ~ 1m 표준. 사용 query 의 scrape_interval 의 2~4배.

사고 6: Alert 의 for 안 설정

원인for: 0 → flap(잠시 충족 후 곧 해제되는 짧은 깜빡임) → 너무 많은 alert.

해결for: 5m ~ for: 15m. 지속 충족 만 fire.

사고 7: Alertmanager 의 receiver 안 분리

원인 — 모든 alert → 한 Slack channel → noise → 무시.

해결severity · team 별 분리 + Notification Policy 의 tree routing.

사고 8: Inhibition 무시 → 폭주

원인 — cluster 의 큰 사고 → instance 100개 의 alert 100개 동시 → Slack 폭주.

해결Inhibition rule (cluster down → instance alert 무시) + Grouping (한 알림 으로).

사고 9: Service Discovery 의 relabel 잘못

원인 — relabel 규칙 잘못 → 의도 안 한 endpoint scrape → 무의미 series.

해결relabel 의 dry-run + Targets 페이지 의 확인.

사고 10: Long-term 저장 X

원인 — Prometheus 단일 → retention 15일 → 30일 전 trend X.

해결 — Mimir · Cortex · Thanos · 또는 Grafana Cloud 의 long-term.

운영 권장 패턴

Pattern 1: 표준 Exporter 8종

node_exporter         OS · 하드웨어
blackbox_exporter     외부 endpoint 의 HTTP/TCP
mysqld_exporter       MySQL
postgres_exporter     PostgreSQL
redis_exporter        Redis
kafka_exporter        Kafka
jmx_exporter          JVM 기반 (Spring · Kafka 등)
nginx-prometheus-exporter  Nginx

이 8 exporter = 대부분 production 의 80% 커버.

Pattern 2: RED Method (Application metric)

RED Method(Rate·Errors·Duration 세 metric 으로 서비스 건강 보기) 는 애플리케이션 표준.

R — Rate    초당 요청 수
E — Errors  에러 비율
D — Duration 응답 시간 분포

표준 metric 3종:
  - http_requests_total (Counter, labels: method, route, status)
  - http_request_duration_seconds (Histogram, labels: method, route)
  - http_errors_total (Counter, labels: error_type)

Pattern 3: USE Method (Resource metric)

USE Method(Utilization·Saturation·Errors 로 자원 상태 보기) 는 인프라 자원 의 표준.

U — Utilization  사용률
S — Saturation   대기 큐 길이
E — Errors       에러

표준 metric:
  - cpu_usage_percent
  - memory_used_bytes / memory_total_bytes
  - disk_io_time_seconds_total (saturation)
  - network_errors_total

Pattern 4: SLO 기반 Alert

SLO(Service Level Objective, 서비스 품질 목표치) 기반 alert 는 단순 임계치 보다 한 차원 위.

groups:
  - name: slo_alerts
    rules:
      # SLO: 99.9% success rate
      # Error budget: 0.1% / 28일

      # 1. Fast burn (1시간) — Critical
      - alert: ErrorBudgetFastBurn
        expr: |
          (1 - (
            sum(rate(http_requests_total{status!~"5.."}[1h])) /
            sum(rate(http_requests_total[1h]))
          )) > (14.4 * 0.001)
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "Error budget burning 14.4x faster (will exhaust in <2 days)"

      # 2. Slow burn (6시간) — Warning
      - alert: ErrorBudgetSlowBurn
        expr: |
          (1 - (
            sum(rate(http_requests_total{status!~"5.."}[6h])) /
            sum(rate(http_requests_total[6h]))
          )) > (6 * 0.001)
        for: 15m
        labels:
          severity: warning

단순 threshold 대신 비즈니스 의미 의 alert.

Pattern 5: Multi-tier Recording Rule

groups:
  - name: tier1_raw
    interval: 30s
    rules:
      - record: instance:http_requests:rate5m
        expr: rate(http_requests_total[5m])

  - name: tier2_aggregated
    interval: 30s
    rules:
      - record: job:http_requests:rate5m
        expr: sum(instance:http_requests:rate5m) by (job)

  - name: tier3_business
    interval: 1m
    rules:
      - record: business:slo_success_rate
        expr: |
          sum(rate(http_requests_total{status!~"5.."}[28d])) /
          sum(rate(http_requests_total[28d]))

여러 계층의 recording rule = dashboard 의 빠른 query + 비즈니스 metric 의 명확한 정의.

Pattern 6: Alert 의 Runbook 링크

- alert: DiskSpaceLow
  expr: ...
  labels:
    severity: warning
  annotations:
    summary: "Disk space below 20%"
    description: "..."
    runbook_url: "https://wiki.company.com/runbooks/disk-space-low"

alert 받은 사람 = 즉시 행동 가능. 어떻게 처리 의 매뉴얼 링크.

시험 직전 한 번 더 — Prometheus + PromQL 압축 노트

Pull Model

  • /metrics endpoint 의 scrape
  • service health = scrape 성공/실패 자동 감지
  • Push Gateway = batch · cron 만 의 예외

Service Discovery

  • Kubernetes · Consul · EC2 · DNS · File
  • relabel_configs 의 자동 필터링
  • annotation 기반 (prometheus.io/scrape: "true")

Exporter

  • node_exporter (OS) · mysqld · postgres · redis · nginx · blackbox · jmx · kafka
  • Application native = Prometheus Client Library
  • 4 metric type — Counter · Gauge · Histogram · Summary

Cardinality

  • label combination 수 = series 수
  • 동적 값 (user_id · request_id) = label X
  • normalization (/products/:id)
  • Recording Rule 의 aggregation

PromQL 핵심

  • Instant Vector vs Range Vector
  • rate (평균) · irate (최근) · increase (누적)
  • rate window = scrape_interval × 4 이상
  • histogram_quantile (sum by (le) 후 quantile)
  • aggregation (sum · avg · max · count · topk by/without)
  • subquery [duration:resolution]

Recording Rule

  • 자주 사용 query 사전 계산
  • naming: level:metric:operation
  • interval = scrape_interval × 2~4
  • multi-tier (raw → aggregated → business)

Alertmanager

  • Prometheus = alert 평가
  • Alertmanager = routing · notification
  • Grouping (같은 그룹 의 alert 합치기)
  • Inhibition (심각한 alert 가 덜 심각한 alert 무시)
  • Silence (일시 mute)
  • group_wait · group_interval · repeat_interval

Alert Rule

  • expr + for + labels + annotations
  • for = 지속 시간 (flap 방지)
  • annotation 의 summary · description · runbook_url
  • 라벨 severity (critical · warning) + team

사고

  • Cardinality 폭발 (label 의식 X)
  • scrape_interval 너무 짧음 (1s)
  • rate window 너무 짧음 (sample 부족)
  • Histogram bucket 정의 잘못
  • Recording Rule interval 너무 짧음
  • Alert for 안 설정 (flap)
  • Alertmanager receiver 안 분리 (noise)
  • Inhibition 없음 (폭주)
  • Service Discovery relabel 잘못
  • Long-term storage X (Mimir · Thanos)

패턴

  • 표준 Exporter 8종 (80% 커버)
  • RED Method (Rate · Errors · Duration) — application
  • USE Method (Utilization · Saturation · Errors) — resource
  • SLO 기반 Alert (error budget · multi-window burn rate)
  • Multi-tier Recording Rule
  • Alert 의 runbook_url

공식 문서: Prometheus overview · PromQL basics 에서 더 깊은 spec 을 확인할 수 있어요.

시리즈 다른 편 (앞뒤 글 모음)

이전 글:

다음 글:

※ 이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

답글 남기기

error: Content is protected !!