본문으로 건너뛰기
10.8 OS 메트릭 연동

10.8 OS 메트릭 연동

PostgreSQL 통계만 봐서는 느린 원인이 DB인지 OS인지 모릅니다. CPU·메모리·디스크 I/O·네트워크 OS 레벨 지표를 같이 보아야 사고 진단이 가능합니다. 운영자가 봐야 할 OS 메트릭과 표준 도구들을 정리합니다.

봐야 할 메트릭 분류

분야메트릭도구
CPUusr/sys/iowait/idle, load averagetop, vmstat, sar, node_exporter
메모리total/used/free/cached/swapfree, vmstat, node_exporter
디스크 I/OIOPS, 처리량, 큐 길이, 응답 시간iostat, iotop, node_exporter
디스크 공간사용량, inodedf, node_exporter
네트워크패킷·대역폭, 드랍, 재전송ss, netstat, node_exporter
파일시스템inotify, dirty 페이지/proc/meminfo
프로세스postgres별 CPU·메모리top, ps, pidstat

node_exporter — Prometheus 표준

Prometheus 표준 호스트 메트릭 exporter. PostgreSQL 호스트 어디든 설치 권장합니다.

# 설치 (시스템 패키지 또는 GitHub release)
sudo dnf install -y node_exporter
sudo systemctl enable --now node_exporter

curl http://localhost:9100/metrics | grep -E 'node_(cpu|memory|disk|network)' | head

기본 9100 포트.

prometheus.yml:

scrape_configs:
  - job_name: 'node'
    static_configs:
      - targets: ['db1.example.com:9100', 'db2.example.com:9100']

Linux 도구 사용 사례

CPU

# 1초 간격으로 5번 스냅샷
vmstat 1 5
# procs   memory      swap  io    system cpu
# r b   swpd  free  ...   ...  us sy id wa st

# CPU 사용률 + load
top -bn1 | head -3

# 사용자/시스템/iowait 시간 추세
sar -u 1 10

iowait가 5%+ 이면 디스크 I/O 병목 가능성이 있습니다. 클라우드 환경에서는 st(steal)도 점검 — 호스트 호스팅 측 부하.

메모리

free -m
# total used free shared buff/cache available

# 누가 메모리를 많이 쓰는지
ps aux --sort=-%mem | head -10

# 슬랩·dirty 페이지 등 상세
cat /proc/meminfo | grep -E 'MemTotal|MemFree|MemAvailable|Cached|Buffers|Dirty|Writeback'

available이 적고 swap used가 늘어나면 OOM 위험합니다. Dirty가 GB 단위면 checkpoint·bgwriter가 못 따라오는 신호입니다.

디스크 I/O

# 디스크별 IOPS·처리량·응답
iostat -xz 1 5
# Device  r/s  w/s  rkB/s  wkB/s  rrqm/s  wrqm/s  %util  await

# 누구 프로세스가 I/O 많이 쓰는지
sudo iotop -oP

# 큐·latency 추세 (sysstat)
sar -d 1 10
컬럼의미
r/s, w/s초당 읽기·쓰기 횟수 (IOPS)
rkB/s, wkB/s초당 처리량
%util디스크 활용률 (100%면 포화)
await평균 응답 시간 (ms)

%util = 100이고 await가 10ms+ 이면 디스크 병목. NVMe면 1ms 미만이 정상.

디스크 공간

df -h
# PGDATA·pg_wal·log 디렉토리 점검

du -sh /var/lib/pgsql/17/data/{base,pg_wal,log}

# inode 점검 (작은 파일 매우 많은 경우)
df -i

PostgreSQL 디스크 풀 = 클러스터 정지·crash recovery. 90% 알람 + 80% 경고가 운영 표준입니다.

네트워크

# 연결 수
ss -tan | grep ':5432' | wc -l

# 인터페이스 통계
ip -s link
sar -n DEV 1 5

# 재전송·드랍
ss -ti | head

retrans가 자주 발생하면 네트워크 품질·MTU·방화벽 점검합니다.

/proc/meminfo와 PostgreSQL

