🐘 PostgreSQL β€” Administrasi & Disaster Recovery

Filosofi: PostgreSQL bukan MySQL yang bisa mysqldump tiap jam tanpa mikir. PG punya arsitektur MVCC, WAL, replication slots β€” backup yang salah bisa korup replication atau bloat disk.


Arsitektur Dasar

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Client  │─────▢│  Postmaster  │─────▢│   Shared   β”‚
β”‚          β”‚      β”‚  (PID 1)     β”‚      β”‚  Buffers   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                         β”‚
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β–Ό          β–Ό          β–Ό
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚ WAL     β”‚ β”‚ Check-  β”‚ β”‚ Archive β”‚
        β”‚ Writer  β”‚ β”‚ pointer β”‚ β”‚ (optional)β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
KomponenFungsi
WAL (Write-Ahead Log)Semua perubahan ditulis ke WAL dulu sebelum data page. Ini jaminan crash recovery
CheckpointFlush dirty buffers ke disk. Frekuensi diatur checkpoint_timeout (default 5 menit)
AutovacuumMembersihkan dead tuples β€” MVVC遗产. Kalau mati β†’ bloat
Replication SlotMenjamin WAL gak dihapus sebelum replica menerimanya

Backup Strategy β€” 3 Lapisan

Aturan Emas

Backup is useless unless you’ve verified restore. Selalu test restore di environment terpisah.

Lapisan 1 β€” Logical Backup (pg_dump / pg_dumpall)

ToolUntukKelemahan
pg_dump1 databaseLambat untuk DB >50GB
pg_dumpallSemua DB + global objects (roles, tablespaces)Output campur aduk, butuh filtering

Command aman:

# Single DB
pg_dump -h localhost -U postgres -d mydb \
  --no-owner --no-acl \
  | gzip > mydb_$(date +%F).sql.gz
 
# All DBs (PG14+)
pg_dumpall -h localhost -U postgres \
  -c  # include DROP/CREATE DB
  | grep -v '^\\\\restrict' \  # ⚠️ PG16+ issue
  | gzip > full_$(date +%F).sql.gz

\restrict Trap

pg_dumpall -c di PG14 menghasilkan \restrict lines yang gak dikenal PG16+. Filter dengan grep -v '^\\\\restrict' sebelum restore.

Lapisan 2 β€” Physical Backup (pg_basebackup)

Untuk replica setup atau PITR (Point-In-Time Recovery):

pg_basebackup -h primary -U replicator \
  -D /backup/pg_base \
  -X stream --progress --verbose
MetodeRecovery PointUkuranKecepatan Restore
pg_dumpSaat eksekusiKecil (SQL)Lambat (replay SQL)
pg_basebackup+ WAL archiveBesar (binary)Cepat (copy file)

Lapisan 3 β€” WAL Archiving (Continuous Archiving)

Untuk PITR ke detik tertentu:

# postgresql.conf
wal_level = replica
archive_mode = on
archive_command = 'cp %p /backup/wal/%f'

Restore PITR: Stop PG β†’ restore base backup β†’ buat recovery.signal β†’ atur restore_command β†’ start.


Container Deployment (Podman/Docker)

# docker-compose.yml
services:
  postgres:
    image: postgis/postgis:16-3.4 # PG16 + PostGIS
    volumes:
      - pgdata:/var/lib/postgresql/data
      - ./backup:/backup
    environment:
      POSTGRES_PASSWORD: ${PG_PASSWORD}
    ports:
      - "5432:5432"

PG16 + PostGIS

Image postgis/postgis sudah include PostGIS extension. Gak perlu install manual. Tapi pull-nya ~500MB β€” siapin bandwidth.

Version Migration (PG14 β†’ PG16)

StepCommandCatatan
1. Dump oldpg_dumpall -c | gzip > old.sql.gzDi PG14
2. Spin up newContainer PG16 + volume kosong
3. Adjust dumpzcat old.sql.gz | grep -v '^\\\\' > clean.sqlBuang \restrict
4. Restorepsql -f clean.sql postgresError toleran
5. Verify\dt+, row count sampleJangan percuma

Performance Tuning Dasar

ParameterDefaultRecommendedNotes
shared_buffers128MB25% RAMBuffer cache PG
effective_cache_size4GB75% RAMEstimasi OS cache
work_mem4MB8-16MBPer sort operation
maintenance_work_mem64MB10% RAMUntuk VACUUM, index
max_connections10020-50Setiap koneksi makan RAM
random_page_cost4.01.1 (SSD)Biar PG prefer index scan
autovacuumONONJangan matikan

