ข้ามไปที่เนื้อหา

PostgreSQL Server Tuning: คู่มือตั้งค่าฉบับเต็มสำหรับปี 2026

PostgreSQL ที่เพิ่งติดตั้งเสร็จมาพร้อมค่าที่ตั้งไว้ให้รันบนโน้ตบุ๊กเครื่องเดียวที่ใช้กันหลายคนเมื่อปี 2005 ได้โดยไม่พัง shared_buffers = 128MB work_mem = 4MB max_connections = 100 ค่า default ชุดนี้ไม่เปลี่ยนมาเกินสิบปีแล้ว และตั้งใจให้ conservative ไว้ก่อน เพื่อให้ server start ได้บนทุกเครื่องโดยไม่ crash

แต่ production server ของคุณไม่ใช่โน้ตบุ๊กปี 2005

คู่มือนี้รวมทุก parameter ใน postgresql.conf ที่มีผลจริง การตั้งค่าระดับ OS ที่อยู่ข้างใต้ และ configuration ที่หยิบไปใช้ได้เลยสำหรับ server ขนาดที่เจอบ่อย ทั้งหมดอัปเดตสำหรับ PostgreSQL 17 บน Linux ในปี 2026 โพสต์นี้เป็นภาค server configuration คู่กับ คู่มือ tuning query และ index ที่พูดเรื่อง EXPLAIN, index และ PgBouncer


PostgreSQL ใช้ Memory ยังไง

ก่อนจะแก้ parameter ตัวไหน ต้องเข้าใจ memory model ก่อน PostgreSQL แบ่ง memory เป็นสองส่วนแยกกัน:

┌─────────────────────────────────────────────────┐
│                   SYSTEM RAM                     │
│                                                  │
│  ┌────────────────────────┐  ┌────────────────┐  │
│  │   Shared Memory Pool   │  │  OS Page Cache │  │
│  │  (shared_buffers)      │  │  (free memory) │  │
│  │  ┌──────────────────┐  │  │                │  │
│  │  │  Buffer Cache    │  │  │  PostgreSQL    │  │
│  │  │  (data pages)    │  │  │  reads data    │  │
│  │  ├──────────────────┤  │  │  through OS    │  │
│  │  │  WAL Buffers     │  │  │  cache too     │  │
│  │  │  (wal_buffers)   │  │  └────────────────┘  │
│  │  └──────────────────┘  │                      │
│  └────────────────────────┘                      │
│                                                  │
│  ┌────────────────────────┐                      │
│  │  Per-Process Memory    │  (× max_connections) │
│  │  work_mem × ops        │                      │
│  │  + stack + overhead    │                      │
│  └────────────────────────┘                      │
└─────────────────────────────────────────────────┘

Shared memory (shared_buffers) จองครั้งเดียวตอน startup แล้วทุก process ใช้ร่วมกัน Per-process memory (work_mem) จองแยกตาม operation ของแต่ละ query เลยโตตามจำนวน connection ส่วน OS page cache เป็น cache อีกชั้นที่ PostgreSQL อ่านข้อมูลผ่าน นี่แหละเหตุผลที่ effective_cache_size สำคัญ ทั้งที่ไม่ได้จอง memory เลยสักไบต์

Process ต่าง ๆ ของ PostgreSQL

Process หน้าที่
postmaster Daemon หลัก spawn process อื่นทั้งหมดและรับ connection
checkpointer Flush dirty page จาก shared_buffers ลง disk ตอน checkpoint
bgwriter ทยอยเขียน dirty page ลง disk ระหว่างรอบ checkpoint
walwriter Flush WAL buffer ลง WAL file
autovacuum launcher Schedule autovacuum worker ให้แต่ละ database
autovacuum worker รัน VACUUM และ ANALYZE บน table
archiver Copy WAL segment ไปเก็บที่ archive (ถ้าเปิดไว้)
stats collector รวบรวม runtime statistics (ตั้งแต่ PG15+ ย้ายไปรวมกับ postmaster แล้ว)
backend (per connection) รัน query ให้ client หนึ่ง session
parallel worker รันงานส่วนหนึ่งของ parallel query

Backend process แต่ละตัวกิน private memory ของตัวเองเพิ่มจาก shared memory อีก max_connections เลยตั้งสูงเกินไปไม่ได้


Part 1: Parameter ด้าน Memory

shared_buffers — Cache หลัก

Page cache ของ PostgreSQL เอง เวลา query อ่าน page ตัว PostgreSQL จะดูใน shared_buffers ก่อน ไม่เจอค่อยไปดู OS page cache แล้วค่อยลงไปอ่าน disk

shared_buffers = 8GB    # 25% of total RAM

สูตร: shared_buffers = total_RAM × 0.25

