PostgreSQL ships with conservative defaults designed to run on minimal hardware. On a production Hong Kong VPS with dedicated NVMe SSD and allocated RAM, these defaults leave significant performance on the table. This guide covers every meaningful PostgreSQL tuning parameter, connection pooling with PgBouncer, and query-level optimisation — moving your database from default to genuinely performant.
Step 1: Install PostgreSQL 16
apt install -y curl ca-certificates
install -d /usr/share/postgresql-common/pgdg
curl -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc --fail \
https://www.postgresql.org/media/keys/ACCC4CF8.asc
sh -c 'echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] \
https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" \
> /etc/apt/sources.list.d/pgdg.list'
apt update && apt install -y postgresql-16
systemctl enable --now postgresql
Step 2: Core Memory Configuration
Edit /etc/postgresql/16/main/postgresql.conf. The parameters below are tuned for a dedicated 8 GB RAM VPS — scale proportionally for your plan:
# ============================================================
# MEMORY — the most impactful parameters
# ============================================================
# shared_buffers: PostgreSQL's own buffer cache
# Rule: 25% of total RAM for dedicated DB server
# 25% of 8 GB = 2 GB
shared_buffers = 2GB
# effective_cache_size: estimate of total memory available for caching
# (shared_buffers + OS page cache)
# Rule: 75% of total RAM
effective_cache_size = 6GB
# work_mem: memory per sort/hash operation (NOT per connection)
# Total memory used = work_mem × active sort operations (can be many)
# Start conservative, increase if slow sorts appear in EXPLAIN
# Rule: (RAM - shared_buffers) / max_connections / 4
work_mem = 32MB
# maintenance_work_mem: for VACUUM, CREATE INDEX, ALTER TABLE
# Can be larger since these run infrequently
maintenance_work_mem = 512MB
# huge_pages: use Linux huge pages for shared_buffers (reduces TLB pressure)
# Requires OS configuration — set to 'try' to enable when available
huge_pages = try
Step 3: WAL and Checkpoint Configuration
# ============================================================
# WAL (Write-Ahead Log) — durability vs performance trade-offs
# ============================================================
# wal_buffers: WAL buffer size (auto-set based on shared_buffers)
wal_buffers = 64MB
# checkpoint_completion_target: spread checkpoint writes over this fraction
# Higher = smoother I/O, lower peak write bursts
checkpoint_completion_target = 0.9
# max_wal_size: maximum WAL size between checkpoints
# Larger = fewer checkpoints = better write throughput, more recovery time
max_wal_size = 4GB
min_wal_size = 1GB
# synchronous_commit: transaction durability guarantee
# 'on' = wait for WAL to be written to disk (safest, ~5ms extra latency)
# 'off' = async commit (~3x faster writes, risk of last 0.5s data on crash)
# For most web apps, 'off' is acceptable — no corruption risk, just recent-write risk
synchronous_commit = off
Step 4: Query Planner Settings
# ============================================================
# QUERY PLANNER — help PostgreSQL make better decisions
# ============================================================
# random_page_cost: cost of a random NVMe page read vs sequential
# Default 4.0 is tuned for spinning HDD; NVMe is much faster random access
# Lower value → planner prefers index scans over seq scans (correct for NVMe)
random_page_cost = 1.1
# effective_io_concurrency: parallel I/O operations for bitmap heap scans
# Set to number of NVMe drives (1 for single NVMe, 4+ for RAID)
effective_io_concurrency = 200
# parallel query workers
max_worker_processes = 8 # Match your vCPU count
max_parallel_workers = 8
max_parallel_workers_per_gather = 4
max_parallel_maintenance_workers = 4
Step 5: Connection Configuration
# ============================================================
# CONNECTIONS — don't over-provision
# ============================================================
# max_connections: each connection uses ~5-10MB shared memory
# Web apps should use connection pooling (PgBouncer) not raw connections
max_connections = 200
# Listening — localhost only for security
listen_addresses = 'localhost'
port = 5432
Apply All Changes
systemctl restart postgresql
# Verify settings
sudo -u postgres psql -c "SHOW shared_buffers;"
sudo -u postgres psql -c "SHOW effective_cache_size;"
sudo -u postgres psql -c "SHOW random_page_cost;"
Step 6: Install and Configure PgBouncer (Connection Pooling)
Each PostgreSQL connection consumes 5–10 MB of memory and requires process forking. Web applications creating thousands of short-lived connections overwhelm PostgreSQL at scale. PgBouncer maintains a small pool of persistent connections to PostgreSQL and multiplexes thousands of application connections through them.
apt install -y pgbouncer
cat > /etc/pgbouncer/pgbouncer.ini << 'EOF' [databases] # Route all connections for 'myapp' database myapp = host=127.0.0.1 port=5432 dbname=myapp [pgbouncer] listen_addr = 127.0.0.1 listen_port = 6432 auth_type = scram-sha-256 auth_file = /etc/pgbouncer/userlist.txt # Transaction pooling — most efficient for web apps # Connection returned to pool after each transaction pool_mode = transaction # Pool size: 20 persistent connections to PostgreSQL per database user default_pool_size = 20 max_client_conn = 1000 # Up to 1000 simultaneous application connections reserve_pool_size = 5 reserve_pool_timeout = 3 # Logging log_connections = 0 log_disconnections = 0 log_pooler_errors = 1 server_reset_query = DISCARD ALL EOF # Create userlist (hashed passwords) sudo -u postgres psql -c "SELECT rolname, rolpassword FROM pg_authid WHERE rolname='myapp_user';" \ | awk '{print $1, $2}' >> /etc/pgbouncer/userlist.txt
systemctl enable --now pgbouncer
Point your application at PgBouncer (port 6432) instead of PostgreSQL directly (port 5432). The connection string changes only in port; everything else remains the same.
Step 7: Indexing Strategies
Identify Missing Indexes
-- Find sequential scans on large tables (likely missing indexes)
SELECT
schemaname,
tablename,
seq_scan,
seq_tup_read,
idx_scan,
n_live_tup
FROM pg_stat_user_tables
WHERE seq_scan > 0 AND n_live_tup > 10000
ORDER BY seq_scan DESC
LIMIT 20;
Find Slow Queries
-- Enable pg_stat_statements extension
sudo -u postgres psql -c "CREATE EXTENSION IF NOT EXISTS pg_stat_statements;"
-- Top 10 slowest queries by total execution time
SELECT
round(total_exec_time::numeric, 2) AS total_ms,
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
left(query, 100) AS query_preview
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
Create Partial and Composite Indexes
-- Standard index
CREATE INDEX CONCURRENTLY idx_orders_user_id ON orders(user_id);
-- Partial index (only index rows matching condition)
-- Much smaller, faster for common filtered queries
CREATE INDEX CONCURRENTLY idx_orders_pending
ON orders(created_at)
WHERE status = 'pending';
-- Composite index (for queries filtering on multiple columns)
CREATE INDEX CONCURRENTLY idx_products_category_price
ON products(category_id, price)
WHERE active = true;
-- BRIN index for time-series data (very small, good for timestamp ranges)
CREATE INDEX CONCURRENTLY idx_events_timestamp_brin
ON events USING brin(created_at)
WITH (pages_per_range = 128);
Always use CONCURRENTLY when creating indexes in production — it builds the index without locking the table, allowing reads and writes to continue.
Step 8: VACUUM and AUTOVACUUM Tuning
# PostgreSQL accumulates dead rows (from UPDATE/DELETE) that bloat tables
# AUTOVACUUM cleans them but default settings are conservative
# In postgresql.conf:
autovacuum = on
autovacuum_vacuum_cost_delay = 2ms # Default 20ms — more aggressive
autovacuum_vacuum_scale_factor = 0.01 # Vacuum when 1% of rows are dead (default 20%)
autovacuum_analyze_scale_factor = 0.005 # Analyze when 0.5% rows changed
autovacuum_max_workers = 4 # More workers for busy databases
# Manually vacuum a bloated table
sudo -u postgres psql -d myapp -c "VACUUM ANALYZE orders;"
# Check table bloat
SELECT
tablename,
pg_size_pretty(pg_total_relation_size(tablename::regclass)) AS total_size,
pg_size_pretty(pg_relation_size(tablename::regclass)) AS table_size,
n_dead_tup,
n_live_tup,
round(n_dead_tup * 100.0 / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;
Step 9: EXPLAIN ANALYZE — Understanding Query Plans
-- Analyse a slow query
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT o.*, u.email
FROM orders o
JOIN users u ON o.user_id = u.id
WHERE o.status = 'pending'
AND o.created_at > NOW() - INTERVAL '7 days'
ORDER BY o.created_at DESC
LIMIT 50;
Key things to look for in EXPLAIN output:
- Seq Scan on large tables — usually needs an index
- Hash Join with large row counts — work_mem may be too low (spilling to disk)
- Nested Loop with many iterations — may indicate missing join index
- Buffers: hit vs read — high “read” means data not in shared_buffers (cache miss)
Performance Comparison: Before vs After Tuning
| Metric | Default Config | Tuned Config (8 GB VPS) |
|---|---|---|
| Complex JOIN query (1M rows) | 800–2,000ms | 80–200ms |
| Bulk INSERT (10k rows) | 2–5s | 200–500ms |
| Connection overhead (1k/s) | 50ms+ | 1–2ms (PgBouncer) |
| Cache hit rate | 60–70% | 95%+ |
| Max sustained TPS | 200–500 | 2,000–8,000 |
Conclusion
PostgreSQL tuning on a Hong Kong VPS is high-leverage work — adjusting shared_buffers, random_page_cost, and adding PgBouncer connection pooling typically delivers 5–10× query throughput improvement on default installations. The NVMe SSD in Server.HK VPS plans makes the lower random_page_cost = 1.1 setting particularly impactful, steering the planner toward index scans that dramatically outperform sequential scans on NVMe hardware.
Run your tuned database: Browse Server.HK Hong Kong VPS plans — 8 GB and 16 GB plans are ideal for PostgreSQL workloads with large working sets.