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.
Sizing InnoDB and PostgreSQL buffers keeps hot indexes in RAM instead of hitting disk.
Composite B-tree indexes cut multi-second table scans down to sub-millisecond lookups.
Tuned redo logs and I/O capacity exploit high-IOPS SSDs without write stalls.
- MySQL/MariaDB vs. PostgreSQL Memory Tuning Reference
- Right-Sizing InnoDB Buffer Pool and Redo Logs in MySQL
- Tuning PostgreSQL Shared Buffers, Work Memory, and Autovacuum
- Identifying Slow Queries and Missing Indexes with EXPLAIN
- Connection Pooling and Linux Kernel Swappiness
- Bypassing phpMyAdmin Limits: CLI Streaming Imports for 5 GB+ Databases
- Deploying PgBouncer and ProxySQL to Eliminate Connection Exhaustion
- Diagnosing Lock Contention, Wait Events, and Kernel Memory Pages
- Frequently Asked Questions on VPS Database Optimization
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.
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.
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.
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?
Should I enable MySQL Query Cache in MySQL 8.0 or MariaDB?
Why does PostgreSQL run faster after changing random_page_cost?
When should I separate the database onto its own dedicated VPS?
What value should vm.swappiness be set to on a database VPS?
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?
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.
