관측성

Prometheus

meellon 2026. 6. 23. 07:30

학습 목표

Prometheuspull 방식으로 메트릭을 수집함을 설명할 수 있다.

앱이 노출하는 exposition format(/metrics)을 읽을 수 있다.

prometheus.ymlscrape·targets·relabel 개념을 설명할 수 있다.

PromQLrate, sum, histogram_quantile 등 기본 쿼리를 작성할 수 있다.

문제 상황

  • 앱마다 메트릭을 push하라고 하면 방화벽·인증·버스트가 복잡하다
    • 중앙 수집기가 주기적으로 가져가는 모델이 단순하다
  • http_requests_total 그래프가 계단만 오른다
    • counter는 rate() 로 RPS를 봐야 한다
  • Pod 3개가 같은 이름으로 메트릭을 내면 어느 인스턴스인지 모른다
    • scrape 시 붙는 instance, job 라벨이 필요하다
  • p99를 구하려면 histogram이 있는데 쿼리 문법을 모른다
    • histogram_quantile_bucket 접미사

메트릭 기초에서 counter·gauge·histogram·RED를 봤다. 이번 편은 그 숫자를 모으고 질의하는 Prometheus다.

1. Prometheus란

Prometheus — 오픈소스 시계열 DB + scrape + PromQL + (선택) Alertmanager.

구성 역할
Prometheus server scrape, 저장(TSDB), 쿼리 API
Exporters / 앱 /metrics HTTP endpoint로 텍스트 노출
Alertmanager 알람 라우팅·그룹·silence
Grafana 대시보드·시각화 (7편)
  • 단일 바이너리로 시작하기 쉽고, K8s·클라우드 생태계와 잘 맞는다
  • 장기 보관·고카디널리티 분석은 Thanos/Mimir 등으로 확장 (본 시리즈 범위 밖)

2. Pull 모델

Pull — Prometheus가 설정된 interval마다 target의 /metricsHTTP GET한다.

Pull 장점 Push 대비
타겟 목록이 중앙 설정에 있다 앱이 수집기 주소를 몰라도 됨
up 메트릭으로 scrape 성공 여부 수집기 장애 시 앱 버퍼 부담 감소
service discovery와 결합 K8s Pod IP 변경에 대응
Push가 쓰이는 경우
단기 배치 Job Pushgateway로 1회성 job 메트릭
NAT 뒤에서 수집기가 닿지 않을 때 (가능하면 pull 우선)
# prometheus.yml (발췌)
scrape_configs:
  - job_name: api
    scrape_interval: 15s
    static_configs:
      - targets: ["api:8080"]
  • scrape_interval — 수집 주기 (기본 1m, job별 override)
  • scrape 실패 시 up{job="api"} == 0타겟 다운 알람에 사용

3. Exposition format

앱·exporter는 텍스트로 메트릭을 노출한다 (OpenMetrics/Prometheus text format).

# HELP http_requests_total Total HTTP requests
# TYPE http_requests_total counter
http_requests_total{method="GET",status="200"} 184203
http_requests_total{method="POST",status="500"} 42

# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{le="0.1"} 12000
http_request_duration_seconds_bucket{le="0.5"} 45000
http_request_duration_seconds_bucket{le="+Inf"} 50000
http_request_duration_seconds_sum 8200.5
http_request_duration_seconds_count 50000
요소 의미
# HELP 설명 (선택)
# TYPE counter / gauge / histogram / summary
{label="value"} 차원
마지막 숫자 현재 샘플 값
  • instrument 라이브러리(client_golang, micrometer 등)가 형식을 맞춰 준다
  • 예시 전체는 code/metrics.exposition 참고

4. 아키텍처와 라벨

Scrape 후 붙는 라벨

라벨 출처
job scrape_configs.job_name
instance host:port
__meta_* service discovery (K8s 등) — relabel 전

relabeling — discovery 메타를 pod, namespace쿼리용 라벨로 바꾼다.

# K8s SD 발췌 개념
- source_labels: [__meta_kubernetes_pod_label_app]
  target_label: app
  • 5편에서 말한 고카디널리티 주의 — user_id를 라벨로 넣지 않는다

TSDB

  • scrape한 샘플을 로컬 시계열 DB에 append
  • retention 기본 15일 — 운영 정책에 맞게 조정
  • 쿼리는 PromQL → HTTP API /api/v1/query

5. PromQL 입문

PromQL은 시계열 선택 + 함수 + 집계다.

시계열 선택

http_requests_total{job="api", status="500"}
  • {label="value"} — 라벨 매처 (=, !=, =~ 정규식)
  • {status=~"5.."} — 5xx 묶기

Counter → RPS

rate(http_requests_total{job="api"}[5m])
  • rate — counter의 초당 평균 증가율 (구간 [5m]은 scrape 간격보다 길게)
  • irate — 마지막 두 샘플만 (민감, 알람용 가끔)

집계

sum(rate(http_requests_total{job="api"}[5m])) by (method)
  • sum / avg / max + by (label) — 차원별 합·평균
  • RED Error rate:
sum(rate(http_requests_total{status=~"5.."}[5m]))
/
sum(rate(http_requests_total[5m]))

Histogram → 백분위

histogram_quantile(
  0.99,
  sum(rate(http_request_duration_seconds_bucket[5m])) by (le)
)
  • _bucket + le 라벨이 있어야 한다
  • histogram_quantile구간 추정 — 버킷 설계가 결과에 영향
쿼리 용도
rate(counter[5m]) RPS, 에러율
sum(...) by (label) 서비스·메서드별 합
histogram_quantile(φ, ...) p50·p95·p99

더 많은 예시는 code/promql-examples.promql 참고.

6. 실무 체크리스트

항목 권장
scrape scrape_interval 15~30s, 타임아웃 명시
RED rate + status 라벨 + duration histogram
알람 recording rule로 반복 쿼리 단순화 (Grafana 7편)
K8s kubernetes_sd_configs + pod annotation prometheus.io/scrape
보안 /metrics 내부망·인증, 민감 라벨 금지
curl -s localhost:9090/metrics | head    # Prometheus 자체 메트릭
curl -s localhost:8080/metrics | head    # 앱 exposition
promtool check config prometheus.yml

7. 정리

  • Prometheus는 pull/metrics를 scrape해 TSDB에 저장한다
  • exposition은 텍스트 + TYPE + 라벨 — instrument 라이브러리로 생성
  • PromQL은 rate·sum·histogram_quantile부터 — counter를 그대로 그리지 않는다
  • job·instance·relabel로 다중 인스턴스를 구분한다
  • 시각화·알람은 Grafana·Alertmanager와 연결 (다음 편)

다음에 다룰 것

  • Grafana
  • 대시보드, alert rule, SLO 패널

해당 내용은 Observability Engineering (Charity Majors, Liz Fong-Jones, George Miranda) 및 Prometheus Documentation (prometheus.io) 의 내용을 기반으로 합니다.

'관측성' 카테고리의 다른 글

메트릭 설계 안티패턴  (0) 2026.06.25
Grafana  (0) 2026.06.24
메트릭 기초  (0) 2026.06.22
로그로 장애 좁히기  (0) 2026.06.21
로그 수집 파이프라인  (0) 2026.06.20