Step-by-Step: How to Optimize MySQL/PostgreSQL Database on VPS

Database performance tuning diagram showing InnoDB buffer pool allocation and query index optimization on a VPS server.
Verified Answer

Optimizing MySQL/MariaDB and PostgreSQL on a VPS centers on sizing memory buffers to match your RAM without triggering OOM swaps: allocate 60–70% of dedicated DB memory to innodb_buffer_pool_size (MySQL) or 25% to shared_buffers (PostgreSQL), enable slow-query logging to add missing B-tree indexes, and deploy connection pooling.

Default package installations of MySQL 8.0, MariaDB 10.11, and PostgreSQL 16 ship with conservative memory defaults designed to boot on 512 MB micro-instances. When you run WooCommerce, SaaS APIs, or analytics dashboards against those stock settings on a 4 GB or 8 GB VPS, queries spill to temporary disk tables, CPU spikes on full-table scans, and concurrent connections exhaust available RAM. Tuning buffer allocation, NVMe I/O concurrency, and query indexing transforms sluggish database response times without buying larger hardware.

In-Memory Working Set

Sizing InnoDB and PostgreSQL buffers keeps hot indexes in RAM instead of hitting disk.

Index-First Queries

Composite B-tree indexes cut multi-second table scans down to sub-millisecond lookups.

NVMe I/O Alignment

Tuned redo logs and I/O capacity exploit high-IOPS SSDs without write stalls.

MySQL/MariaDB vs. PostgreSQL Memory Tuning Reference

MySQL (InnoDB) manages its own large buffer cache directly, whereas PostgreSQL relies on a smaller shared buffer paired with the Linux kernel page cache. Never blindly copy a 16 GB configuration onto a 4 GB NVMe VPS that also runs Nginx and PHP-FPM—leave at least 25–35% of system RAM for the OS and web workers.

Tuning Parameter MySQL 8 / MariaDB PostgreSQL 16 Target on 8 GB VPS
Primary Buffer Cache innodb_buffer_pool_size shared_buffers 4G (MySQL) / 2G (PG)
OS Cache Hint innodb_flush_method = O_DIRECT effective_cache_size O_DIRECT / 5G–6G
Sort / Temp Memory tmp_table_size / sort_buffer_size work_mem 64M tmp / 16MB work_mem
WAL / Redo Sizing innodb_redo_log_capacity max_wal_size 1G–2G
NVMe Concurrency innodb_io_capacity random_page_cost 2000 IOPS / 1.1 cost

Right-Sizing InnoDB Buffer Pool and Redo Logs in MySQL

In MySQL and MariaDB, innodb_buffer_pool_size is the single highest-impact setting. It caches both table rows and B-tree indexes in memory. Set innodb_flush_method = O_DIRECT on Linux so InnoDB bypasses double-buffering in the OS filesystem cache, freeing RAM for PHP or Node.js processes.

On NVMe storage, raise innodb_io_capacity = 2000 and innodb_io_capacity_max = 4000 so background page flushing keeps pace with bursty writes. Keep innodb_flush_log_at_trx_commit = 1 for strict ACID durability on financial or e-commerce databases, or use 2 only if losing up to one second of transactions during a power loss is acceptable. In MySQL 8.0+, replace legacy innodb_log_file_size directives with innodb_redo_log_capacity (typically 1 GB to 2 GB on active VPS instances) so large batch imports and index rebuilds never stall waiting for checkpoint flushes.

For multi-core VPS servers, set innodb_buffer_pool_instances equal to the number of gigabytes allocated when the pool exceeds 1 GB (capped at 8), which reduces internal mutex contention across concurrent reader and writer threads.

Tuning PostgreSQL Shared Buffers, Work Memory, and Autovacuum

For PostgreSQL on NVMe VPS nodes, lower random_page_cost from its spinning-disk default of 4.0 down to 1.1. Without this change, the query planner frequently avoids efficient index scans because it overestimates random disk seek penalties. Set effective_io_concurrency = 200 to match SSD parallelism, and allocate effective_cache_size to roughly 70% of total system RAM so PostgreSQL accurately estimates how much data resides in the OS page cache.

Also monitor autovacuum closely. High-churn tables accumulate dead tuples that bloat index size and degrade sequential scans. Lower autovacuum_vacuum_scale_factor to 0.05 on large tables so vacuum workers reclaim dead tuples proactively rather than stalling peak traffic. On busy transactional workloads, increasing autovacuum_max_workers to 4 and raising maintenance_work_mem to 512 MB ensures index cleanup completes rapidly without exhausting NVMe write bandwidth.

