본문 바로가기

PostgreSQL

13. PostgreSQL - VACUUM 내부 동작 과정

vacuum이 하는 일

  • dead tuple 제거
  • dead tuple을 가리키는 index tuple 제거
  • tuple의 oid txids를 freeze함.
  • system catalog(pg_database and pg_class)와 연관된 frozen txid를 갱신
  • clog의 불필요한 부분을 제거
  • vacuum이 수행된 table의 FSM과 VM  갱신
  • 몇몇 통계 갱신(pg_stat_all_tables 등)

 

vacuum 내부 동작 과정

  • vacuum이 필요한 table 중에 table 선택
  • table에 대해 ShareUpdateExclusiveLock 획득 (다른 transaction에서 read 허용)
  • table 내 모든 page에서 dead tuple 을 찾기 위해 scan을 하고 필요할 경우 old tuples freeze도 진행
    • dead tuple 목록은 local memory인 maintenance_work_mem에 저장됨.
    • autovacuum 수행 시 최대 autovacuum_max_workers * maintenance_work_mem 크기만큼 메모리가 할당될 수 있으므로 maintenance_work_mem 크기를 너무 높게 잡으면 안됨.
    • 대신에 autovacuum_work_mem을 별도로 설정하여 제어할 수 있음.
  • dead tuple을 가리키는 index tuples도 제거하는데 이 단계를 cleanup stage라고 함.
    • 11 version부터는 index cleanup을 진행하기 위한 파라미터인 vacuum_cleanup_index_scale_factor 를 제공하여 index cleanup이 dead tuple을 제거할 때마다 수행되지 않도록 함.
  • 위 작업을 진행할 때 maintenance_work_mem 공간이 부족해 dead tuple 스캔을 다 못하게 될 경우 아래 작업으로 이어지며 아래 작업이 끝난뒤 다시 남아있는 dead tuple을 스캔하는 작업을 진행함.
  • table data file의 page에서 dead tuples를 제거하고 live tuples를 재할당
  • vacuum을 수행한 table의 FSM과 VM을 갱신


위의 그림에서 3개의 page가 있고 첫 번째 page에 3개의 tuple 중 하나의 dead tuple인 상황
vacuum이 수행되면 index tuple 및 dead tuple이 제거
단편화를 제거하고자 남아있는 tuple에 대해서 순서정렬을 다시 진행함.
dead tuple이 제거되지만 tuple을 가리키는 line pointer는 제거되지 않고 재사용됨.
line pointer가 제거될 경우 연관된 index의 모든 index tuple들이 update되어야 하기 때문임.

 

  • index_vacuum_cleanup()으로 indexes를 clean up함.
  • 마지막 page에 tuple이 없을 경우 마지막 page를 truncate함.
  • vacuum을 수행한 table과 관련된 system catalog와 통계정보를 갱신 ( pg_stat_all_tables)
  • 통계정보 갱신 후 ShareUpdateExclusiveLock 해제

 

  • vacuum을 수행과 관련된 system catalog 및 통계정보를 갱신
  • 가능할 경우, 필요없는 clog의 file과 page를 제거.

 

참고
vacuum command는 parallel option을 13 version부터 지원
multiple indexes가 생성되어 있고 vacuum parallel option이 켜져있을 경우
index를 vacuum하고 index를 cleanup하는 단계가 병렬로 처리됨.

단, autovacuum 시에는 동작하지 않고 vacuum  command를 이용해서 수동으로 할 경우에만 병렬 처리 가능.

 

 

'PostgreSQL' 카테고리의 다른 글

15. PostgreSQL - VACUUM  (3) 2024.12.22
14. PostgreSQL - Visibility Map  (1) 2024.12.22
11. PostgreSQL - Lost updates  (4) 2024.12.21
10. visibility check rules  (4) 2024.12.19
09. transaction snapshot  (1) 2024.12.18