PostgreSQL Performance Tuning สำหรับ Application Developer (ฉบับปี 2026)¶
Query ช้าไม่ได้เป็นปัญหาของ database แต่เป็นปัญหาของ design
Query ที่ใช้ 4 วินาทีบน table 100 ล้าน row แทบทุกครั้งมีต้นเหตุที่แก้ได้ อาจจะขาด index, เลือก index ผิดประเภท, table bloat, connection pool เต็ม หรือ config ยังเป็นค่า default ที่ตั้งไว้สำหรับ dataset 1GB แล้วไม่มีใครไปแก้อีกเลย ปัญหา performance ส่วนใหญ่เจอและแก้จบได้ที่ระดับ query กับ schema ยังไม่ต้องไปแตะ hardware เลยด้วยซ้ำ
กติกาพื้นฐาน¶
ก่อนจะ tune อะไร ตอบให้ได้ก่อนว่ากำลัง optimize เพื่ออะไร เป้าหมายหลักมีสองข้อ และสองข้อนี้มักดึงกันไปคนละทาง
- Read throughput: index ช่วย ยิ่งมี index เยอะ read ยิ่งเร็ว แต่ write ก็ยิ่งช้า
- Write throughput: index ถ่วง เพราะทุก INSERT/UPDATE/DELETE ต้องอัปเดตทุก index ตามไปด้วย
OLTP application (web app, API, microservice) มี read 80–95% ของ traffic ทั้งหมด ใส่ index ได้เต็มที่ แล้วแยก monitor write latency ไว้อีกตัว ส่วน data pipeline กับ batch job ลอง drop index ทิ้งก่อน bulk-load แล้วค่อย rebuild ทีหลัง
Part 1: Profile ก่อน แล้วค่อย Tune¶
พลาดกันบ่อยที่สุดตอน tune คือการเดา วัดก่อนทุกครั้ง แล้วค่อยเปลี่ยน
เปิดใช้ pg_stat_statements¶
Extension ตัวนี้เก็บข้อมูลทุก query ที่รัน ว่ารันกี่ครั้ง ใช้เวลาเท่าไร ถ้าจะหา query ช้า ไม่มี tool ไหนช่วยได้มากกว่าตัวนี้
-- Add to postgresql.conf, then restart
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.max = 10000
pg_stat_statements.track = all
หา 10 query ที่กินเวลารวมมากที่สุด:
SELECT
round(total_exec_time::numeric, 2) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
calls,
round(rows::numeric / calls, 1) AS avg_rows,
left(query, 120) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
หา query ที่โดนเรียกบ่อยแต่ latency กลางๆ (ของจริงมักเป็นกลุ่มนี้ที่ส่งผลหนักสุด):
SELECT
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(stddev_exec_time::numeric, 2) AS stddev_ms,
left(query, 120) AS query
FROM pg_stat_statements
WHERE calls > 1000
ORDER BY mean_exec_time DESC
LIMIT 20;
Tune เสร็จแล้ว reset stats ทิ้ง ตัวเลขรอบใหม่จะได้วัดผลได้ไม่ปนของเก่า:
หา Index ที่ไม่มีใครใช้¶
Index ทุกตัวมีต้นทุน ทั้ง write และ storage ตัวที่ไม่มีใครใช้ก็เป็น overhead เปล่าๆ:
SELECT
schemaname,
tablename,
indexname,
pg_size_pretty(pg_relation_size(indexrelid)) AS index_size,
idx_scan AS scans
FROM pg_stat_user_indexes
JOIN pg_index USING (indexrelid)
WHERE idx_scan = 0
AND indisunique IS FALSE
ORDER BY pg_relation_size(indexrelid) DESC;
Index ที่ scan เป็นศูนย์ตั้งแต่ reset stats ครั้งล่าสุด คือตัวที่น่าลบทิ้ง แต่อย่าเพิ่งรีบ drop ดูต่ออีกสักพัก อย่างน้อยหนึ่งสัปดาห์ ให้แน่ใจก่อน
หา Index ที่ยังขาด (Sequential Scan บน Table ใหญ่)¶
SELECT
schemaname,
relname AS table,
seq_scan,
seq_tup_read,
idx_scan,
n_live_tup AS live_rows,
pg_size_pretty(pg_total_relation_size(relid)) AS total_size
FROM pg_stat_user_tables
WHERE seq_scan > 0
AND n_live_tup > 100000
ORDER BY seq_tup_read DESC
LIMIT 20;
Table ใหญ่ที่ seq_tup_read สูง แปลว่าโดน full table scan อยู่ซ้ำๆ ให้เพิ่ม index บน column ที่ใช้ใน WHERE clause ของ table นั้น
Part 2: อ่าน EXPLAIN ให้ขาดแบบ Senior Engineer¶
EXPLAIN บอกแค่ query plan ส่วน EXPLAIN (ANALYZE, BUFFERS) บอกว่ารันจริงแล้วเกิดอะไรขึ้น รวมถึงใช้ cache ไปแค่ไหน
วิธีเรียก EXPLAIN แบบที่ควรใช้ตอนนี้¶
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT * FROM transactions
WHERE acc_from = 'ACC-001'
AND created_at > now() - interval '30 days';
Output แต่ละบรรทัดบอกอะไร:
Bitmap Heap Scan on transactions (cost=297.23..8421.44 rows=10037 width=89)
^cost estimate ^rows estimate
Recheck Cond: (acc_from = 'ACC-001')
-> Bitmap Index Scan on idx_txn_acc_from (cost=0.00..294.72 rows=10037)
Index Cond: (acc_from = 'ACC-001')
Buffers: shared hit=4821 read=4153
^cache hits ^disk reads
Planning Time: 1.2 ms
Execution Time: 297.5 ms
จุดที่ต้องดู:
| สิ่งที่เห็น | แปลว่า |
|---|---|
Seq Scan บน table ใหญ่ | ขาด index ต้องเพิ่ม |
rows=10000 vs actual rows=1 | statistics เก่าแล้ว รัน ANALYZE |
Buffers: read=10000 | อ่าน disk หนัก เช็ก shared_buffers หรือ selectivity ของ index |
Hash Join บน table เล็ก | ปกติไม่มีปัญหา ถ้า lookup ผ่าน index ได้ Nested Loop จะดีกว่า |
Sort แบบไม่มี index | เพิ่ม index มารองรับ ORDER BY หรือ merge join |
cost=0..9999999 สูงผิดปกติ | มี sequential scan ก้อนใหญ่ซ่อนอยู่ลึกๆ ใน plan |
บังคับ Plan ไว้ทดสอบ¶
-- Test without index to measure impact
SET enable_indexscan = off;
EXPLAIN ANALYZE SELECT ...;
SET enable_indexscan = on;
Part 3: วางกลยุทธ์ Index¶
เริ่มจาก B-Tree Index¶
B-tree เป็นตัว default ใช้ได้กับ =, <, >, BETWEEN, LIKE 'prefix%' และ ORDER BY
-- Single column
CREATE INDEX CONCURRENTLY idx_txn_acc_from
ON transactions (acc_from);
-- With timing: sequential scan vs index scan
-- Before: 3,757 ms (seq scan, 100M rows)
-- After: 297 ms (index scan) — 12× faster
บน production ใส่ CONCURRENTLY ทุกครั้ง จะได้สร้าง index ไปโดยไม่ lock write
Compound Index: ลำดับ Column มีผล¶
Compound index (a, b) ใช้ได้กับ: - WHERE a = ? AND b = ? ใช้ทั้งสอง column - WHERE a = ? ใช้แค่ column แรก - ORDER BY a, b sort ได้เลย ไม่ต้องมี sort step แยก
แต่ถ้ามีแค่ WHERE b = ? อย่างเดียว index ตัวนี้ ช่วยไม่ได้ เพราะ query ต้องมี column แรกด้วย
-- For: WHERE acc_from = ? AND acc_to = ?
CREATE INDEX CONCURRENTLY idx_txn_from_to
ON transactions (acc_from, acc_to);
-- Timing comparison for acc_from + acc_to filter:
-- Separate indexes: 34.6 ms
-- Compound index: 1.2 ms — 28× faster
กฎ: ถ้าทั้งสอง column อยู่ใน WHERE ให้เอา column ที่ selectivity สูงสุด (ค่าซ้ำน้อยสุด) ขึ้นก่อน และ column แบบ equality ต้องมาก่อน column แบบ range เสมอ
Covering Index: เพิ่ม Column ด้วย INCLUDE¶
Covering index มีครบทุก column ที่ query ต้องใช้ PostgreSQL เลยไม่ต้องกลับไปอ่าน heap table อีก ผลคือได้ Index Only Scan ซึ่งเป็นทางที่ read ได้เร็วที่สุดแล้ว
-- Query: SELECT acc_from, acc_to, value FROM transactions WHERE acc_from = ?
CREATE INDEX CONCURRENTLY idx_txn_covering
ON transactions (acc_from)
INCLUDE (acc_to, value);
Column ใน INCLUDE อยู่แค่ที่ leaf ของ index ไม่ได้เข้าไปอยู่ในโครงสร้าง B-tree เลยไม่มีผลกับลำดับการ sort และไม่ทำให้ index ลึกขึ้น
ใช้ตอนไหน: query read ที่โดนเรียกบ่อย และ select column ชุดเล็กๆ ชุดเดิมทุกครั้ง
Partial Index: Index แค่ส่วนที่ Query จริง¶
ถ้า 95% ของ query filter ด้วย status = 'active' ก็ไม่มีเหตุผลต้อง index row อีก 95% ที่เป็น 'archived'
-- Index only active records
CREATE INDEX CONCURRENTLY idx_orders_active
ON orders (created_at)
WHERE status = 'active';
-- This query will use it:
SELECT * FROM orders WHERE status = 'active' AND created_at > now() - interval '7 days';
-- This query will NOT (different status value):
SELECT * FROM orders WHERE status = 'archived' AND created_at > ...;
Partial index เล็กกว่า สร้างเสร็จเร็วกว่า แล้วก็ scan เร็วกว่าด้วย
Expression Index¶
Index ผลลัพธ์ของ function แทนค่าดิบใน column:
-- Query uses lower() for case-insensitive match
SELECT * FROM users WHERE lower(email) = lower('User@Example.com');
-- Create expression index
CREATE INDEX CONCURRENTLY idx_users_email_lower
ON users (lower(email));
-- Index on JSONB field extraction
CREATE INDEX CONCURRENTLY idx_events_user_id
ON events ((payload->>'user_id'));
Expression ใน query ต้องตรงกับใน index เป๊ะ ไม่อย่างนั้น PostgreSQL จะไม่ใช้ index ตัวนี้
GIN Index: Full-Text Search และ JSONB¶
B-tree เช็กไม่ได้ว่าค่าไหนอยู่ใน array หรือ JSONB มี key นี้ไหม งานแบบนี้ต้องใช้ GIN (Generalized Inverted Index)
-- Full-text search
ALTER TABLE articles ADD COLUMN search_vector tsvector
GENERATED ALWAYS AS (to_tsvector('english', title || ' ' || body)) STORED;
CREATE INDEX CONCURRENTLY idx_articles_search
ON articles USING GIN (search_vector);
-- Query
SELECT title FROM articles
WHERE search_vector @@ plainto_tsquery('english', 'cloud native kubernetes');
-- JSONB containment
CREATE INDEX CONCURRENTLY idx_events_payload
ON events USING GIN (payload jsonb_path_ops);
-- Query: find events where payload contains {"type": "login"}
SELECT * FROM events WHERE payload @> '{"type": "login"}';
BRIN Index: Table ใหญ่มากที่ Data เรียงกันอยู่แล้ว¶
BRIN (Block Range Index) เก็บแค่ค่า min/max ของแต่ละ block range ไม่ได้เก็บ pointer ทีละ row ขนาดเลยเล็กมาก (มักเล็กกว่า B-tree ราว 100 เท่า) แต่ใช้ได้เฉพาะตอนที่ data เรียงกันอยู่บน disk จริงๆ เช่น column created_at ของ table ที่มีแต่ insert
-- Effective for time-series / append-only tables
CREATE INDEX CONCURRENTLY idx_events_created_brin
ON events USING BRIN (created_at) WITH (pages_per_range = 128);
-- A 100M row table's BRIN index: ~500 KB vs ~3 GB for B-tree
ใช้ BRIN เมื่อ: column มี cardinality สูง data เข้ามาเรียงตามลำดับคร่าวๆ (เช่น timestamp) และ query ใช้ range filter ถ้าต้อง lookup ค่าอะไรก็ได้แบบสุ่ม BRIN ช่วยไม่ได้
Part 4: Configuration ฝั่ง Server¶
ค่า default ตั้งมาให้รันได้ทุกที่ ไม่ได้ตั้งมาให้เร็ว parameter สามตัวนี้ส่งผลมากที่สุด
shared_buffers¶
นี่คือ page cache ใน memory ของ PostgreSQL ค่า default คือ 128MB น้อยเกินไปมากสำหรับ production workload ไม่ว่าแบบไหน
นอกจาก cache ตัวนี้ PostgreSQL ยังพึ่ง page cache ของ OS อีกชั้น ตั้ง shared_buffers เกิน 8GB เลยไม่ค่อยได้อะไรเพิ่ม เพราะ cache ของ OS รับส่วนที่เหลือไปอยู่แล้ว
effective_cache_size¶
ค่านี้บอก query planner ว่ามี cache รวมทั้งหมด (PostgreSQL + OS) เท่าไร ค่านี้ ไม่ได้ จอง memory จริง เป็นแค่ hint ให้ planner ใช้ตัดสินใจเลือก plan ตั้งสูงๆ ไว้ได้เลย
ถ้า effective_cache_size สูง planner จะเลือก index scan มากกว่า sequential scan เพราะคิดว่า data ส่วนใหญ่อยู่ใน cache แล้ว
work_mem¶
Memory ที่ให้ sort หรือ hash ใช้ต่อหนึ่ง operation ค่า default คือ 4MB ถ้า sort ไม่พอใน work_mem ก็จะล้นไปเขียนลง disk (Sort Method: external merge Disk)
ระวัง: work_mem คิดต่อ operation และ query ซับซ้อนตัวเดียวอาจมี sort กับ hash หลายตัวรันพร้อมกัน ลองคิดดู 200 connection แต่ละตัวมี 5 operation ตัวละ 64MB ช่วง peak จะกิน memory ถึง 64GB งาน OLTP เลยควรตั้งไว้ต่ำๆ แล้วค่อยเพิ่มเฉพาะ session ที่ทำ analytics:
Config ครบชุดสำหรับ OLTP Server 16GB¶
# postgresql.conf
shared_buffers = 4GB
effective_cache_size = 12GB
work_mem = 32MB
maintenance_work_mem = 1GB # For VACUUM, CREATE INDEX
max_connections = 100 # Use PgBouncer for more
wal_buffers = 64MB
checkpoint_completion_target = 0.9
random_page_cost = 1.1 # SSD: 1.1; spinning disk: 4.0
effective_io_concurrency = 200 # SSD: 200; spinning disk: 2
max_worker_processes = 8
max_parallel_workers = 4
max_parallel_workers_per_gather = 2
แก้ postgresql.conf เสร็จแล้วทำต่อแบบนี้:
# Parameters marked as requiring restart
sudo systemctl restart postgresql-17
# Parameters that apply on reload
sudo systemctl reload postgresql-17
# Check which changed without restart
SELECT name, pending_restart FROM pg_settings WHERE pending_restart = true;
Part 5: Connection Pooling ด้วย PgBouncer¶
PostgreSQL สร้าง OS process ใหม่ (ไม่ใช่ thread) ทุกครั้งที่มี connection เข้ามา 500 connection ก็คือ 500 process แย่ง memory กับ CPU กันอยู่ ทั้งที่ส่วนใหญ่ idle อยู่เฉยๆ แค่ overhead ของ connection อย่างเดียวก็กิน RAM ไปหลาย GB แล้ว แถม latency ยังเพิ่มอีก
PgBouncer คั่นกลางระหว่าง application กับ PostgreSQL ถือ database connection จริงไว้เป็น pool เล็กๆ แล้วเอา connection จาก application เป็นพันๆ ตัวมา multiplex ใช้ pool นี้ร่วมกัน
ติดตั้ง PgBouncer¶
Configure /etc/pgbouncer/pgbouncer.ini¶
[databases]
myapp = host=127.0.0.1 port=5432 dbname=myapp
[pgbouncer]
listen_port = 6432
listen_addr = 127.0.0.1
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
; Transaction pooling: connection returned to pool after each transaction
; Best for OLTP — works with most ORMs
pool_mode = transaction
server_pool_size = 25 ; Real DB connections per database/user pair
max_client_conn = 1000 ; Max application connections PgBouncer accepts
default_pool_size = 25
reserve_pool_size = 5
reserve_pool_timeout = 3
; Keep connections alive
server_idle_timeout = 600
client_idle_timeout = 0
log_connections = 0
log_disconnections = 0
สร้าง Auth File¶
# Generate scram-sha-256 hash from PostgreSQL
psql -c "SELECT concat('\"', usename, '\" \"', passwd, '\"') FROM pg_shadow WHERE usename = 'myappuser';" -t
Application ต่อเข้า port 6432 แทน 5432 แค่นี้ก็ตั้ง max_connections ของ PostgreSQL ไว้ที่ 100 แทน 1000 ได้แล้ว เพราะ PgBouncer รับ concurrency ฝั่ง application ไปแทน
เลือก Pool Mode ไหนดี¶
| Mode | คืน connection เข้า pool ตอนไหน | ใช้กับอะไรได้บ้าง |
|---|---|---|
session | ตอน client disconnect | ได้ทุกอย่าง รวมถึง SET, LISTEN, temp table |
transaction | หลัง commit แต่ละ transaction | ORM ส่วนใหญ่ แต่ไม่มี state ระดับ session |
statement | หลังจบแต่ละ statement | แทบไม่มีใครใช้ เพราะใช้กับ transaction หลาย statement ไม่ได้ |
OLTP application ส่วนใหญ่ใช้ mode transaction ก็พอ แต่ถ้า application ใช้ advisory lock, SET LOCAL หรือ prepared statement ที่ต้องอยู่ข้าม transaction ให้ใช้ mode session
Part 6: Table Partitioning¶
ถ้า table โตเกิน ~50–100M row และ query filter ด้วย dimension เดิมเสมอ (เวลา, tenant, region) ลองทำ partitioning ดู PostgreSQL จะข้าม partition ที่ไม่เกี่ยวไปได้ทั้งก้อนโดยไม่ต้อง scan
Range Partitioning ตามวันที่¶
-- Create partitioned parent table
CREATE TABLE transactions (
id bigserial,
acc_from varchar(20) NOT NULL,
acc_to varchar(20) NOT NULL,
value numeric(18,2) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
) PARTITION BY RANGE (created_at);
-- Create monthly partitions
CREATE TABLE transactions_2026_01 PARTITION OF transactions
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
CREATE TABLE transactions_2026_02 PARTITION OF transactions
FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');
-- Indexes are created per partition
CREATE INDEX ON transactions_2026_01 (acc_from);
CREATE INDEX ON transactions_2026_02 (acc_from);
ถ้า WHERE clause มี partition key อยู่ด้วย PostgreSQL จะทำ partition pruning ให้เองอัตโนมัติ:
-- PostgreSQL scans only transactions_2026_01 — all other partitions skipped
EXPLAIN SELECT * FROM transactions
WHERE created_at BETWEEN '2026-01-01' AND '2026-01-31'
AND acc_from = 'ACC-001';
-- → Index Scan on transactions_2026_01 (not a full table scan)
ให้ระบบสร้าง Partition เอง¶
ใช้ pg_partman สร้างและ drop partition ตาม schedule:
CREATE EXTENSION pg_partman SCHEMA partman;
SELECT partman.create_parent(
p_parent_table := 'public.transactions',
p_control := 'created_at',
p_interval := 'monthly',
p_premake := 3 -- Create 3 future partitions ahead
);
-- Run via cron or pg_agent to maintain partitions
SELECT partman.run_maintenance(p_analyze := false);
กรณีที่ไม่ควร Partition¶
- Table < 10M row: ได้ overhead เพิ่มมาเปล่าๆ ไม่ได้อะไรคืน
- ไม่มี partition key ที่ชัด: hash partitioning แทบไม่ทำให้ query เร็วขึ้น
- Access pattern แบบสุ่ม: partition pruning ช่วยได้แค่ query แบบ range/list
Part 7: Tune Autovacuum¶
PostgreSQL ใช้ MVCC (Multi-Version Concurrency Control) เวลา update จะไม่เขียนทับ row เดิม แต่สร้าง version ใหม่ แล้ว mark version เก่าว่า "dead" Autovacuum มีหน้าที่ตามเก็บพื้นที่ของ dead tuple พวกนี้คืน ถ้าเก็บไม่ทัน table จะ bloat query ช้าลง และถ้าหนักจริงๆ ก็จะเจอภาวะฉุกเฉิน transaction ID wraparound
เช็ก Bloat ตอนนี้¶
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
FROM pg_stat_user_tables
WHERE n_dead_tup > 10000
ORDER BY n_dead_tup DESC
LIMIT 20;
Table ที่โดน query บ่อยแล้ว dead_pct เกิน 20% ถือว่ามีปัญหาแล้ว dead tuple เยอะแปลว่า query ต้องไล่ scan row ที่สุดท้ายก็ต้องทิ้งอยู่ดี
Tune Autovacuum ทั้งระบบ¶
ค่า default ของ autovacuum จะเริ่มทำงานเมื่อ dead tuple เกิน 50 + 0.2 × live_rows (20% ของ table) ถ้า table มี 100M row ก็ต้องรอให้ dead tuple สะสมถึง 20 ล้านตัวก่อน vacuum ถึงจะรัน เยอะเกินไปมาก
# postgresql.conf
# Worker resources
autovacuum_max_workers = 5 # Default: 3
autovacuum_vacuum_cost_delay = 2ms # Default: 2ms (SSD); set 20ms for spinning disk
autovacuum_vacuum_cost_limit = 400 # Default: 200; raise for SSD
# Trigger thresholds (lower = vacuum runs sooner)
autovacuum_vacuum_scale_factor = 0.05 # Default: 0.20 (5% dead triggers vacuum)
autovacuum_analyze_scale_factor = 0.02 # Default: 0.10
autovacuum_vacuum_threshold = 500 # Default: 50
ตั้ง Autovacuum แยกราย Table¶
Table ที่ write หนักต้องตั้งให้ vacuum ถี่กว่า table ที่แทบไม่มีใครแตะ:
-- High-write OLTP table: vacuum aggressively
ALTER TABLE transactions SET (
autovacuum_vacuum_scale_factor = 0.01,
autovacuum_vacuum_threshold = 100,
autovacuum_analyze_scale_factor = 0.005,
autovacuum_vacuum_cost_delay = 1
);
-- Large archive table: vacuum rarely (minimal writes)
ALTER TABLE transactions_archive SET (
autovacuum_vacuum_scale_factor = 0.10,
autovacuum_vacuum_threshold = 10000
);
สั่ง Vacuum เองตอนฉุกเฉิน¶
ใช้ตอนที่ bloat หนักไปแล้ว และ autovacuum ตามไม่ทัน:
# Run VACUUM ANALYZE without blocking reads/writes (but blocks other VACUUMs)
psql -d myapp -c "VACUUM (ANALYZE, VERBOSE) transactions;"
# For extreme bloat: reclaims space to OS (requires brief exclusive lock at end)
psql -d myapp -c "VACUUM (FULL, ANALYZE) transactions_archive;"
VACUUM FULL เขียน table ใหม่ทั้งก้อน ใช้ได้เฉพาะช่วง maintenance window เท่านั้น ถ้าอยากคืนพื้นที่แบบไม่มี downtime ให้ใช้ extension pg_squeeze หรือ pg_repack แทน
Part 8: ออกแบบ Data Model ให้เร็วตั้งแต่ต้น¶
Schema ที่ตัดสินใจไปตั้งแต่แรก แก้ทีหลังยากกว่า index หรือ config ตัวไหนๆ กฎไม่กี่ข้อด้านล่างนี้ทำไว้ตั้งแต่ต้น ผลจะทบไปเรื่อยๆ:
เลือก Data Type ให้ถูก¶
-- Bad: storing integers as text
account_id varchar(20) -- requires text comparison, larger storage
-- Better
account_id bigint -- fixed 8 bytes, integer comparison
-- Bad: status as freeform text
status varchar(20) -- unbounded, no constraint
-- Better
status text CHECK (status IN ('active', 'inactive', 'suspended'))
-- Or use a native ENUM (faster comparison, less storage):
CREATE TYPE account_status AS ENUM ('active', 'inactive', 'suspended');
เลือก BIGSERIAL หรือ UUID อย่างมีเหตุผล¶
-- For internal IDs (contiguous, fast joins)
id bigserial PRIMARY KEY
-- For external/distributed IDs (random order — use UUIDv7 for monotonic inserts)
id uuid DEFAULT gen_random_uuid() PRIMARY KEY
Insert UUIDv4 ลง B-tree primary key ทำให้เกิด page split ส่วน UUIDv7 เรียงตามเวลาอยู่แล้วเลยไม่เจอปัญหานี้ PostgreSQL 17 มี gen_ulid() ให้ใช้เป็นอีกทางเลือกที่เรียงตามเวลาเหมือนกัน
แยก Data ร้อนออกจาก Data เย็น¶
Table ที่มีทั้ง column ที่ update บ่อยและ column ที่แทบไม่มีใครแตะปนกันอยู่ จะทำให้ vacuum ช้าและ heap บวม แยกเป็นสอง table แบบ vertical partitioning จะได้ให้ table ที่ data ร้อนเล็กอยู่เสมอ:
-- Hot table: core financial data, updated often
CREATE TABLE transactions (
id bigserial PRIMARY KEY,
acc_from varchar(20) NOT NULL,
acc_to varchar(20) NOT NULL,
value numeric(18,2) NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL
);
-- Cold table: metadata appended once, never updated
CREATE TABLE transaction_details (
transaction_id bigint PRIMARY KEY REFERENCES transactions(id),
channel text,
ip_address inet,
user_agent text,
raw_payload jsonb
);
Part 9: Pattern การ Optimize ระดับ Query¶
อย่าครอบ Column ที่มี Index ด้วย Function ใน WHERE¶
-- Bad: function prevents index use
SELECT * FROM users WHERE date_trunc('day', created_at) = '2026-05-01';
-- Good: range query uses index
SELECT * FROM users
WHERE created_at >= '2026-05-01'
AND created_at < '2026-05-02';
ใช้ CTE ให้เป็น (PostgreSQL 12+)¶
ก่อน PostgreSQL 12 CTE เป็น optimization fence planner มองเป็นกล่องดำ optimize ข้ามเข้าไปไม่ได้ ตั้งแต่ 12 เป็นต้นมา planner inline CTE ได้แล้ว ถ้ายังอยากได้ fence แบบเดิม (ซึ่งน้อยครั้งมาก) ให้ใช้ WITH ... AS MATERIALIZED
-- PostgreSQL 12+: this CTE is inlined and the planner optimizes it end-to-end
WITH recent_txn AS (
SELECT * FROM transactions WHERE created_at > now() - interval '1 day'
)
SELECT acc_from, sum(value) FROM recent_txn GROUP BY acc_from;
-- Force materialization (old behavior) — rarely needed
WITH recent_txn AS MATERIALIZED (
SELECT * FROM transactions WHERE created_at > now() - interval '1 day'
)
SELECT acc_from, sum(value) FROM recent_txn GROUP BY acc_from;
LIMIT + ORDER BY ต้องมี Index ที่ใช่¶
-- Query: get latest 20 transactions for account ACC-001
SELECT * FROM transactions
WHERE acc_from = 'ACC-001'
ORDER BY created_at DESC
LIMIT 20;
-- Correct index: equality first, then ORDER BY column
CREATE INDEX CONCURRENTLY idx_txn_acc_created
ON transactions (acc_from, created_at DESC);
ถ้าไม่มี index ตัวนี้ PostgreSQL ต้องดึงทุก row ที่ acc_from = 'ACC-001' ขึ้นมา sort ให้หมดก่อน แล้วค่อยหยิบ 20 ตัวแรก ใส่ LIMIT ไว้ก็ไม่ช่วย
Write ก้อนใหญ่ให้ทำเป็น Batch¶
-- Bad: 100,000 individual INSERTs (100,000 round trips)
for row in data:
execute("INSERT INTO events VALUES (?)", row)
-- Good: single multi-row INSERT
INSERT INTO events (user_id, event_type, created_at)
VALUES
(1, 'login', now()),
(2, 'purchase', now()),
...; -- Up to ~1000 rows per statement
ถ้า bulk load ก้อนใหญ่มากจริงๆ ใช้ COPY:
COPY ไม่ต้องเสีย overhead ทีละ row เลยเร็วกว่า INSERT 10–100 เท่าเวลาโหลด data จำนวนมาก
Part 10: Query Monitoring ที่ควรรันเป็นประจำ¶
เอา query ชุดนี้ใส่ไว้ใน operational review ทุกสัปดาห์:
Table และ Index ที่ใหญ่ที่สุด¶
SELECT
relname,
pg_size_pretty(pg_total_relation_size(oid)) AS total,
pg_size_pretty(pg_relation_size(oid)) AS table,
pg_size_pretty(pg_indexes_size(oid)) AS indexes
FROM pg_class
WHERE relkind = 'r'
ORDER BY pg_total_relation_size(oid) DESC
LIMIT 15;
Query ที่รันค้างนาน¶
SELECT
pid,
now() - query_start AS duration,
state,
wait_event_type,
wait_event,
left(query, 100) AS query
FROM pg_stat_activity
WHERE state != 'idle'
AND query_start < now() - interval '30 seconds'
ORDER BY duration DESC;
Query ที่รอ Lock¶
SELECT
blocked.pid AS blocked_pid,
blocked.query AS blocked_query,
blocking.pid AS blocking_pid,
blocking.query AS blocking_query
FROM pg_stat_activity AS blocked
JOIN pg_stat_activity AS blocking
ON blocking.pid = ANY(pg_blocking_pids(blocked.pid))
WHERE blocked.cardinality(pg_blocking_pids(blocked.pid)) > 0;
Index Hit Rate (เป้าคือ > 99%)¶
SELECT
relname AS table,
round(idx_blks_hit * 100.0 / nullif(idx_blks_hit + idx_blks_read, 0), 2) AS idx_hit_rate,
round(heap_blks_hit * 100.0 / nullif(heap_blks_hit + heap_blks_read, 0), 2) AS heap_hit_rate
FROM pg_statio_user_tables
ORDER BY idx_blks_read + heap_blks_read DESC
LIMIT 15;
Hit rate ของ index หรือ heap ต่ำกว่า 95% เมื่อไร ให้เพิ่ม shared_buffers หรือเพิ่ม RAM ให้ server
Summary¶
PostgreSQL performance tuning ปี 2026 ทำกันเป็นชั้นๆ เรียงจากชั้นที่ได้ผลมากที่สุดลงไปแบบนี้:
ลำดับชั้นของการ Tune¶
| ชั้น | Tool | ทำตอนไหน |
|---|---|---|
| Profile ก่อน | pg_stat_statements | ทุกครั้ง ก่อนเปลี่ยนอะไรก็ตาม |
| Index | B-tree, GIN, BRIN, partial, covering | ทุก query ที่ช้า |
| Connection pooling | PgBouncer (transaction mode) | concurrent connection > 100 |
| Configuration | shared_buffers, work_mem, effective_cache_size | หลัง profile เสร็จ |
| Autovacuum | Scale factor, ตั้งแยกราย table | เมื่อ % dead tuple สูง |
| Partitioning | Range ตามวันที่, list ตาม tenant | > 50M row และมี partition key ชัด |
| Schema design | Type ที่ใช่, แยก hot/cold | ตอนออกแบบ |
10 กฎที่ผลทบต้นไปเรื่อยๆ¶
- วัดด้วย
pg_stat_statementsก่อน อย่าเดาว่า query ไหนช้า - ใช้
EXPLAIN (ANALYZE, BUFFERS)ไม่ใช่แค่EXPLAINเพราะจำนวน row ที่ planner ประมาณกับของจริงคลาดกันตลอด - ลำดับ column ใน compound index มีผล: column แบบ equality ขึ้นก่อน column แบบ range ไว้ท้าย
- Column ใน
INCLUDEทำให้ B-tree index กลายเป็น covering index ซึ่งเป็นทาง read ที่เร็วที่สุด - Partial index บนเฉพาะ subset ที่ filter จริง เล็กกว่า เร็วกว่า และดูแลง่ายกว่า
- เกิน 200 connection ต้องมี PgBouncer แบบ transaction mode ไม่ใช่ทางเลือกแล้ว และตั้ง
max_connections = 100ที่ PostgreSQL shared_buffers= 25% ของ RAM เป็นแค่จุดเริ่ม ไม่ใช่เพดาน คอยดู cache hit rate ไว้- ค่า default ของ autovacuum ไม่เหมาะกับ table ใหญ่ ลด scale factor แล้วเพิ่ม cost limit
- Partitioning เป็นเรื่องของ schema ไม่ใช่วิธีแก้ query ช้า และช่วยได้เฉพาะตอน query filter ด้วย partition key
- ครอบ column ที่มี index ด้วย function ใน WHERE เมื่อไร index ก็ใช้ไม่ได้ เขียนใหม่เป็น range query หรือไปใช้ expression index
ทุกเทคนิคในโพสต์นี้ใช้จังหวะเดียวกันหมด วัดก่อน เปลี่ยนทีละอย่าง แล้ววัดซ้ำ ไม่ใช่ setting ตัวไหน แต่เป็นวินัยแบบนี้แหละที่ทำให้ database เร็วได้ตลอด ไม่ต้องมานั่ง tune ฉุกเฉินตอนตีสาม
อ้างอิงจาก PostgreSQL 17, PgBouncer 1.23 และ pg_partman 5.x บน Rocky Linux 9 เทคนิคทั้งหมดใช้ได้กับ PostgreSQL 14 ขึ้นไป
มีคำถามหรืออยากคุยต่อ? ติดต่อผมได้ทาง LinkedIn, X หรือส่ง email มาได้เลย
Discussion
Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.