7.1 pg_stat_statements
pg_stat_statements는 literal을 normalize한 query 단위로 execution statistics를 누적합니다. Planning statistics는 pg_stat_statements.track_planning을 on으로 설정한 경우에만 수집되며 기본값은 off입니다. 한 번 느린 query보다 전체 database time을 많이 쓰는 query를 찾는 데 적합합니다.
SELECT queryid, calls,
round(total_exec_time::numeric, 1) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
rows,
shared_blks_hit, shared_blks_read,
temp_blks_read, temp_blks_written,
left(query, 120) AS sample
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
네 가지 관점
- Total time: 전체 resource 소비
- Mean과 variance: 한 번의 latency와 흔들림
- Calls: N+1과 지나친 호출
- Rows, buffers, temp: 작업량과 spill
Counter는 reset 또는 restart 구간을 포함합니다. stats_reset, 배포 시각, traffic을 함께 기록합니다. Query ID는 server, version, schema 조건에 따라 장기 식별자로 주의해서 사용합니다.
다른 user의 query text와 queryid는 권한 제한을 받습니다. Monitoring role은 pg_read_all_stats 등 필요한 최소 권한으로 구성하고 query text의 개인정보나 secret 노출을 관리합니다.