📋 Introduction
This comprehensive guide covers MariaDB database optimization for WordPress hosting environments. While WordPress optimization plugins focus on individual site databases, this guide addresses system-level MariaDB optimization for improved efficiency and performance across all databases.
- Optimize MariaDB database management system performance
- Configure InnoDB buffer pool and log buffer settings
- Use MySQLTuner for performance analysis and recommendations
- Monitor and manage database memory usage
- Implement proper maintenance schedules
🔧 MySQLTuner Overview
MySQLTuner is a powerful script that analyzes your MariaDB configuration and provides recommendations for optimal performance and stability. Proper usage is critical for maintaining a healthy database environment.
- Frequency: Run MySQLTuner once every 60-90 days maximum
- Traffic Requirement: Ensure your sites have active traffic for accurate recommendations
- Implementation: Add variables one at a time and restart MariaDB after each change
- Support: Consult the course Q&A for advice before implementing recommendations
Running MySQLTuner
Navigate to the MySQLTuner directory and execute the script with sudo privileges:
cd ~/MySQLTuner/ls -lsudo ./mysqltuner⚙️ InnoDB Configuration
Understanding InnoDB Components
InnoDB is the default storage engine for MariaDB and MySQL. Two critical parameters affect its performance: the log buffer size and the buffer pool size.
InnoDB Memory Architecture
Data Requests
Cached Data & Indexes
Transaction Changes
Persistent Storage
1. InnoDB Log Buffer Size
The InnoDB log buffer temporarily stores transaction data before writing it to disk log files. Increasing this buffer reduces disk write frequency and improves write performance.
Recommended Value: 32MB
Purpose: Caches data changes before flushing to InnoDB log files
Check Current Log Buffer Size
First, log in to MariaDB and check the current setting:
sudo mariadbSHOW VARIABLES LIKE 'innodb_log_buffer_size';exit;Configure Log Buffer Size
Edit the main MariaDB configuration file:
sudo nano /etc/mysql/mariadb.conf.d/50-server.cnfAdd the following directive in the InnoDB section (typically after innodb_log_file_size):
innodb_log_buffer_size = 32MSave the file (Ctrl+O, Enter, Ctrl+X) and restart MariaDB:
sudo systemctl restart mariadb2. InnoDB Buffer Pool Size
The buffer pool is the most critical InnoDB memory component. It caches frequently accessed table data and indexes in RAM, dramatically reducing disk I/O operations.
- Recommended: 80% of total server RAM
- Purpose: Prevent memory swapping to disk
- Example: For a 1GB RAM server, set buffer pool to 800MB
Understanding Memory Swapping
What is Swapping?
Swapping occurs when the system moves data from RAM to disk storage due to insufficient memory. For databases, this causes:
- Slower query execution
- Increased latency
- Reduced throughput
- Potential server crashes
Monitor Buffer Pool Usage
Check actual memory consumption of the InnoDB buffer pool:
sudo mariadbSHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_bytes_data';The query returns the value in bytes. Remove the last six digits to convert to megabytes.
Result: 6,700,000 bytes = 6.7 MB
Server RAM: 1 GB (1,000 MB)
Buffer Pool Limit: 80% = 800 MB
Current Usage: 6.7 MB / 800 MB = 0.84% (very low)
Buffer Pool Usage Visualization
Current Usage Example
6.7 MB used out of 800 MB available
- Monitor at 25-30% usage: Begin planning for RAM upgrade
- Action Required: Take screenshots and consult course Q&A
- Prevention: Regular monitoring prevents performance degradation
📊 Database Monitoring Queries
View Database Sizes
Monitor the size of all databases on your server:
SELECT table_schema AS "Database", ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS "Size (MB)" FROM information_schema.tables GROUP BY table_schema;
View InnoDB Database Sizes
Filter to show only InnoDB engine databases:
SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.tables WHERE engine = 'InnoDB' GROUP BY table_schema;
View Buffer Pool Usage by Database
See how much buffer pool memory each database consumes:
SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.tables WHERE engine = 'InnoDB' GROUP BY table_schema;
For WordPress sites using exclusively InnoDB tables, the database size and buffer pool usage will be identical. This is normal and indicates all tables use the InnoDB storage engine.
View Table I/O Statistics
Monitor read/write operations and performance metrics per table:
SELECT object_schema AS 'Database', object_name AS 'Table', COUNT_READ AS 'Reads', COUNT_WRITE AS 'Writes', SUM_TIMER_READ / 1000000000 AS 'Read Time (ms)', SUM_TIMER_WRITE / 1000000000 AS 'Write Time (ms)' FROM performance_schema.table_io_waits_summary_by_table ORDER BY SUM_TIMER_READ + SUM_TIMER_WRITE DESC;
Understanding I/O Statistics
| Column | Description |
|---|---|
| Database | Name of the database |
| Table | Name of the table |
| Reads | Number of read operations performed |
| Writes | Number of write operations performed |
| Read Time (ms) | Total time spent on read operations in milliseconds |
| Write Time (ms) | Total time spent on write operations in milliseconds |
🛠️ Database Maintenance Operations
Optimize All Databases
Database optimization reorganizes physical storage, reduces fragmentation, reclaims unused space, and improves query performance.
sudo mysqlcheck --optimize --all-databases"Table does not support optimize, doing recreate and analyze instead"
This is not an error. It indicates MySQL is using an alternative optimization method that recreates the table and updates index statistics. This approach ensures proper optimization even for tables that don't support the traditional OPTIMIZE TABLE command.
Auto-Repair Databases
Automatically check and repair corrupted tables:
sudo mysqlcheck --auto-repair --check --all-databasesMaintenance Process Flow
Scan for errors
Fix corruption
Reorganize data
Update statistics
⚠️ Critical: InnoDB Log File Size
Changing the InnoDB log file size requires a specific procedure to prevent data corruption.
- STOP the MariaDB service first
- MODIFY the innodb_log_file_size directive
- START the MariaDB service
⚠️ WARNING: If you restart MariaDB instead of stopping, modifying, and then starting, you may corrupt InnoDB tables!
Correct Procedure for Log File Size Changes
sudo systemctl stop mariadbEdit the configuration file:
sudo nano /etc/mysql/mariadb.conf.d/50-server.cnfModify the directive:
innodb_log_file_size = 200MStart the service:
sudo systemctl start mariadbComparison: Safe vs Unsafe Methods
| ✓ SAFE METHOD | ✗ UNSAFE METHOD |
|---|---|
|
1. Stop service 2. Modify config 3. Start service |
1. Modify config 2. Restart service ⚠️ Risk of corruption! |
📈 Interpreting MySQLTuner Results
Performance Metrics Section
The Performance Metrics section provides critical information about memory usage and server capacity.
| Metric | Description | Action Threshold |
|---|---|---|
| Maximum Reached Memory | Highest memory usage achieved | Monitor if approaching 150-200% |
| Maximum Possible Memory | Theoretical maximum if all connections used | Should not exceed server RAM |
| Overall Possible Memory Usage | Percentage of total memory that could be used | Take action at 150-200% |
Common Recommendations
- "MySQL started within the last 24 hours - recommendations may be inaccurate"
- "Reduce your overall MySQL memory footprint"
- "Dedicate this server to your database for highest performance"
- Take a screenshot of the Performance Metrics section
- Post in the course Q&A MySQLTuner thread
- Request advice on reducing max_connections
- Default connections: 151 (may need reduction)
Memory Usage Threshold Examples
Memory Usage Status
Normal (127%)
Warning (175%)
Critical (200%+)
✅ Implementation Best Practices
Variable Adjustment Strategy
Add one variable
Restart MariaDB
Test functionality
Monitor performance
- Easier troubleshooting if issues arise
- Clear cause-and-effect relationships
- Ability to roll back specific changes
- Better understanding of performance impacts
When to Seek Help
Use the course Q&A MySQLTuner featured question thread when:
- First time receiving variables to adjust
- Uncertain about implementing recommendations
- Memory usage reaches 150-200%
- Buffer pool usage exceeds 25-30%
- Experiencing performance degradation
- Need guidance on connection limits
🚀 Caching for Database Optimization
Proper caching implementation is crucial for reducing database queries and improving overall server performance.
- Page Caching: Stores rendered HTML pages, eliminating repeated database queries
- Object Caching: Stores database query results in memory (Redis, Memcached)
- Combined Impact: Drastically reduces database load and improves response times
Request Flow: Without vs With Caching
| Without Caching | With Caching |
|---|---|
|
Request → PHP → Database Query → Process → Render Slow |
Request → Cache → Response (Database bypassed) Fast |
By implementing proper page and object caching, database queries are reduced dramatically, leading to improved server performance and better resource utilization.
📚 Quick Reference Commands
System Updates
sudo apt update && sudo apt upgrade -y && sudo apt autoremove -y
MariaDB Service Management
sudo systemctl restart mariadbsudo systemctl stop mariadbsudo systemctl start mariadbsudo systemctl status mariadbConfiguration File Locations
/etc/mysql/mariadb.conf.d/50-server.cnfDatabase Maintenance
sudo mysqlcheck --optimize --all-databasessudo mysqlcheck --auto-repair --check --all-databasesMonitor Buffer Pool
SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_bytes_data';Run MySQLTuner
cd ~/MySQLTuner/sudo ./mysqltuner📋 Additional Server Tasks Reference
WordPress Updates with Permission Management
Default PHP Pool User - Standard Permissions
cd /var/www/example.com/sudo ls -l public_html/sudo chown -R PHP_POOL_USER:PHP_POOL_USER public_html/sudo find /var/www/example.com/public_html/ -type d -exec chmod 770 {} \;
sudo find /var/www/example.com/public_html/ -type f -exec chmod 660 {} \;
After setting permissions, open the WordPress Dashboard to run updates, then restart PHP-FPM:
sudo systemctl reload php8.3-fpmDefault PHP Pool User - Hardened Permissions
cd /var/www/example.com/sudo chown -R PHP_POOL_USER:PHP_POOL_USER public_html/sudo find /var/www/example.com/public_html/ -type d -exec chmod 550 {} \;
sudo find /var/www/example.com/public_html/ -type f -exec chmod 440 {} \;
sudo find /var/www/example.com/public_html/wp-content/ -type d -exec chmod 770 {} \;
sudo find /var/www/example.com/public_html/wp-content/ -type f -exec chmod 660 {} \;
Security Scanning Tools
ClamAV Installation and Usage
sudo apt updatesudo apt install clamavDisable automatic updates:
sudo systemctl stop clamav-freshclamsudo systemctl disable clamav-freshclamManual database update and scan:
sudo freshclamsudo clamscan -r /path/to/scanRKHunter (Rootkit Hunter)
sudo apt install rkhuntersudo rkhunter --propupdsudo rkhunter --checkall --skView log files:
sudo cat /var/log/rkhunter.logsudo less /var/log/rkhunter.logRemove automatic cron jobs:
cd /etc/cron.daily/sudo rm rkhuntercd /etc/cron.weekly/sudo rm rkhunterDisk Space Management
df -hsudo apt autoremove && sudo apt cleansudo journalctl --vacuum-time=1daysView directory sizes:
cd /du -ah --max-depth=1 | sort -h🎯 Summary
Optimizing MariaDB requires careful planning, systematic implementation, and ongoing monitoring. Key takeaways include:
- Run MySQLTuner sparingly (every 60-90 days) with active traffic
- Implement configuration changes incrementally
- Monitor buffer pool usage regularly (alert at 25-30%)
- Follow proper procedures for InnoDB log file size changes
- Leverage caching to reduce database load
- Maintain regular database optimization and repair schedules
- Seek guidance when memory usage approaches critical thresholds
- Verify current InnoDB buffer pool configuration
- Adjust log buffer size to 32MB
- Run baseline MySQLTuner analysis
- Set up monitoring schedule
- Implement page and object caching
- Schedule regular maintenance tasks