RAM ของ server shared_buffers ที่แนะนำ
4 GB 1 GB
16 GB 4 GB
32 GB 8 GB
64 GB 16 GB
128 GB 16–32 GB

ตั้งเกิน 25% ได้ผลเพิ่มน้อยลงเรื่อย ๆ เพราะ sequential scan ยังพึ่ง OS page cache อยู่ ถ้าดันไปถึง 40% ขึ้นไป OS cache จะเหลือน้อยจน sequential read ช้าลง

Huge pages: ถ้าตั้ง shared_buffers ไว้ ≥ 8 GB ให้เปิด huge pages ด้วย จะช่วยลด TLB pressure:

# postgresql.conf
huge_pages = try    # try | on | off
# /etc/sysctl.conf — set before PostgreSQL starts
vm.nr_hugepages = 4096   # (shared_buffers_bytes / 2MB) + 10% overhead
sysctl -p

work_mem — Memory ต่อ Sort/Hash หนึ่งครั้ง

work_mem จองต่อ sort, hash join หรือ bitmap index operation หนึ่งครั้ง ไม่ใช่ต่อ connection Query ซับซ้อนตัวเดียวอาจมี 5–10 operation รันพร้อมกัน ถ้า server มี 200 connection ช่วง peak อาจจอง work_mem พร้อมกันเป็นหลักพันก้อน

work_mem = 32MB    # Conservative OLTP default

สูตรที่ปลอดภัย: work_mem = (total_RAM × 0.25) / max_connections

RAM ของ server max_connections work_mem ที่ปลอดภัย
16 GB 100 40 MB
32 GB 100 80 MB
32 GB 200 40 MB
64 GB 200 80 MB

เช็กว่า query spill ลง disk หรือเปล่า ถ้าเจอแปลว่า work_mem ต่ำไป:

-- Look for "Sort Method: external merge Disk" in query plans
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM large_table ORDER BY column1, column2;

สำหรับ analytics query ให้เพิ่ม work_mem เฉพาะ session นั้น อย่าไปเพิ่มทั้ง server:

SET work_mem = '512MB';
-- Now run the heavy analytic query
SELECT ...;

maintenance_work_mem — Memory สำหรับ Vacuum และสร้าง Index

VACUUM, CREATE INDEX, CLUSTER และ ALTER TABLE ADD FOREIGN KEY ใช้ค่านี้ ต่างจาก work_mem ตรงที่ maintenance operation รันพร้อมกันแค่ไม่กี่ตัว เลยตั้งให้สูงกว่ากันเยอะได้

maintenance_work_mem = 2GB    # 1–4 GB is typical for 32 GB+ servers

Autovacuum worker ไม่ใช้ maintenance_work_mem แต่ไปใช้ autovacuum_work_mem แทน:

autovacuum_work_mem = 512MB   # -1 means fall back to maintenance_work_mem

effective_cache_size — บอก Planner ว่ามี Cache เท่าไหร่

Parameter ตัวนี้ไม่ได้จอง memory เลย แค่บอก query planner ว่าให้ถือว่ามี cache รวม (shared_buffers + OS page cache) อยู่ประมาณเท่าไหร่ ตั้งค่ายิ่งสูง planner ยิ่งเลือก index scan แทน sequential scan

effective_cache_size = 24GB   # 75% of total RAM

สูตร: effective_cache_size = total_RAM × 0.75

ดู OS cache ที่มีจริงบนเครื่องก่อนตั้งค่า:

free -h
#              total        used        free      shared  buff/cache   available
# Mem:          31Gi        6.2Gi       1.1Gi     1.5Gi      24Gi       23Gi
# → effective_cache_size ≈ 24GB (available column)

temp_buffers — Cache สำหรับ Temporary Table

Cache ของแต่ละ session ไว้ใช้กับ temporary table ค่า default 8MB พอสำหรับ application ส่วนใหญ่ เพิ่มเฉพาะตอนที่สร้าง temporary table ขนาดใหญ่ใน session

temp_buffers = 32MB    # Increase only if using large temp tables

Part 2: จัดการ Connection

max_connections

ทุก connection จะ spawn backend process หนึ่งตัว กิน private memory ราว ~5–10 MB บวก stack overhead อีก ตั้งค่านี้สูงเกินไปก็เปลือง RAM แถม locking contention ยังเพิ่มขึ้นด้วย

max_connections = 200   # Direct connections without a pooler
max_connections = 100   # With PgBouncer in front (recommended)

ข้อจำกัดที่เลี่ยงไม่ได้:

Peak memory = shared_buffers + (max_connections × work_mem × ops_per_query) + OS overhead

