To fix high MySQL CPU usage on WordPress: Enable the runtime slow query log via SET GLOBAL slow_query_log = 'ON'; SET GLOBAL long_query_time = 1;, analyze bottleneck queries using mysqldumpslow, prune bloated wp_options autoload size below 800KB, index unindexed meta_key lookups in wp_postmeta, and deploy Redis persistent object caching to eliminate redundant read queries.[1][2]
Follow this step-by-step database administration runbook to isolate CPU-intensive SQL transactions, eliminate table lock contention, and tune MariaDB or MySQL 8.0 buffer pools across production web hosting infrastructure.[1][3]
Why Does MySQL Consume High CPU on WordPress Servers?
MySQL and MariaDB processes consume excessive CPU cycles when forced to execute continuous, unindexed row scans across disk rather than serving query result sets directly from RAM.[1] In WordPress architectures, dynamic page requests execute anywhere from 25 to over 150 individual SQL queries before PHP renders the HTML document.[2]
When MySQL spikes to 100% CPU, the root cause almost always maps to one of four systemic bottlenecks:
- Full Table Scans on
wp_postmeta: Standard WordPress schema indexespost_idandmeta_keyindividually, but notmeta_value. Plugins querying post metadata by unindexed values force the database engine to inspect millions of rows sequentially, driving CPU thread usage to maximum saturation.[1][4] wp_optionsAutoload Bloat: WordPress executesSELECT option_name, option_value FROM wp_options WHERE autoload = 'yes'on every single page load.[2] When poorly coded plugins deposit transient caches, session tokens, and analytics dumps into this table, autoload sizes balloon from standard sub-800KB baselines to 10MB or more, triggering severe memory thrashing and CPU overhead.[2]- Missing Persistent Object Caching: Without an in-memory datastore like Redis or Memcached, WordPress queries the relational database repeatedly for identical, static data sets (such as theme options, widget layouts, and post terms) on every HTTP hit.[3]
- WP-Cron and Action Scheduler Stampedes: Automated background jobs—especially WooCommerce order syncs, automated backups, and webhook retries—can execute concurrently without thread limits, spawning dozens of concurrent write transactions that lock InnoDB table rows.[5]
Diagnostic Matrix: High MySQL CPU Symptoms and Remediations
| Root Cause Mechanism | Key Diagnostic Symptom | Diagnostic Command | Direct Remediation Action |
|---|---|---|---|
| Unindexed Metadata Queries | Rows_examined exceeds Rows_sent by >10,000x |
mysqldumpslow -s t /var/log/mysql/slow.log |
Add composite indexes or refactor query clauses |
wp_options Autoload Bloat |
High memory allocation on autoload = 'yes' |
SELECT SUM(LENGTH(option_value)) FROM wp_options WHERE autoload='yes'; |
Prune expired transient options and set autoload='no' |
| InnoDB Buffer Pool Undersized | High disk I/O wait accompanied by 100% CPU | SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_reads'; |
Scale innodb_buffer_pool_size to 70% of available RAM |
| Orphaned WooCommerce Sessions | Millions of rows in wp_woocommerce_sessions |
SELECT count(*) FROM wp_woocommerce_sessions; |
Clear expired sessions via WP-CLI or automated cron |
| WP-Cron Execution Stampede | Hundreds of concurrent admin-ajax.php requests |
SHOW FULL PROCESSLIST; |
Disable WP-Cron in wp-config.php and map to system crontab |
Step-by-Step Diagnostic Checklist: How to Fix High MySQL CPU Usage on WordPress
Execute this sequential diagnostic runbook from the terminal to isolate slow queries, inspect execution plans, and tune database configurations.
Step 1: Capture Active Query Execution in Real Time
When CPU usage spikes, immediately inspect the active database thread pool to identify locked transactions:
# Log in to MySQL shell as root
mysql -u root -p
# View running threads and active execution states
SHOW FULL PROCESSLIST;
Inspect the Time and State columns. Queries in Sending data, Copying to tmp table, or Sorting result that remain active for more than 2 seconds represent critical bottlenecks.[1] Note the Id and terminate runaway transactions immediately:
-- Kill a runaway query thread by its ID
KILL 49201;
Step 2: Enable and Analyze the MySQL Slow Query Log
Turn on runtime slow query logging to log queries exceeding acceptable execution thresholds without requiring a database daemon restart.[1]
-- Enable runtime slow query logging in MySQL/MariaDB
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL slow_query_log_file = '/var/log/mysql/mysql-slow.log';
SET GLOBAL long_query_time = 1.0;
SET GLOBAL log_queries_not_using_indexes = 'ON';
Allow the server to collect query telemetry under live traffic for 15 to 30 minutes, then aggregate the output using mysqldumpslow:
# Summarize the top 10 worst queries by execution time
mysqldumpslow -s t -t 10 /var/log/mysql/mysql-slow.log
# Summarize queries sorting by total rows examined (catches unindexed queries)
mysqldumpslow -s r -t 10 /var/log/mysql/mysql-slow.log
If an individual SQL statement displays an average Query_time of 3.5 seconds and Rows_examined: 450000, the query is forcing full table scans across disk.[1]
Remediating wp_options Autoload Bloat and Transient Backlogs
The single most common internal WordPress database vulnerability is autoload bloat. Every time WordPress initializes the environment, it loads every row in wp_options where autoload = 'yes' into memory as an associative array.[2]
Step 1: Measure Total Autoload Size
Run this SQL query to measure the aggregate payload size of your autoloaded configuration:
-- Calculate total autoloaded data size in Megabytes
SELECT ROUND(SUM(LENGTH(option_value)) / (1024 * 1024), 2) AS autoload_size_mb
FROM wp_options
WHERE autoload = 'yes';
- Under 800 KB: Healthy, high-performance database state.
- 1 MB to 3 MB: Moderate bloat; performance degradation begins under load.
- Above 3 MB: Critical bottleneck; causes severe memory contention and MySQL CPU spikes.[2]
Step 2: Identify and Clean the Largest Autoloaded Records
-- List the 15 largest individual autoloaded rows
SELECT option_name, ROUND(LENGTH(option_value) / 1024, 2) AS size_kb
FROM wp_options
WHERE autoload = 'yes'
ORDER BY LENGTH(option_value) DESC
LIMIT 15;
Common offenders include abandoned transients, debug logging arrays, and unpurged redirect rules. Clean expired transients directly via WP-CLI:
# Purge all expired transients from the terminal
wp transient delete --expired --path=/var/www/html
# Clean all transients if transients table is heavily bloated
wp transient delete --all --path=/var/www/html
Pro Tip: Convert Autoload Flags for Non-Essential Options
For options containing large data arrays that are only needed inside the WP Admin dashboard (such as sitemap caches or analytics data), execute:
UPDATE wp_options SET autoload = 'no' WHERE option_name = 'problematic_option_name';. This prevents the record from loading on frontend visitor traffic.[2]
Indexing Unindexed wp_postmeta and WooCommerce Queries
Complex WooCommerce product catalogs, faceted search filters, and custom post type queries frequently query the wp_postmeta table using meta_value.[4] By default, WordPress only creates an index on post_id and meta_key.
Inspect slow queries with EXPLAIN:
-- Inspect the execution plan of a slow metadata query
EXPLAIN SELECT post_id FROM wp_postmeta WHERE meta_key = '_stock_status' AND meta_value = 'outofstock';
If the type column returns ALL and key returns NULL, MySQL is reading every row in the table.[4]
Adding Composite Indexes
Add a composite index covering meta_key and meta_value to accelerate selective queries:
-- Add optimized composite index to postmeta (adjust key length for InnoDB UTF8MB4 limits)
ALTER TABLE wp_postmeta ADD INDEX meta_key_value (meta_key(191), meta_value(100));
This composite index allows MySQL’s B-Tree traversal engine to locate rows directly in milliseconds without touching unreferenced disk blocks.[4]
Common Pitfall: Adding Unbounded Indexes to Large Tables
Never run unconstrained ALTER TABLE ADD INDEX commands on production tables exceeding 5 million rows during peak traffic hours. Large index builds create exclusive metadata table locks, queuing incoming PHP worker threads and triggering 502/504 gateway timeouts. Execute index modifications during low-traffic windows or use Percona Toolkit's pt-online-schema-change.[3]
Offloading Database Load with Redis Persistent Object Caching
The definitive architectural solution to prevent high MySQL CPU usage is eliminating query execution altogether by caching database result sets in RAM.[3] On high-traffic e-commerce sites hosted on Nextgen Hosting Dedicated Servers or localized Pakistan Dedicated Servers, deploying Redis reduces MySQL query volume by 70% to 90%.[3]
Install and configure Redis on Ubuntu/Debian:
# Install Redis server and PHP Redis extension
apt-get update && apt-get install -y redis-server php-redis
# Configure Redis in /etc/redis/redis.conf
sed -i 's/^maxmemory .*/maxmemory 1024mb/' /etc/redis/redis.conf
sed -i 's/^maxmemory-policy .*/maxmemory-policy allkeys-lru/' /etc/redis/redis.conf
# Restart Redis service
systemctl restart redis-server
Next, add Redis caching keys to wp-config.php:
// Enable persistent Redis object cache
define('WP_CACHE', true);
define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_PORT', 6379);
define('WP_REDIS_TIMEOUT', 1);
define('WP_REDIS_READ_TIMEOUT', 1);
define('WP_REDIS_DATABASE', 0);
Install the Redis Object Cache drop-in (wp-content/object-cache.php) via WP-CLI:
wp plugin install redis-cache --activate --path=/var/www/html
wp redis enable --path=/var/www/html
MySQL / MariaDB Server Tuning Parameters (my.cnf)
For dedicated database nodes and bare-metal cloud servers, optimize InnoDB memory buffers in /etc/mysql/my.cnf under the [mysqld] block:
[mysqld]
# Allocate 60-70% of total system RAM to InnoDB Buffer Pool on dedicated DB servers
innodb_buffer_pool_size = 8G
innodb_buffer_pool_instances = 8
# Optimize log file size to reduce checkpoint flush freezes
innodb_log_file_size = 1G
innodb_log_buffer_size = 64M
# Improve disk I/O handling on NVMe enterprise SSDs
innodb_io_capacity = 2000
innodb_io_capacity_max = 4000
innodb_flush_neighbors = 0
innodb_flush_method = O_DIRECT
# Connection and thread caching
max_connections = 300
thread_cache_size = 64
table_open_cache = 4000
table_definition_cache = 2000
# Slow query logging baseline
slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 1.0
log_queries_not_using_indexes = 0
Restart MySQL to apply the new buffer pool configuration:
systemctl restart mysql
Frequently Asked Questions About WordPress Database CPU Spikes
Why is MySQL taking 100% CPU on my WordPress server?
MySQL reaches 100% CPU saturation when queries perform unindexed table scans across large tables (like wp_postmeta), when wp_options contains several megabytes of bloated autoloaded data, when concurrent background WP-Cron jobs create transaction locks, or when the InnoDB buffer pool is too small to keep working datasets in RAM.[1][2]
How do I enable and read the MySQL slow query log in WordPress?
Enable the log dynamically without restarting by running SET GLOBAL slow_query_log = 'ON'; SET GLOBAL long_query_time = 1; in the MySQL CLI.[1] Read and aggregate the log file using the terminal utility mysqldumpslow -s t /var/log/mysql/mysql-slow.log to sort bottleneck queries by total execution duration.[1]
How do I fix bloated wp_options autoload data?
Query the total autoload size using SELECT SUM(LENGTH(option_value)) FROM wp_options WHERE autoload='yes'.[2] If the result exceeds 1MB, list the largest records, purge expired transients using wp transient delete --expired, and change non-critical frontend options to autoload='no'.[2]
How do missing indexes in wp_postmeta impact database performance?
By default, WordPress does not index the meta_value column.[4] When plugins search products or posts by metadata values (such as SKU, stock status, or custom attributes), MySQL scans every single row in the table, creating massive CPU spikes.[4] Adding composite indexes on (meta_key(191), meta_value(100)) resolves this bottleneck.
How does Redis object caching reduce MySQL CPU usage?
Redis stores compiled WordPress database query results in system RAM.[3] When visitors access pages, WordPress retrieves options, menus, and post metadata directly from Redis memory in microseconds rather than executing repetitive SQL SELECT statements on the MySQL server, cutting database CPU load by up to 90%.[3]
Accelerate WordPress with High-Performance Database Hosting
Eliminate database CPU bottlenecks, table locks, and query latency. Power your enterprise WordPress and WooCommerce applications with dedicated NVMe storage, tuned MariaDB thread pools, and managed Redis acceleration from Nextgen Hosting.
Explore Global Dedicated Servers Explore Pakistan Dedicated ServersDisclaimer: This post is for informational and educational purposes only, accurate to the best of our knowledge at publication. It does not constitute advice. We do not guarantee accuracy or completeness and accept no liability for any decisions or losses resulting from reliance on this content.
Sources & Official References
- MySQL Documentation. "The Slow Query Log and Server Diagnostics in MySQL 8.0." Oracle Corporation. Available at: https://dev.mysql.com/doc/refman/8.0/en/slow-query-log.html
- WordPress Developer Resources. "Options API and Optimization Guidelines for wp_options Autoload." WordPress.org Core Documentation. Available at: https://developer.wordpress.org/apis/options/
- Redis Ltd. "Optimizing Web Application Latency with Redis Object Caching." Redis Technical Guides. Available at: https://redis.io/docs/latest/develop/use-cases/
- MariaDB Foundation. "Optimizing Queries and B-Tree Indexes in MariaDB." MariaDB Knowledge Base. Available at: https://mariadb.com/kb/en/optimization-and-tuning/
- WooCommerce Documentation. "Action Scheduler Architecture and High-Volume Transaction Scaling." WooCommerce Core Engineering. Available at: https://woocommerce.com/document/action-scheduler/
