Back to Knowledge Base
performanceoptimizationmonitoring

Performance Optimization Guide

Optimize your servers and applications for maximum performance and efficiency

Sarah Martinez
Updated September 16, 2024

Performance Optimization Guide

Maximizing server and application performance is crucial for delivering excellent user experiences and efficiently utilizing resources.

System-Level Optimization

CPU Optimization

Optimize CPU performance through:

Process Priority Management

# View process priorities
ps -eo pid,ppid,ni,comm

# Adjust process priority
nice -n -10 important_process
renice -10 -p process_id

CPU Affinity

# Set CPU affinity for a process
taskset -c 0,1 process_name
taskset -pc 0,1 process_id

# View current affinity
taskset -p process_id

Memory Optimization

Virtual Memory Tuning

# Optimize swappiness
echo 'vm.swappiness=10' >> /etc/sysctl.conf

# Adjust dirty ratios
echo 'vm.dirty_ratio=15' >> /etc/sysctl.conf
echo 'vm.dirty_background_ratio=5' >> /etc/sysctl.conf

# Apply changes
sysctl -p

Memory Monitoring

# Monitor memory usage
free -h
vmstat 1 10
sar -r 1 10

# Check for memory leaks
valgrind --leak-check=full ./your_program

Storage Optimization

I/O Scheduler Optimization

# Check current I/O scheduler
cat /sys/block/sda/queue/scheduler

# Set appropriate scheduler
echo deadline > /sys/block/sda/queue/scheduler  # For HDDs
echo noop > /sys/block/sda/queue/scheduler      # For SSDs

File System Tuning

# Mount options for performance
mount -o noatime,nodiratime /dev/sda1 /mount/point

# XFS tuning
mount -o noatime,largeio,inode64,swalloc /dev/sda1 /mount/point

# ext4 tuning
tune2fs -o journal_data_writeback /dev/sda1

Web Server Optimization

Nginx Performance Tuning

Basic Configuration

worker_processes auto;
worker_cpu_affinity auto;
worker_connections 1024;

# Enable gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;

# Enable HTTP/2
listen 443 ssl http2;

# Optimize buffers
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 4k;

Caching Configuration

# Browser caching
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

# Proxy caching
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=app_cache:10m max_size=10g;

location / {
    proxy_cache app_cache;
    proxy_cache_valid 200 1h;
    proxy_cache_use_stale error timeout updating;
}

Apache Performance Tuning

MPM Configuration

# For high-traffic sites (Event MPM)
<IfModule mpm_event_module>
    StartServers 3
    MinSpareThreads 75
    MaxSpareThreads 250
    ThreadsPerChild 25
    MaxRequestWorkers 400
    MaxConnectionsPerChild 1000
</IfModule>

Module Optimization

# Enable compression
LoadModule deflate_module modules/mod_deflate.so
<Location />
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip dont-vary
</Location>

# Enable caching
LoadModule expires_module modules/mod_expires.so
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"

Database Optimization

MySQL/MariaDB Tuning

Configuration Optimization

[mysqld]
# Buffer pool size (75% of available RAM)
innodb_buffer_pool_size = 6G
innodb_buffer_pool_instances = 6

# Log file optimization
innodb_log_file_size = 1G
innodb_log_buffer_size = 16M

# Connection optimization
max_connections = 500
max_connect_errors = 10000

# Query cache
query_cache_size = 256M
query_cache_type = 1

# Thread optimization
thread_cache_size = 50
table_open_cache = 4000

Query Optimization

-- Use EXPLAIN to analyze queries
EXPLAIN SELECT * FROM users WHERE email = 'user@example.com';

-- Create appropriate indexes
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at);

-- Optimize slow queries
SELECT * FROM mysql.slow_log WHERE query_time > 2;

PostgreSQL Tuning

Configuration Optimization

# Memory settings
shared_buffers = 2GB
effective_cache_size = 6GB
work_mem = 64MB
maintenance_work_mem = 512MB

# Write-ahead log
wal_buffers = 16MB
checkpoint_completion_target = 0.7
wal_writer_delay = 200ms

# Connection settings
max_connections = 200

Application-Level Optimization

PHP Performance

OPcache Configuration

; Enable OPcache
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1

PHP-FPM Tuning

[www]
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 1000

; Process manager settings
pm.status_path = /status
ping.path = /ping

Node.js Performance

Cluster Mode

const cluster = require('cluster');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
  
  cluster.on('exit', (worker) => {
    console.log(`Worker ${worker.process.pid} died`);
    cluster.fork();
  });
} else {
  require('./app.js');
}

Memory Management

// Garbage collection optimization
node --max-old-space-size=4096 app.js

// Memory leak detection
const memwatch = require('memwatch-next');
memwatch.on('leak', (info) => {
  console.error('Memory leak detected:', info);
});

Network Optimization

TCP Tuning

Kernel Parameters

# Increase network buffers
echo 'net.core.rmem_max = 16777216' >> /etc/sysctl.conf
echo 'net.core.wmem_max = 16777216' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_rmem = 4096 16384 16777216' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_wmem = 4096 16384 16777216' >> /etc/sysctl.conf

# TCP congestion control
echo 'net.ipv4.tcp_congestion_control = bbr' >> /etc/sysctl.conf

# Connection tracking
echo 'net.netfilter.nf_conntrack_max = 1000000' >> /etc/sysctl.conf

CDN Implementation

Cloudflare Configuration

// Next.js with Cloudflare optimization
const nextConfig = {
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, max-age=31536000, immutable',
          },
        ],
      },
    ];
  },
};

Monitoring and Profiling

Performance Monitoring Tools

System Monitoring

# Real-time monitoring
htop
iotop
nethogs

# Historical monitoring
sar -u 1 60    # CPU usage
sar -r 1 60    # Memory usage
sar -d 1 60    # Disk I/O

Application Profiling

# PHP profiling with Xdebug
php -dxdebug.profiler_enable=1 -dxdebug.profiler_output_dir=/tmp script.php

# Node.js profiling
node --prof app.js
node --prof-process isolate-*.log > processed.txt

Performance Benchmarking

Web Server Benchmarking

# Apache Bench
ab -n 10000 -c 100 http://example.com/

# Siege
siege -c 100 -t 60s http://example.com/

# wrk
wrk -t12 -c400 -d30s http://example.com/

Database Benchmarking

# MySQL benchmark
sysbench oltp_read_write --table-size=1000000 --mysql-db=test --mysql-user=root prepare
sysbench oltp_read_write --table-size=1000000 --mysql-db=test --mysql-user=root --threads=16 run

Optimization Checklist

Server Optimization

  • Configure appropriate swappiness
  • Optimize I/O scheduler
  • Tune TCP parameters
  • Enable compression
  • Configure caching

Application Optimization

  • Enable OPcache/bytecode caching
  • Optimize database queries
  • Implement connection pooling
  • Use CDN for static assets
  • Minify CSS/JS files

Monitoring Setup

  • Set up performance monitoring
  • Configure alerting
  • Regular performance testing
  • Capacity planning

Remember: Performance optimization is an iterative process. Monitor, test, optimize, and repeat to achieve the best results.

Article Info

Published
February 20, 2024
Last Updated
September 16, 2024
Author
Sarah Martinez
Reading Time
5 min read

Need Help?

Our support team is here to help with any questions.

Contact Support