สมมติ work_mem = 32MB, query ละ 3 op และมี 200 connection: กรณีแย่สุดจะกิน 200 × 32MB × 3 = 19.2 GB

กฎ: วาง PgBouncer แบบ transaction mode ไว้หน้า database เพื่อ multiplex connection จาก application แล้วตั้ง max_connections ตามจำนวน query ที่คาดว่าจะรันพร้อมกันจริง ไม่ใช่ตามจำนวน thread ของ application

superuser_reserved_connections

superuser_reserved_connections = 3   # Default: 3

ค่านี้กัน connection ไว้ให้ DBA เข้าได้เสมอ แม้ server จะรับ connection เต็มแล้ว ห้ามตั้งเป็น 0 เด็ดขาด ไม่งั้นตอนเกิด connection storm คุณจะเข้า server ตัวเองไม่ได้


Part 3: WAL และ Checkpoint Tuning

WAL (Write-Ahead Log) คือกลไกด้าน durability ทุกการเขียนต้องลง WAL ก่อน แล้วค่อยไปแก้ data page ส่วน checkpoint คือ process ที่ flush data page ที่แก้แล้วลง disk และ mark จุดใน WAL ที่ restart ต่อได้อย่างปลอดภัย

ถ้า tune checkpoint ไม่ดีจะเจอ write storm คือ I/O พุ่งเป็นช่วง ๆ ระหว่าง flush dirty page จน query สะดุด

wal_buffers

Buffer ใน memory ที่พักข้อมูล WAL ไว้ก่อนเขียนลง WAL file ค่า default (-1) จะตั้งให้อัตโนมัติเป็น 1/32 ของ shared_buffers สูงสุดไม่เกิน 64MB ถ้า workload เขียนหนัก ให้ตั้งเองไปเลย:

wal_buffers = 64MB    # -1 auto; 64MB is the practical ceiling

checkpoint_completion_target

ค่านี้ให้ checkpoint ทยอยเขียน I/O ไปเรื่อย ๆ แทนที่จะ flush ทุกอย่างทีเดียวตอนถึงจังหวะ checkpoint ค่า default 0.9 แปลว่า "เขียน dirty page ให้หมดภายใน 90% ของช่วงเวลาระหว่าง checkpoint" ค่านี้ดีอยู่แล้ว แค่อย่าลดต่ำกว่า 0.7

checkpoint_completion_target = 0.9

checkpoint_timeout และ max_wal_size

checkpoint_timeout คือระยะห่างสูงสุดระหว่าง checkpoint สองรอบ (default 5min) ส่วน max_wal_size จะสั่ง checkpoint ทันทีที่ WAL โตเกินขนาดนี้ (default 1GB)

checkpoint_timeout = 15min    # Longer = fewer checkpoints = less write I/O
max_wal_size       = 4GB      # Larger = fewer checkpoints; needs more recovery time after crash
min_wal_size       = 1GB      # Keep recycled WAL segments instead of deleting

หาต้นเหตุ checkpoint storm:

log_checkpoints = on    # Log every checkpoint with its statistics
LOG: checkpoint complete: wrote 14823 buffers (22%); 0 WAL file(s) added,
     1 removed, 5 recycled; write=120.192 s, sync=0.014 s, total=120.221 s;
     sync files=12, longest=0.014 s, shortest=0.001 s;
     distance=43901 kB, estimate=44765 kB

ถ้าเวลา write เข้าใกล้ checkpoint_timeout แปลว่า checkpointer เขียนไม่ได้หยุดเลย ให้เพิ่ม max_wal_size เพื่อให้การเขียนกระจายออกไปในช่วงเวลาที่ยาวขึ้น

wal_compression

PostgreSQL 17 บีบอัด WAL ได้ทั้ง LZ4, Zstd และ zlib เสีย CPU เพิ่มนิดหน่อยแต่ I/O ลดลง บน hardware ยุคนี้แทบจะคุ้มทุกครั้ง

wal_compression = lz4    # or zstd for better compression; default: off

synchronous_commit

ค่านี้กำหนดว่า WAL ต้องไปถึงไหนถึงจะนับว่า durable ค่า default on จะรอ WAL flush ลง disk ก่อน แล้วค่อยตอบ client ว่า commit สำเร็จ ปลอดภัยแต่ช้ากว่า

# For maximum durability (default):
synchronous_commit = on

# For higher write throughput (risk: lose ~wal_writer_delay ms of commits on crash):
synchronous_commit = off      # Never for financial data

# For replication:
synchronous_commit = remote_write   # Waits for standby to receive WAL (not fsync)
synchronous_commit = remote_apply   # Waits for standby to apply WAL (zero data loss)

Part 4: Storage และ I/O Tuning

random_page_cost และ seq_page_cost

