Home  Postgress   Postgresql ...

PostgreSQL DBA Advanced Cheat Sheet


🧠 **PostgreSQL DBA Advanced Cheat Sheet **

1️⃣ Performance Tuning Parameters

Key settings from postgresql.conf that directly affect speed and memory efficiency.

ParameterDescriptionTypical Value
shared_buffersAmount of memory for caching data pages.25% of system RAM
work_memMemory used for sort/hash operations per query.64MB – 256MB
maintenance_work_memUsed for VACUUM, CREATE INDEX.256MB – 1GB
effective_cache_sizeHow much memory the planner assumes is available for caching.50–75% of RAM
max_connectionsControls total concurrent sessions.100–300
checkpoint_timeoutTime between automatic checkpoints.5–15 minutes
wal_buffersMemory for WAL writes before disk flush.16MB – 64MB
synchronous_commitWait for WAL confirmation or not.on for safety, off for performance
random_page_costPlanner’s cost estimate for random I/O.Lower if on SSD (e.g. 1.1–1.5)

2️⃣ Index Tuning and Optimization

Indexes are double-edged — they speed reads but slow writes.

TypeDescriptionUse Case
B-TREEDefault index typeFor equality and range queries
HASHHash-basedFast equality only
GINGeneralized Inverted IndexFor JSONB, full text, arrays
GiSTGeneralized Search TreeFor geometric or complex data
BRINBlock Range IndexLarge, append-only tables (e.g., logs)
Partial IndexIndex with WHERE conditionWhen you query subset of rows
Expression IndexIndex on computed valuee.g. LOWER(name)

Example:

CREATE INDEX idx_active_users ON users (last_login)
WHERE active = true;

3️⃣ Vacuum, Analyze & Autovacuum

PostgreSQL uses MVCC (Multi-Version Concurrency Control). Old row versions remain after updates/deletes — VACUUM removes them.

CommandPurpose
VACUUMCleans up dead tuples (frees space)
ANALYZEUpdates query planner statistics
VACUUM FULLRewrites table (reclaims disk space)
AUTOVACUUMAutomatic cleanup background process

Check vacuum activity:

SELECT relname, last_vacuum, last_autovacuum, n_dead_tup
FROM pg_stat_all_tables
WHERE n_dead_tup > 1000;

4️⃣ WAL (Write-Ahead Logging) & Checkpoints

WAL ensures durability — changes are written to WAL logs before disk. This allows recovery after crashes.

ConceptDescription
WAL SegmentDefault 16MB log file containing changes
CheckpointWrites dirty buffers from memory to disk periodically
Archive ModeEnables continuous archiving for PITR (Point-In-Time Recovery)
Replication SlotPrevents WAL removal before standby has consumed it

View WAL files:

ls $PGDATA/pg_wal/

Force checkpoint:

CHECKPOINT;

5️⃣ Replication & High Availability

PostgreSQL supports streaming replication (asynchronous/synchronous).

Setup overview:

  1. Enable replication in postgresql.conf

    wal_level = replica
    max_wal_senders = 5
    
  2. Add replication user:

    CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'secret';
    
  3. Configure pg_hba.conf to allow replication.

  4. Clone base backup:

    pg_basebackup -h primary_host -D /data/replica -U replicator -Fp -Xs -P
    
  5. Start replica.

Monitor replication lag:

SELECT pg_is_in_recovery(), now() - pg_last_xact_replay_timestamp() AS replication_lag;

6️⃣ Query Optimization & EXPLAIN

EXPLAIN and EXPLAIN ANALYZE help identify slow queries.

Example:

EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 123;

You’ll see:

Use these to:


7️⃣ Monitoring and Maintenance Queries

PurposeSQL
Long-running queriesSELECT pid, query, now() - query_start FROM pg_stat_activity WHERE state='active';
Index usage ratioSELECT relname, idx_scan, seq_scan FROM pg_stat_user_tables;
Table bloatSELECT relname, n_dead_tup FROM pg_stat_all_tables;
Connection countSELECT count(*) FROM pg_stat_activity;
I/O statsSELECT * FROM pg_statio_user_tables;

8️⃣ Backup & PITR Strategy

Incremental / PITR backup flow:

  1. Enable WAL archiving

    archive_mode = on
    archive_command = 'cp %p /archive/%f'
    
  2. Use pg_basebackup for base snapshot.

  3. Restore + replay WAL logs for recovery to a specific timestamp.


9️⃣ Security Essentials

SettingPurpose
pg_hba.confControls host-based authentication
ssl = onEnables SSL connections
password_encryption = scram-sha-256Secure password hashing
ALTER ROLE user PASSWORD 'xxx';Rotate passwords
REVOKE CONNECT ON DATABASERestrict access

🔟 Useful Extensions

ExtensionUse Case
pg_stat_statementsTracks slow queries
pg_partmanAutomates table partitioning
pgcryptoEncryption and hashing
postgisGeospatial support
pg_repackOnline table reorganization

Published on: Oct 07, 2025, 05:20 AM  
 

Comments

Add your comment