Common Failures & Fixes

GejalaPenyebabFix
Connection refusedPort gak terbuka / service matisystemctl status postgresql atau podman logs
Too many connectionsmax_connections penuhKurangi pool size di app, atau naikkan max_connections
WAL full (disk 100%)Archive gagal / replication lagCek pg_stat_replication, bersihin WAL dengan pg_archivecleanup
Bloat besarAutovacuum gak jalanSELECT pg_stat_progress_vacuum; VACUUM VERBOSE
Role does not existBackup tanpa --no-owner di env bedaRestore dengan --no-owner atau create role dulu


🧠 Berpikir β€” Metodologi Penyusunan Catatan

Catatan ini disusun melalui proses berpikir terstruktur sebagai berikut:

1. Thinking Type yang Digunakan

TypeKenapaBagian
Analytical ThinkingMemecah backup strategy jadi 3 lapis (logical, physical, WAL), membandingkan tradeoff tiap opsiBackup Strategy, Performance Tuning
Systems ThinkingMemetakan interaksi komponen PG — WAL→checkpoint→archive, bagaimana satu kegagalan (archive gagal) menyebabkan WAL fullArsitektur Dasar, Common Failures
Concrete ThinkingMenyusun command exact untuk backup, restore, migrasi β€” step-by-step tanpa asumsiContainer Deployment, Migration Steps
Critical ThinkingMempertanyakan asumsi umum β€” β€œbackup is useless unless verified”, \\restrict trap PG14β†’16Aturan Emas, Migration warnings

2. Background Knowledge (Pra-Penulisan)

  • PG page structure: MVCC, WAL segments (16MB default), checkpoint distance, autovacuum triger
  • pg_dump internals: -c flag produces DROP DATABASE + CREATE DATABASE + \\connect β€” di PG14 output includes \\restrict (PG16 gak kenal)
  • PostGIS container: image postgis/postgis:16-3.4 sudah bundle ekstensi + pgvector mulai support
  • Memory tuning: shared_buffers 25% RAM adalah sweet spot β€” >40% malah hurt karena PG pake OS page cache juga
  • Failed experience: restoration failure karena missing role, tablespace path beda β€” ditangkap di Common Failures

3. RAG Vault β€” Dokumen yang Dikonsultasi

DokumenKontribusi
CD Pipeline GuidePG + Podman deployment context, environment variables pattern
DevOps RoadmapContainer deployment patterns, Docker Compose structure
Data Engineering RoadmapPosisi PG dalam pipeline data secara umum
Infrastructure AdministratorServer layout β€” PG jadi salah satu service

4. Sintesis β€” Bagaimana Bagian Bergabung

Background Knowledge (first principles)
    β”‚
    β–Ό
RAG Vault (konteks vault existing)
    β”‚
    β–Ό
Analytical:  Backup β†’ 3 layers β†’ compare physical vs logical
    β”‚
    β–Ό
Systems:     Arsitektur PG β†’ WAL β†’ checkpoint β†’ failure cascade β†’ tuning
    β”‚
    β–Ό
Concrete:    Exact commands β†’ Migration steps β†’ Container YAML
    β”‚
    β–Ό
Critical:    Warning traps β†’ `\\restrict` β†’ verify restore β†’ performance limits

5. Sequential Thinking Steps

Thought 1 (Cognitive):  "PG architecture = WAL + MVCC. Gak bisa disamakan dgn MySQL."
Thought 2 (Analytical): "Backup harus 3 layer. Logical untuk portability, physical untuk speed, WAL untuk PITR."
Thought 3 (Critical):   "Tapi guarantee backup cuma valid kalau dites restore. Banyak org skip ini."
Thought 4 (Systems):    "WAL bisa full kalau archive gagal. Replication slot bikin WAL gak dihapus. Ini cascade."
Thought 5 (Concrete):   "Command: pg_dumpall -c | grep -v '^\\restrict' | gzip. Step by step."
Thought 6 (Analytical): "Migrasi PG14β†’16 β€” apa yang beda? \restrict, default parameter, extension version."
Thought 7 (Convergent): "Filter 5 parameter tuning paling impactful: shared_buffers, effective_cache_size, work_mem, random_page_cost, max_connections."

πŸ”— Lihat Juga