Identifying Slow Queries and Missing Indexes with EXPLAIN

Hardware tuning cannot fix an unindexed WHERE or ORDER BY clause. Enable MySQL’s slow query log (long_query_time = 0.5) or PostgreSQL’s pg_stat_statements extension to capture the top queries by total execution time, then inspect their execution plans with EXPLAIN ANALYZE.

Watch for type: ALL in MySQL or Seq Scan in PostgreSQL on tables exceeding a few thousand rows, as well as Using temporary; Using filesort indicators. Creating a targeted composite index following the equality-first, range-last rule (e.g., CREATE INDEX idx_orders_status_created ON orders(status, created_at)) routinely cuts query latency from hundreds of milliseconds down to under 2 ms while reducing CPU utilization across the entire VPS.

Database CLI — Bash

# /etc/mysql/mysql.conf.d/99-vps-tuning.cnf (Example for 8 GB shared web+DB VPS)
[mysqld]
innodb_buffer_pool_size = 4G
innodb_redo_log_capacity = 1G
innodb_flush_method = O_DIRECT
innodb_io_capacity = 2000
innodb_io_capacity_max = 4000
max_connections = 150
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 0.5

# Quick MySQL & PostgreSQL diagnostic checks via CLI
mysqltuner --user root
psql -U postgres -c "SELECT query, calls, total_exec_time FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;"

Connection Pooling and Linux Kernel Swappiness

Setting max_connections = 1000 is a common anti-pattern that crashes VPS instances under load, because every active thread allocates per-connection sort, join, and read buffers. Keep max_connections realistic (100–200) and place PgBouncer in front of PostgreSQL or ProxySQL in front of MySQL when serving serverless or high-concurrency microservices.

Finally, set vm.swappiness = 1 in /etc/sysctl.conf so the Linux kernel keeps database buffer pages in RAM rather than swapping them out prematurely. Combine this with automated logical backups (mysqldump --single-transaction or pg_dump) scheduled during off-peak hours so maintenance jobs never compete with live user traffic for NVMe bandwidth.

Bypassing phpMyAdmin Limits: CLI Streaming Imports for 5 GB+ Databases

Browser-based tools like phpMyAdmin or Adminer routinely fail when importing SQL dumps larger than 250 MB because PHP upload_max_filesize, max_execution_time, and Nginx FastCGI timeouts abort mid-transaction—leaving partially populated tables and broken foreign keys. On a Linux VPS, streaming compressed SQL archives directly over CLI eliminates HTTP timeouts and completes multi-gigabyte imports in a fraction of the time.

For MySQL and MariaDB, wrap large imports in session-level flags that defer secondary index validation and transaction commits until the stream finishes, while temporarily raising max_allowed_packet to handle bulk INSERT statements. For PostgreSQL, convert plain SQL dumps to custom directory format (-Fd) so pg_restore can load tables and build B-tree indexes in parallel across multiple vCPU cores.

Database CLI — Bash

# 1. Stream a 10 GB gzipped MySQL dump with live progress and disabled commit overhead
(echo "SET autocommit=0; SET unique_checks=0; SET foreign_key_checks=0;";  zcat prod_backup.sql.gz;  echo "SET foreign_key_checks=1; SET unique_checks=1; COMMIT;")  | pv | mysql --max_allowed_packet=512M -u root -p target_db

# 2. Parallel PostgreSQL restore across 4 vCPU cores with elevated maintenance memory
PGOPTIONS="-c maintenance_work_mem=512MB" pg_restore   -U postgres -d target_db -j 4 --no-owner --role=app_user prod_backup.dump

If you temporarily lower innodb_flush_log_at_trx_commit = 2 during a massive migration, restore it to 1 immediately afterward so ACID durability remains intact in production.

When importing into an existing live schema where downtime is unacceptable, always restore into a staging database first, verify index integrity with ANALYZE TABLE or ANALYZE VERBOSE; so the query planner rebuilds up-to-date cardinality statistics, and then perform an atomic database rename or connection-string cutover during a quiet window.

Deploying PgBouncer and ProxySQL to Eliminate Connection Exhaustion

High-concurrency web stacks—such as Next.js serverless routes, Laravel Octane workers, or microservice fleets—open hundreds of short-lived database TCP connections during traffic bursts. Because PostgreSQL spawns an independent OS backend process per client socket (consuming 5–10 MB of base memory plus per-sort work_mem), 400 idle app sockets can consume over 4 GB of VPS RAM before executing a single complex join.

