Performance optimization is crucial for any production Laravel application. This comprehensive guide covers server-level optimizations, PHP configuration tuning, database optimization, and advanced caching strategies that can dramatically improve your application's speed and user experience.
Understanding Performance Bottlenecks
Before diving into optimizations, it's important to understand common performance bottlenecks in Laravel applications:
- PHP execution time: Unoptimized PHP configurations
- Database queries: Slow or inefficient queries
- File I/O operations: Excessive disk reads/writes
- Network latency: Uncompressed responses and missing browser caching
- Memory usage: Insufficient memory allocation
Step 1: PHP Configuration Optimization
OPcache Configuration
OPcache dramatically improves PHP performance by storing compiled bytecode in memory. Edit your PHP configuration:
# Edit the PHP configuration file
nano /opt/cpanel/ea-php82/root/etc/php.ini
Add these OPcache optimizations:
; OPcache Configuration for Performance
[opcache]
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=32
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
opcache.save_comments=1
opcache.validate_timestamps=1
opcache.fast_shutdown=1
; Additional Performance Settings
output_buffering=4096
zlib.output_compression=On
; Session Performance
session.gc_probability=1
session.gc_divisor=1000
; Memory Limits
memory_limit=512M
max_execution_time=300
max_input_time=300
post_max_size=100M
upload_max_filesize=100M
Applying PHP Changes
Restart the web server to apply changes:
systemctl restart httpd
# Verify OPcache is enabled
/opt/cpanel/ea-php82/root/usr/bin/php -r 'echo "OPcache: " . (function_exists("opcache_get_status") ? "ENABLED" : "DISABLED") . "\n";'
Step 2: MySQL Database Optimization
Locating MySQL Configuration
Find your MySQL configuration file:
find /etc -name "my.cnf" 2>/dev/null
# Common locations:
# /etc/my.cnf
# /etc/mysql/my.cnf
# /etc/alternatives/my.cnf
MySQL Performance Tuning
Edit the MySQL configuration file:
Add these performance optimizations under the [mysqld]
section:
[mysqld]
# Performance optimizations
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
query_cache_type = 1
query_cache_size = 64M
max_connections = 500
tmp_table_size = 128M
max_heap_table_size = 128M
# Additional performance settings
innodb_log_buffer_size = 16M
innodb_read_io_threads = 4
innodb_write_io_threads = 4
innodb_file_per_table = 1
# Connection optimization
thread_cache_size = 16
table_open_cache = 4000
Applying MySQL Changes
# Restart MySQL service
systemctl restart mysql
systemctl status mysql
# Verify settings are applied
mysql -u root -p -e "SHOW VARIABLES LIKE 'innodb_buffer_pool_size';"
mysql -u root -p -e "SHOW VARIABLES LIKE 'query_cache_size';"
Step 3: Apache/HTTP Server Optimization
Optimized .htaccess Configuration
Create a performance-optimized .htaccess
file in your public directory:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Handle X-XSRF-Token Header
RewriteCond %{HTTP:x-xsrf-token} .
RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]
# Redirect Trailing Slashes If Not A Folder
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
# ==========================================
# PERFORMANCE OPTIMIZATIONS
# ==========================================
# Enable compression (reduces file sizes by 60-80%)
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/json
</IfModule>
# Browser caching (faster repeat visits)
<IfModule mod_expires.c>
ExpiresActive on
# CSS and JavaScript
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType text/javascript "access plus 1 year"
ExpiresByType application/x-javascript "access plus 1 year"
# Images
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/ico "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
# Documents
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType application/zip "access plus 1 month"
# Fonts
ExpiresByType font/woff "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
ExpiresByType application/font-woff "access plus 1 year"
ExpiresByType application/font-woff2 "access plus 1 year"
</IfModule>
# Security headers
<IfModule mod_headers.c>
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options SAMEORIGIN
Header always set X-XSS-Protection "1; mode=block"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>
# Additional performance optimizations
<IfModule mod_mime.c>
# Force compression for CSS and JS files
<FilesMatch "\.(css|js)$">
<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
</IfModule>
</FilesMatch>
# Set proper MIME types
AddType application/javascript .js
AddType text/css .css
</IfModule>
Root Directory .htaccess
Ensure your root .htaccess
file is optimized:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
# PHP handler
<IfModule mime_module>
AddHandler application/x-httpd-ea-php82 .php .php8 .phtml
</IfModule>
Step 4: Laravel-Specific Optimizations
Environment Configuration
Optimize your .env
file for production:
APP_ENV=production
APP_DEBUG=false
LOG_LEVEL=error
# Cache Configuration
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
# Database Connection Optimization
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=your_app_digital_db
DB_USERNAME=your_app_digital_db_user
DB_PASSWORD=your_secure_password
DB_CHARSET=utf8mb4
DB_COLLATION=utf8mb4_unicode_ci
# Redis Configuration (if using Redis)
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
Laravel Optimization Commands
Run these optimization commands after any configuration changes:
cd /home/your_username/public_html
# Clear all caches
php artisan optimize:clear
# Generate optimized autoloader
composer dump-autoload --optimize --no-dev
# Cache configuration, routes, and views
php artisan config:cache
php artisan route:cache
php artisan view:cache
# Optimize for production
php artisan optimize
# If using events
php artisan event:cache
Step 5: Queue System Setup
Background Job Processing
Set up Laravel's queue system for background processing:
# Process queued jobs
/opt/cpanel/ea-php82/root/usr/bin/php /home/your_username/public_html/artisan queue:work --max-time=60 --sleep=3 --tries=3 --max-jobs=50 >> /dev/null 2>&1
Cron Job Configuration
Add queue processing to cPanel cron jobs:
Navigate to cPanel → Cron Jobs and add:
# Process queue every minute
* * * * * /opt/cpanel/ea-php82/root/usr/bin/php /home/your_username/public_html/artisan schedule:run >> /dev/null 2>&1
# Restart queue worker every 5 minutes (prevents memory leaks)
*/5 * * * * /opt/cpanel/ea-php82/root/usr/bin/php /home/your_username/public_html/artisan queue:restart >> /dev/null 2>&1
Step 6: Testing Your Optimizations
Apache Configuration Test
# Test Apache configuration syntax
httpd -t
# If OK, restart Apache
systemctl restart httpd
Compression Testing
Test if compression is working:
# Test compression
curl -H "Accept-Encoding: gzip,deflate" -I http://yourdomain.com
# Check file sizes (should be much smaller with compression)
curl -H "Accept-Encoding: gzip,deflate" http://yourdomain.com | wc -c
Performance Monitoring
Monitor your optimizations:
# Check PHP processes
ps aux | grep php
# Monitor MySQL processes
mysqladmin -u root -p processlist
# Check server resources
htop
free -h
df -h
Step 7: Advanced Caching Strategies
Redis Integration
If you have Redis available, configure it for better performance:
# Install Redis (if not already installed)
sudo apt update
sudo apt install redis-server
# Start Redis service
sudo systemctl start redis-server
sudo systemctl enable redis-server
Update your Laravel configuration:
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
Database Query Optimization
Implement query optimization in your Laravel application:
// Use eager loading to prevent N+1 queries
$users = User::with(['posts', 'comments'])->get();
// Use database indexes for frequently queried columns
Schema::table('users', function (Blueprint $table) {
$table->index(['email', 'status']);
});
// Use query caching for expensive queries
$expensiveData = Cache::remember('expensive_query', 3600, function () {
return DB::table('large_table')
->join('another_table', '...')
->where('complex_condition', '...')
->get();
});
Performance Monitoring Tools
Built-in Laravel Tools
# Debug mode (only for testing, not production)
php artisan tinker
> DB::enableQueryLog();
> // Run your application
> DB::getQueryLog();
External Monitoring
Consider implementing:
- New Relic: Application performance monitoring
- Blackfire: PHP profiling and optimization
- Scout APM: Laravel-specific monitoring
- Laravel Telescope: Development debugging (remove in production)
Common Performance Issues and Solutions
High Memory Usage
// In your AppServiceProvider
public function boot()
{
if (app()->environment('production')) {
DB::disableQueryLog();
}
}
Slow Asset Loading
# Optimize images before deployment
# Use tools like ImageOptim, TinyPNG, or implement lazy loading
# Minify CSS and JavaScript
npm run production
# Enable Brotli compression if available
<IfModule mod_brotli.c>
AddOutputFilterByType BROTLI_COMPRESS text/plain text/html text/css application/javascript
</IfModule>
Session Performance Issues
// Configure session for better performance
// config/session.php
'driver' => env('SESSION_DRIVER', 'redis'),
'lifetime' => 120,
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => null,
'table' => 'sessions',
'store' => null,
'lottery' => [2, 100],
'cookie' => env('SESSION_COOKIE', 'laravel_session'),
'path' => '/',
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE', true),
'http_only' => true,
'same_site' => 'lax',
Measuring Performance Improvements
Before and After Benchmarks
Use these tools to measure your optimization impact:
# Apache Bench (ab) testing
ab -n 1000 -c 10 https://yourdomain.com/
# Load testing with curl
time curl -w "@curl-format.txt" -o /dev/null -s "https://yourdomain.com/"
# Create curl-format.txt:
echo " time_namelookup: %{time_namelookup}\n
time_connect: %{time_connect}\n
time_appconnect: %{time_appconnect}\n
time_pretransfer: %{time_pretransfer}\n
time_redirect: %{time_redirect}\n
time_starttransfer: %{time_starttransfer}\n
----------\n
time_total: %{time_total}\n" > curl-format.txt
Key Metrics to Monitor
Track these performance indicators:
- Time to First Byte (TTFB): Should be under 200ms
- Page Load Time: Target under 3 seconds
- Database Query Time: Individual queries under 100ms
- Memory Usage: Monitor for memory leaks
- CPU Usage: Should remain stable under load
Production Maintenance Scripts
Automated Optimization Script
Create a maintenance script for regular optimization:
#!/bin/bash
# optimize-laravel.sh
cd /home/your_username/public_html
echo "Starting Laravel optimization..."
# Clear caches
php artisan optimize:clear
# Regenerate optimized files
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan optimize
# Clear expired sessions and cache
php artisan queue:restart
echo "Optimization complete!"
# Optional: Restart services
# systemctl restart httpd
# systemctl restart mysql
Make it executable and add to cron:
chmod +x optimize-laravel.sh
# Add to cron (run daily at 2 AM)
0 2 * * * /home/your_username/optimize-laravel.sh >> /home/your_username/optimization.log 2>&1
Log Rotation and Cleanup
#!/bin/bash
# cleanup-logs.sh
LOG_DIR="/home/your_username/public_html/storage/logs"
# Keep only last 30 days of logs
find $LOG_DIR -name "*.log" -mtime +30 -delete
# Compress old logs
find $LOG_DIR -name "*.log" -mtime +7 -exec gzip {} \;
echo "Log cleanup completed: $(date)"
Security Considerations for Performance
Rate Limiting
Implement rate limiting to prevent abuse:
// In RouteServiceProvider
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
RateLimiter::for('uploads', function (Request $request) {
return Limit::perMinute(10)->by($request->user()?->id ?: $request->ip());
});
Security Headers for Performance
Add security headers that also improve performance:
<IfModule mod_headers.c>
# Security headers
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options SAMEORIGIN
Header always set X-XSS-Protection "1; mode=block"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
# Performance headers
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'"
</IfModule>
CDN Integration for Global Performance
Cloudflare Setup
Configure Cloudflare for global performance:
- Add domain to Cloudflare
Configure these settings:SSL/TLS: Full (Strict)Speed Optimizations:- Auto Minify: CSS, JavaScript, HTML- Brotli: Enabled- Early Hints: Enabled- Rocket Loader: Enabled (test carefully)Caching:- Browser Cache TTL: 4 hours- Always Online: Enabled
AWS CloudFront Alternative
For AWS CloudFront integration:
# Install AWS CLI
pip install awscli
# Configure CloudFront distribution
aws cloudfront create-distribution \
--distribution-config file://distribution-config.json
Troubleshooting Performance Issues
Common Performance Problems
High CPU Usage:
# Identify resource-intensive processes
top -p $(pgrep -d, php)
# Check for infinite loops in queue workers
ps aux | grep "queue:work"
Memory Leaks:
# Monitor memory usage over time
watch -n 5 'free -h'
# Check PHP memory usage
grep memory_limit /opt/cpanel/ea-php82/root/etc/php.ini
Database Bottlenecks:
-- Check slow queries
SHOW FULL PROCESSLIST;
-- Analyze query performance
EXPLAIN SELECT * FROM your_table WHERE conditions;
Performance Debugging Tools
Enable these temporarily for debugging:
// In AppServiceProvider (remove in production)
if (app()->environment('local')) {
DB::listen(function ($query) {
if ($query->time > 100) {
Log::warning('Slow query detected', [
'sql' => $query->sql,
'time' => $query->time
]);
}
});
}
What's Next?
With these performance optimizations in place, your Laravel application should see significant improvements in loading times, response rates, and overall user experience. The next guide in our series will cover email configuration, queue management, and monitoring systems to complete your production setup.
Performance optimization requires ongoing monitoring and fine-tuning. At ScriptVil, we're developing a marketplace where developers can find performance monitoring scripts, optimization tools, and server configuration templates. Whether you need ready-made performance solutions or want to share your optimization expertise, ScriptVil will connect you with the developer community when we launch.
Key Performance Takeaways
- OPcache can improve PHP performance by 300-400%
- Proper database indexing reduces query time by 90%+
- Gzip compression reduces bandwidth usage by 60-80%
- Browser caching dramatically improves repeat visit speeds
- Queue systems prevent UI blocking for heavy operations
- Regular maintenance prevents performance degradation
Remember: Always benchmark before and after optimizations to measure real-world impact. Performance optimization is an iterative process that requires continuous monitoring and adjustment based on your application's specific needs and traffic patterns.