สองค่านี้บอก planner ว่าอ่าน page แบบ random แพงกว่าแบบ sequential กี่เท่า ค่า default (4.0 และ 1.0) ตั้งมาสำหรับจานหมุน แต่บน SSD สัดส่วนนี้ต่างไปมาก

# SSD (NVMe or SATA):
random_page_cost = 1.1
seq_page_cost    = 1.0

# Spinning disk (7200 RPM):
random_page_cost = 4.0
seq_page_cost    = 1.0

# Cloud block storage (EBS, GCP PD — latency varies):
random_page_cost = 1.5

ผลกระทบ: ถ้าตั้ง random_page_cost สูงไป planner จะเลือก sequential scan แทน index scan สวนทางกับที่ควรเป็นบน SSD เลย

effective_io_concurrency

จำนวน I/O request ที่ PostgreSQL ยิงพร้อมกันตอนทำ bitmap heap scan ค่า default 1 เหมาะกับจานหมุน แต่ SSD รับ request พร้อมกันทีละเยอะ ๆ ได้สบาย

effective_io_concurrency = 200    # SSD/NVMe
effective_io_concurrency = 2      # Spinning disk

wal_level และค่าเกี่ยวกับ archive

wal_level = replica    # Minimum for streaming replication; 'logical' for logical decoding

ถ้าใช้ WAL archiving ทำ PITR:

archive_mode = on
archive_command = 'pgbackrest --stanza=pg_cluster archive-push %p'
archive_timeout = 60    # Force segment switch every 60s even with low write volume

Part 5: Parallel Query Tuning

PostgreSQL ทำ sequential scan, join, aggregation และ index build แบบ parallel ได้ parameter หลักมีสี่ตัว:

max_worker_processes      = 8     # Total parallel worker pool (system-wide)
max_parallel_workers      = 8     # Subset available for parallel queries
max_parallel_workers_per_gather = 4    # Max workers for a single query node
max_parallel_maintenance_workers = 4   # For CREATE INDEX, VACUUM

กฎง่าย ๆ: ตั้ง max_worker_processes เท่ากับจำนวน CPU core และ max_parallel_workers_per_gather เท่ากับครึ่งหนึ่งของจำนวน core

Parallel Query เริ่มทำงานตอนไหน

PostgreSQL จะรัน query แบบ parallel ก็ต่อเมื่อ cost ที่ประเมินไว้สูงกว่า parallel_setup_cost และ cost ของแต่ละ chunk สูงกว่า parallel_tuple_cost OLTP query ที่แตะข้อมูล < 10M row แทบไม่ได้อะไรจาก parallelism แต่ analytics query อาจเร็วขึ้น 4–8×

อยากบังคับเปิดหรือปิด parallelism เฉพาะ session:

-- Enable maximum parallelism for this session
SET max_parallel_workers_per_gather = 8;

-- Disable (useful for debugging plan differences)
SET max_parallel_workers_per_gather = 0;

Parallel Index Build (PostgreSQL 11+)

max_parallel_maintenance_workers = 4
-- Build index using 4 workers simultaneously
SET max_parallel_maintenance_workers = 4;
CREATE INDEX CONCURRENTLY idx_large_table ON large_table (column1);

Part 6: ตั้งค่า Autovacuum ฝั่ง Server

Autovacuum คือ process ที่ทำ maintenance อยู่เบื้องหลังของ PostgreSQL คอยเก็บกวาด dead tuple อัปเดต table statistics และกันไม่ให้เกิด transaction ID wraparound ถ้า tune autovacuum ไม่พอ นี่คือสาเหตุที่เจอบ่อยที่สุดที่ database ที่กำลังโตจู่ ๆ ก็ช้าลง

Parameter หลักของ Autovacuum

# Enable (should always be on in production)
autovacuum = on

# Worker pool
autovacuum_max_workers        = 5      # Default: 3; increase for busy databases
autovacuum_naptime            = 30s    # How often the launcher checks for work

# Trigger thresholds (when to start vacuuming)
autovacuum_vacuum_threshold   = 500    # Minimum dead tuples before trigger
autovacuum_vacuum_scale_factor = 0.05  # + 5% of live rows (default: 0.20 = 20%)
autovacuum_analyze_threshold  = 250
autovacuum_analyze_scale_factor = 0.02

# Transaction ID wraparound emergency vacuum
autovacuum_freeze_max_age     = 150000000   # Default: 200M; reduce for safety
autovacuum_multixact_freeze_max_age = 350000000

ทำไม scale_factor ถึงสำคัญ: ค่า default 0.20 แปลว่า table ขนาด 100M row ต้องมี dead tuple สะสมถึง 20M กว่า vacuum จะเริ่ม ถ้ามี update 1,000 ครั้งต่อวินาที ก็ต้องรอถึง 5.5 ชั่วโมง ลดเหลือ 0.05 จะ trigger ที่ 5M dead tuple (ราว 80 นาที)

