Cache Hit Ratio란?
- Cache Hit Ratio는 쿼리 시 디스크에서 직접 읽지 않고, 메모리에 있는 데이터를 참조한 비율
Cache Hit Ratio 계산 공식
cache_hit_ratio = blks_hit / (blks_hit + blks_read)
| 항목 | 설명 |
|---|
blks_hit | 메모리에서 블록을 읽은 횟수 |
blks_read | 디스크에서 블록을 읽은 횟수 |
전체 DB 기준 Cache Hit Ratio 확인
SELECT
datname,
blks_hit,
blks_read,
ROUND(100.0 * blks_hit / NULLIF(blks_hit + blks_read, 0), 2) AS cache_hit_ratio
FROM
pg_stat_database
ORDER BY
cache_hit_ratio ASC;
특정 테이블별 Cache Hit Ratio 분석
- PostgreSQL 13 이상에서는
pg_statio_user_tables를 통해 테이블 단위의 통계도 확인 가능
SELECT
relname AS table_name,
heap_blks_hit,
heap_blks_read,
ROUND(100.0 * heap_blks_hit / NULLIF(heap_blks_hit + heap_blks_read, 0), 2) AS cache_hit_ratio
FROM
pg_statio_user_tables
ORDER BY
cache_hit_ratio ASC;
캐시 비율 낮으면 어떻게 하나요?
| 원인 | 해결 팁 |
|---|
| shared_buffers 작음 | PostgreSQL 설정에서 증가 (shared_buffers = 1GB 등) |
| 자주 쓰는 테이블이 큼 | 특정 테이블을 메모리 캐시로 유도하기 위해 autovacuum, 인덱스 튜닝 |
| 쿼리가 너무 넓게 읽음 | 필요한 칼럼만 SELECT, LIMIT 사용 |
| 전체 테이블 스캔 많음 | 인덱스 추가 고려 |
캐시 튜닝 관련 확인 쿼리 모음
SELECT * FROM pg_stat_database;
SELECT * FROM pg_statio_user_tables;
SELECT
relname,
idx_blks_hit,
idx_blks_read,
ROUND(100.0 * idx_blks_hit / NULLIF(idx_blks_hit + idx_blks_read, 0), 2) AS index_cache_hit_ratio
FROM
pg_statio_user_tables
ORDER BY
index_cache_hit_ratio ASC;
캐시 비율 외 모니터링 지표
seq_scan / idx_scan | 인덱스 효율 확인 |
|---|
temp_bytes / temp_files | 정렬/조인 중 임시 파일 생성 여부 |
n_tup_upd, n_tup_del | dead tuple 증가 추세 (autovacuum 참고) |