PostgreSQL은 OS page cache를 적극 활용 (1.4). MemTotal이 64GB이면:

영역권장
shared_buffers~16GB (25%)
OS page cache용~40GB
백엔드 work_mem · OS 자체나머지

Cached + Buffers가 PostgreSQL이 의존하는 두 번째 캐시. 이 값이 작으면 OS가 PG에 메모리를 거의 못 주고 있다는 신호입니다.

OOM Killer 추적

# OOM 이력
sudo dmesg | grep -iE 'killed process|out of memory'
journalctl -k | grep -iE 'oom|killed'

postgres가 OOM에 죽었다면:

  • work_mem 너무 큼
  • max_connections 너무 큼
  • 메모리 누수 (드물지만 확장 모듈 의심)

postmaster 자체 보호는 systemd 유닛의 PG_OOM_ADJUST_VALUE(10.2 참고).

node_exporter 핵심 메트릭

Prometheus 메트릭의미
node_cpu_seconds_total{mode="iowait"}CPU iowait
node_memory_MemAvailable_bytes사용 가능 메모리
node_disk_io_time_seconds_total디스크 사용 시간
node_disk_read_bytes_total, node_disk_written_bytes_total누적 I/O
node_filesystem_avail_bytes디스크 가용 공간
node_network_receive_bytes_total네트워크
node_load1, node_load5load average
node_textfile_collector자체 메트릭 파일 (커스텀)

통합 대시보드

PostgreSQL 진단은 PG 메트릭 + OS 메트릭을 한 화면에 두는 게 효율적. Grafana 대시보드 예시 구성:

┌─────────────────┬─────────────────┬─────────────────┐
│  pg_up · 연결수  │  CPU iowait     │  Disk %util     │
├─────────────────┼─────────────────┼─────────────────┤
│  cache hit %    │  Memory pressure│  Disk space     │
├─────────────────┼─────────────────┼─────────────────┤
│  WAL 생성량      │  network        │  load average    │
├─────────────────┴─────────────────┴─────────────────┤
│  TOP 쿼리 (pg_stat_statements)                       │
└─────────────────────────────────────────────────────┘

운영 사고 시 한 페이지에서 PG와 OS를 같이 봐 원인 분리합니다.

자주 보이는 사고 패턴

증상의심
쿼리 느린데 PG 카운터는 정상OS iowait, %util 봐야
쿼리는 빠른데 commit이 느림디스크 fsync latency — pg_stat_wal.wal_sync_time
메모리 사용량 폭증work_mem × connections, OOM 직전
디스크 풀 갑작스러움WAL archive 실패 또는 replication slot 정체
연결 수 폭증애플리케이션 leak, pooler 부족
시계열 그래프에 cliffautovacuum·체크포인트·backup

클라우드 환경의 추가 메트릭

클라우드메트릭
AWS RDSCPUUtilization, DatabaseConnections, FreeStorageSpace, ReadIOPS, WriteIOPS, BurstBalance
Azurecpu_percent, storage_percent, active_connections
GCPcpu/usage_time, network/connections
NCPCPU·메모리·디스크

EBS gp3·io2 같은 IOPS 제한은 클라우드 특유의 함정. BurstBalance가 0으로 떨어지면 기본 IOPS만 사용 → 갑작스러운 느림.

iowait + %util 동시 관찰: 둘 다 높으면 디스크 자체 한계. iowait 높은데 %util 낮으면 네트워크 스토리지 latency(EBS, NFS) 문제. 분리해서 봐야 정확합니다.

정리

  • PostgreSQL 모니터링은 PG 메트릭 + OS 메트릭 양쪽 필수
  • node_exporter가 Prometheus 표준 — postgres_exporter와 함께
  • 진단 도구: vmstat, iostat, iotop, sar, ss, dmesg
  • 디스크 풀과 OOM이 PostgreSQL을 가장 자주 죽이는 OS 사고
  • Grafana 대시보드에 PG·OS를 한 페이지로
  • 클라우드 환경은 IOPS 한도·burst balance 같은 추가 메트릭

Part X 설정과 운영이 끝났습니다. 다음 Part XI에서는 백업과 복구를 봅니다.