Throttle I/O ของ Autovacuum

PostgreSQL จำกัดความเร็ว autovacuum ไว้ ไม่ให้ไปกวน foreground query กลไกที่ใช้เป็นระบบ credit อ่านหรือเขียน page แต่ละครั้งจะหัก credit พอ credit หมด autovacuum ก็ sleep รอ

autovacuum_vacuum_cost_delay  = 2ms     # Sleep duration when cost limit hit (SSD: 2ms, disk: 20ms)
autovacuum_vacuum_cost_limit  = 400     # Default: 200; credits per vacuum cycle

Server ที่ใช้ SSD: ลด delay เพิ่ม limit:

autovacuum_vacuum_cost_delay  = 2ms
autovacuum_vacuum_cost_limit  = 800

จานหมุน: เพิ่ม delay ลด limit กัน I/O เต็ม:

autovacuum_vacuum_cost_delay  = 20ms
autovacuum_vacuum_cost_limit  = 200

Monitor สุขภาพของ Autovacuum

-- Tables where autovacuum is falling behind
SELECT
    schemaname,
    relname AS table,
    n_live_tup,
    n_dead_tup,
    round(n_dead_tup * 100.0 / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
    last_autovacuum,
    last_autoanalyze,
    autovacuum_count
FROM pg_stat_user_tables
WHERE n_dead_tup > 10000
ORDER BY n_dead_tup DESC
LIMIT 20;
-- Currently running autovacuum workers
SELECT
    datname,
    pid,
    now() - xact_start AS runtime,
    query
FROM pg_stat_activity
WHERE query LIKE '%autovacuum%'
  AND query NOT LIKE '%pg_stat_activity%'
ORDER BY xact_start;

Transaction ID Wraparound — เหตุฉุกเฉินที่ห้ามปล่อยให้เกิด

PostgreSQL ใช้ transaction ID ขนาด 32-bit พอนับไปถึง 2 พันล้าน transaction ตัวเลขจะวนกลับมาเริ่มใหม่ (wraparound) พอใกล้จะ wraparound เมื่อไหร่ PostgreSQL จะเข้า read-only emergency mode ทันที เพื่อกันข้อมูลเสียหาย

เช็กว่าตอนนี้ใกล้แค่ไหนแล้ว:

SELECT
    datname,
    age(datfrozenxid) AS xid_age,
    2147483647 - age(datfrozenxid) AS xids_remaining
FROM pg_database
ORDER BY age(datfrozenxid) DESC;

ถ้า xid_age ขึ้นไปใกล้ 1.5 พันล้าน ให้รัน emergency vacuum ทันที:

vacuumdb --all --freeze --analyze-in-stages -j 4

Part 7: Logging และ Observability

เลือกเปิด log ให้พอดี น้อยไปก็พลาด slow query เยอะไปก็มีแต่ noise เต็มไฟล์

# Where to log
log_destination        = 'stderr'
logging_collector      = on
log_directory          = '/var/log/postgresql'
log_filename           = 'postgresql-%Y-%m-%d.log'
log_rotation_age       = 1d
log_rotation_size      = 100MB
log_file_mode          = 0640

# What to log
log_min_messages        = warning      # Server log level
log_min_error_statement = error        # Log failed statements at ERROR+

# Slow query logging — the most important setting
log_min_duration_statement = 1000      # Log queries taking > 1 second (in ms)
                                       # Set to 0 to log everything (dev only)

# Checkpoint and lock logging
log_checkpoints         = on
log_lock_waits          = on
deadlock_timeout        = 1s           # Log deadlocks after 1 second

# Connection logging (enable if debugging connection storms)
log_connections         = off          # High volume on busy servers
log_disconnections      = off

# Temporary file logging (catch queries spilling to disk)
log_temp_files          = 0            # Log any temp file creation (0 = all sizes)

# Statement detail
log_line_prefix         = '%m [%p] %q%u@%d '   # Timestamp [PID] user@database
log_statement           = 'ddl'                  # Log all DDL (CREATE, ALTER, DROP)

auto_explain — EXPLAIN อัตโนมัติสำหรับ Slow Query

ตัวนี้ log output ของ EXPLAIN ANALYZE ให้อัตโนมัติทุกครั้งที่ query ช้าเกิน threshold ขาดไม่ได้เลยเวลาไล่หา slow query ที่โผล่มาเป็นพัก ๆ เพราะไม่ต้องนั่งรันเองทีละตัว

shared_preload_libraries = 'pg_stat_statements,auto_explain'

auto_explain.log_min_duration = 2000    # Log plans for queries > 2 seconds
auto_explain.log_analyze      = true    # Include actual vs estimated rows
auto_explain.log_buffers      = true    # Include buffer I/O stats
auto_explain.log_nested_statements = true  # Include subquery plans
auto_explain.sample_rate      = 1.0     # 1.0 = every query; 0.1 = 10% sample

Part 8: OS-Level Tuning

Performance ของ PostgreSQL ขึ้นกับการตั้งค่า OS พอ ๆ กับ postgresql.conf ตั้งค่าพวกนี้ไว้ใน /etc/sysctl.conf แล้ว reboot ไปก็ยังอยู่

Virtual Memory

# /etc/sysctl.conf

# Prefer swapping file cache over anonymous memory (PostgreSQL manages its own cache)
vm.swappiness = 10           # Default: 60; lower = less aggressive swapping

# Dirty page writeback — controls when kernel starts writing dirty pages
vm.dirty_ratio          = 10   # Flush when dirty pages hit 10% of RAM
vm.dirty_background_ratio = 5  # Start background flush at 5% of RAM

# For large shared_buffers (> 8 GB), increase shared memory limits
kernel.shmmax = 17179869184   # Bytes: >= shared_buffers size
kernel.shmall = 4194304       # Pages: kernel.shmmax / page_size (usually 4096)
sysctl -p   # Apply without reboot

Transparent Huge Pages — ปิดไปเลยสำหรับ PostgreSQL

THP (Transparent Huge Pages) ทำให้ latency กระตุกเวลา kernel compact memory PostgreSQL จัดการ huge pages เองผ่าน huge_pages = try อยู่แล้ว ปิด THP ไปได้เลย:

# /etc/rc.local or a systemd service
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag
# Verify
cat /sys/kernel/mm/transparent_hugepage/enabled
# [always] madvise never  → should show: always madvise [never]

เพดาน File Descriptor

แต่ละ connection ของ PostgreSQL เปิด file descriptor หลายตัว (data file, WAL, socket) ค่า default ของ OS มักอยู่ที่แค่ 1024 น้อยเกินไปมากสำหรับ database server ที่งานเยอะ

# /etc/security/limits.conf
postgres  soft  nofile  65536
postgres  hard  nofile  65536

# For systemd services (/etc/systemd/system/postgresql-17.service.d/limits.conf):
[Service]
LimitNOFILE=65536
# Verify PostgreSQL's actual limit
cat /proc/$(pgrep -f "postgres -D")/limits | grep "open files"

I/O Scheduler

NVMe SSD ให้ใช้ none (ไม่ใช้ scheduler เลย ให้ device จัดการ queue เอง):

# Check current scheduler
cat /sys/block/nvme0n1/queue/scheduler
# [mq-deadline] none kyber bfq

# Set none for NVMe
echo none > /sys/block/nvme0n1/queue/scheduler

# Persist via udev rule (/etc/udev/rules.d/60-postgresql-io.rules):
ACTION=="add|change", KERNEL=="nvme*", ATTR{queue/scheduler}="none"
ACTION=="add|change", KERNEL=="sd*", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="mq-deadline"

Part 9: Configuration Template พร้อมใช้

Template A: 16 GB RAM, 8 vCPU, NVMe SSD — OLTP Web Application

# Memory
shared_buffers          = 4GB
effective_cache_size    = 12GB
work_mem                = 32MB
maintenance_work_mem    = 1GB
autovacuum_work_mem     = 512MB
temp_buffers            = 16MB
huge_pages              = try

# Connections
max_connections         = 100    # + PgBouncer for application connections
superuser_reserved_connections = 3

# WAL and Checkpoints
wal_buffers             = 64MB
wal_compression         = lz4
wal_level               = replica
max_wal_size            = 4GB
min_wal_size            = 1GB
checkpoint_timeout      = 15min
checkpoint_completion_target = 0.9
synchronous_commit      = on

# Storage
random_page_cost        = 1.1
seq_page_cost           = 1.0
effective_io_concurrency = 200

# Parallel Query
max_worker_processes    = 8
max_parallel_workers    = 8
max_parallel_workers_per_gather = 2
max_parallel_maintenance_workers = 4

# Autovacuum
autovacuum                        = on
autovacuum_max_workers            = 5
autovacuum_vacuum_scale_factor    = 0.05
autovacuum_analyze_scale_factor   = 0.02
autovacuum_vacuum_cost_delay      = 2ms
autovacuum_vacuum_cost_limit      = 400

# Logging
log_min_duration_statement = 1000
log_checkpoints            = on
log_lock_waits             = on
log_temp_files             = 0
log_line_prefix            = '%m [%p] %q%u@%d '
log_statement              = 'ddl'
deadlock_timeout           = 1s

# Extensions (requires restart)
shared_preload_libraries = 'pg_stat_statements,auto_explain'
pg_stat_statements.max   = 10000
pg_stat_statements.track = all
auto_explain.log_min_duration = 2000
auto_explain.log_analyze      = true
auto_explain.log_buffers      = true

Template B: 64 GB RAM, 32 vCPU, NVMe SSD — Analytics / Mixed Workload

# Memory
shared_buffers          = 16GB
effective_cache_size    = 48GB
work_mem                = 128MB     # Higher for analytics joins/sorts
maintenance_work_mem    = 4GB
autovacuum_work_mem     = 1GB
huge_pages              = on

# Connections
max_connections         = 200
superuser_reserved_connections = 5

# WAL and Checkpoints
wal_buffers             = 64MB
wal_compression         = zstd
wal_level               = replica
max_wal_size            = 16GB
min_wal_size            = 4GB
checkpoint_timeout      = 30min
checkpoint_completion_target = 0.9

# Storage
random_page_cost        = 1.1
effective_io_concurrency = 200

# Parallel Query (analytics benefits from more parallelism)
max_worker_processes    = 32
max_parallel_workers    = 32
max_parallel_workers_per_gather = 8
max_parallel_maintenance_workers = 8

# Autovacuum
autovacuum_max_workers            = 8
autovacuum_vacuum_scale_factor    = 0.05
autovacuum_analyze_scale_factor   = 0.02
autovacuum_vacuum_cost_delay      = 2ms
autovacuum_vacuum_cost_limit      = 800

Part 10: รวม Query สำหรับ Monitoring

เก็บ query ชุดนี้ไว้ในกล่องเครื่องมือ DBA รันทุกสัปดาห์ หรือผูกกับ alerting ให้รันเองก็ได้

Buffer Cache Hit Rate

-- Target: > 99% for OLTP; < 95% signals shared_buffers is too small
SELECT
    schemaname,
    relname,
    heap_blks_hit,
    heap_blks_read,
    round(heap_blks_hit * 100.0 / nullif(heap_blks_hit + heap_blks_read, 0), 2) AS hit_rate
FROM pg_statio_user_tables
ORDER BY heap_blks_read DESC
LIMIT 15;

Table ที่กินพื้นที่ Buffer Cache มากที่สุด

CREATE EXTENSION IF NOT EXISTS pg_buffercache;

SELECT
    c.relname,
    pg_size_pretty(count(*) * 8192) AS buffered,
    round(count(*) * 100.0 /
        (SELECT setting::int FROM pg_settings WHERE name = 'shared_buffers'), 1) AS pct_of_shared_buffers,
    round(count(*) * 8192 * 100.0 / pg_relation_size(c.oid), 1) AS pct_of_table_cached
FROM pg_class c
JOIN pg_buffercache b ON b.relfilenode = c.relfilenode
JOIN pg_database d ON b.reldatabase = d.oid AND d.datname = current_database()
GROUP BY c.oid, c.relname
ORDER BY count(*) DESC
LIMIT 10;

Connection ที่ Active แยกตาม State

SELECT
    state,
    wait_event_type,
    wait_event,
    count(*) AS connections
FROM pg_stat_activity
WHERE pid <> pg_backend_pid()
GROUP BY state, wait_event_type, wait_event
ORDER BY connections DESC;

Query ที่ Block กันอยู่

SELECT
    blocked.pid            AS blocked_pid,
    blocked.usename        AS blocked_user,
    left(blocked.query, 80) AS blocked_query,
    blocking.pid           AS blocking_pid,
    blocking.usename       AS blocking_user,
    left(blocking.query, 80) AS blocking_query,
    now() - blocked.query_start AS wait_duration
FROM pg_stat_activity AS blocked
JOIN pg_stat_activity AS blocking
    ON blocking.pid = ANY(pg_blocking_pids(blocked.pid))
ORDER BY wait_duration DESC;

อายุของ Transaction ID (ความปลอดภัยเรื่อง Wraparound)

SELECT
    datname,
    age(datfrozenxid)                          AS xid_age,
    2147483647 - age(datfrozenxid)             AS xids_remaining,
    round((age(datfrozenxid)::numeric / 2147483647) * 100, 1) AS pct_used
FROM pg_database
ORDER BY age(datfrozenxid) DESC;
-- Alert if pct_used > 50%

Query ที่รันนาน

SELECT
    pid,
    now() - query_start AS duration,
    state,
    wait_event_type,
    wait_event,
    left(query, 120) AS query
FROM pg_stat_activity
WHERE state != 'idle'
  AND query_start < now() - interval '30 seconds'
ORDER BY duration DESC;

Query ที่ใช้เวลารวมมากที่สุด (pg_stat_statements)

SELECT
    round(total_exec_time::numeric, 0)          AS total_ms,
    calls,
    round(mean_exec_time::numeric, 2)           AS mean_ms,
    round(stddev_exec_time::numeric, 2)         AS stddev_ms,
    round(rows::numeric / nullif(calls, 0), 1) AS avg_rows,
    left(query, 120)                            AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 15;

Table Bloat (Live vs Dead Row)

SELECT
    schemaname,
    relname AS table,
    n_live_tup,
    n_dead_tup,
    round(n_dead_tup * 100.0 / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
    last_autovacuum,
    last_autoanalyze,
    autovacuum_count
FROM pg_stat_user_tables
WHERE n_dead_tup > 10000
ORDER BY n_dead_tup DESC
LIMIT 20;

สรุป

PostgreSQL server tuning ลงแรงครั้งเดียว แต่ได้ผลทบต้นทุกวัน Server ที่ตั้งค่าดี ๆ รับ throughput ได้ 5–10× ของ server ที่ติดตั้งแบบ default โดยไม่ต้องแก้ query เลยสักตัว

Configuration แต่ละชั้น

ชั้น Parameter ผลกระทบ
Memory shared_buffers, work_mem, effective_cache_size สูงที่สุด — การเลือก plan, disk I/O
WAL / Checkpoint max_wal_size, checkpoint_timeout, wal_compression สูง — write throughput, I/O spike
Storage random_page_cost, effective_io_concurrency สูง — การเลือก plan บน SSD vs disk
Autovacuum scale_factor, cost_delay, cost_limit สูง — table bloat, ความแม่นยำของ statistics
Parallelism max_parallel_workers_per_gather, max_worker_processes ปานกลาง — analytics query
Connections max_connections + PgBouncer ปานกลาง — memory ไม่ล้น, ระบบเสถียร
OS vm.swappiness, THP, file descriptor, I/O scheduler ปานกลาง — เป็นฐานของทุกอย่างข้างบน
Logging log_min_duration_statement, auto_explain, log_checkpoints ปานกลาง — observability

10 กฎที่ได้ผลทบต้น

  1. shared_buffers = 25% ของ RAM อย่าทิ้งไว้ที่ 128MB ค่า default นี้ตั้งมาตั้งแต่ hardware ยุค PostgreSQL 8.0
  2. effective_cache_size = 75% ของ RAM ค่านี้ไม่ได้จอง memory ตั้งสูงก็ไม่เสียอะไร แต่ถ้า planner เลือก plan ผิด throughput หายแน่
  3. work_mem คิดต่อ operation ไม่ใช่ต่อ connection คำนวณกรณีแย่สุดก่อนตั้ง: work_mem × ops × connections
  4. เปิด huge pages เมื่อ shared_buffers ≥ 8 GB TLB pressure ลดลงแบบวัดผลได้
  5. max_wal_size = 4× ของข้อมูลที่เขียนในหนึ่งรอบ checkpoint_timeout ดูขนาดที่เหมาะจาก checkpoint log อย่าเดา
  6. wal_compression = lz4 คือ throughput ที่แทบได้ฟรีบน server ที่ติดคอขวด I/O บีบอัด WAL โดยใช้ CPU น้อยจนแทบไม่รู้สึก
  7. random_page_cost = 1.1 บน SSD ถ้าทิ้งไว้ที่ 4.0 (default ของจานหมุน) planner จะไม่ค่อยเชื่อ index ของคุณ
  8. Autovacuum scale_factor = 0.05 ค่า default 0.20 ทำให้ table 100M row สะสม dead tuple ได้ถึง 20M แบบนี้คือ table เน่า ไม่ใช่ feature
  9. เปิด log_min_duration_statement = 1000 ไว้ตลอด Slow query log คือสัญญาณเตือนแรกสุดว่ามี index regression
  10. Monitor อายุ transaction ID ทุกสัปดาห์ Wraparound emergency mode เป็น failure mode ไม่กี่อย่างของ PostgreSQL ที่ต้องหยุดระบบจริง ๆ รู้ค่า xids_remaining ไว้ก่อนจะกลายเป็นวิกฤต

Database ที่ตั้งค่าดีตั้งแต่แรก จะไม่ปลุกคุณตอนตีสาม


ทดสอบบน PostgreSQL 17.x และ Rocky Linux 9.x ค่า configuration parameter และค่า default ทั้งหมดเทียบกับ PostgreSQL 17 official documentation แล้ว

มีคำถามหรืออยากคุยต่อ ทักมาได้ทาง LinkedIn, X หรือ email

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.