Inserting PgBouncer in transaction pooling mode decouples client connections from backend PostgreSQL processes: 500 concurrent web workers share a tight, cache-warm pool of 25–40 database processes with near-zero context-switching overhead. On MySQL/MariaDB stacks, ProxySQL performs similar connection multiplexing while transparently routing SELECT traffic to read replicas and INSERT/UPDATE statements to the primary node.

PuTTY / Linux Terminal (bash)

# /etc/pgbouncer/pgbouncer.ini — High-concurrency transaction pooling
[databases]
app_prod = host=127.0.0.1 port=5432 dbname=app_prod

[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
auth_type = scram-sha-256
pool_mode = transaction
max_client_conn = 600
default_pool_size = 30
reserve_pool_size = 10
server_reset_query = DISCARD ALL

When using transaction pooling in PgBouncer, disable session-bound prepared statements in older ORMs (or upgrade to PgBouncer 1.21+ which supports protocol-level prepared statement multiplexing) to avoid intermittent prepared statement does not exist errors.

Diagnosing Lock Contention, Wait Events, and Kernel Memory Pages

When CPU utilization stays low yet query latency spikes during checkout bursts, your database is blocked on row locks, mutex contention, or dirty-page checkpoint flushes rather than raw compute. Inspecting live engine wait events pinpoints the exact bottleneck within seconds.

Engine Diagnostic Command / View Critical Bottleneck Signal
MySQL 8 / InnoDB SHOW ENGINE INNODB STATUS\G High History list length (>50k) or buffer pool free-page waits
PostgreSQL 16 pg_stat_activity + pg_blocking_pids(pid) wait_event_type = 'Lock' or 'LWLock' during peak writes
Linux Kernel cat /sys/kernel/mm/transparent_hugepage/enabled THP set to [always] causing compaction latency spikes

Disable Linux Transparent Huge Pages (never) on dedicated database VPS nodes and set vm.dirty_background_ratio = 5 with vm.dirty_ratio = 10 so the kernel flushes modified NVMe pages smoothly in small background batches rather than freezing disk I/O during massive checkpoint storms.

For large multi-gigabyte tables on PostgreSQL, monitor index bloat and long-running idle in transaction sessions regularly, because an abandoned open transaction prevents autovacuum from reclaiming dead row versions even when aggressive scale factors are configured. Adding idle_in_transaction_session_timeout = '5min' and statement_timeout = '30s' at the role or database level protects your VPS from runaway ORM bugs and ensures predictable tail latency under peak concurrency.

Frequently Asked Questions on VPS Database Optimization

How much RAM should I give MySQL on a 4 GB VPS running WordPress?
When Nginx, PHP-FPM, and MySQL share a 4 GB VPS, set innodb_buffer_pool_size to 1.5 GB–2 GB so PHP workers and the Linux OS retain enough headroom without triggering the OOM killer.
Should I enable MySQL Query Cache in MySQL 8.0 or MariaDB?
MySQL 8.0 removed the legacy Query Cache because its global mutex caused severe contention on multi-core servers. Use Redis or Memcached for application-level object caching instead.
Why does PostgreSQL run faster after changing random_page_cost?
The default 4.0 cost assumes slow spinning HDDs, pushing PostgreSQL toward sequential scans. Lowering it to 1.1 reflects NVMe random read speed so the planner chooses fast index lookups.
When should I separate the database onto its own dedicated VPS?
Move MySQL or PostgreSQL to a separate private-network VPS once your active dataset exceeds 50% of shared RAM or when CPU spikes from PHP/Node.js workers starve database I/O.
What value should vm.swappiness be set to on a database VPS?
Set vm.swappiness = 1 (or 10 on shared app+DB nodes) in /etc/sysctl.conf so the Linux kernel avoids swapping out MySQL InnoDB buffer pools or PostgreSQL shared buffers under normal memory pressure.
How does PgBouncer reduce RAM overhead on a PostgreSQL VPS?
PostgreSQL forks a dedicated OS process for every client connection, consuming 5–10 MB per idle socket. Placing PgBouncer in transaction pooling mode multiplexes hundreds of app connections onto a small pool of backend DB processes.
Step-by-Step How to Optimize MySQL/PostgreSQL Database

Applying the mysql/mariadb vs postgresql memory tuning reference principles covered above helps prevent resource bottlenecks and configuration drift in production. Review our VPS hosting specifications to match CPU, NVMe I/O, and network capacity to your workload.