VPSYOUVPSYOU
Home
  • Global Network Performance Test
  • VPS Providers
  • International VPS
  • Domestic VPS
  • Cloud Servers
  • Beginner Guide
  • Server Setup
  • Performance Optimization
  • Speed Test
  • Price Comparison
About
  • 简体中文
  • English
GitHub
Home
  • Global Network Performance Test
  • VPS Providers
  • International VPS
  • Domestic VPS
  • Cloud Servers
  • Beginner Guide
  • Server Setup
  • Performance Optimization
  • Speed Test
  • Price Comparison
About
  • 简体中文
  • English
GitHub
  • Guides

    • VPS Beginner's Guide
    • Server Setup Guide
    • Performance Optimization Guide

Performance Optimization Guide

Advanced techniques to optimize your VPS performance for maximum efficiency and speed.

🎯 Performance Optimization Overview

Key Areas to Optimize

  1. System Resources - CPU, Memory, Disk I/O
  2. Network Performance - Bandwidth, Latency, Connections
  3. Application Layer - Web servers, Databases, Caching
  4. Security vs Performance - Balancing security and speed

🖥️ System-Level Optimization

CPU Optimization

Process Priority Management

# Check current processes
top
htop

# Set process priority (nice values: -20 to 19)
nice -n 10 command          # Lower priority
nice -n -5 command          # Higher priority

# Change running process priority
renice -n 5 -p PID

# CPU affinity (bind process to specific cores)
taskset -c 0,1 command      # Use cores 0 and 1

CPU Governor Settings

# Check available governors
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors

# Set performance governor
echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor

# Make permanent
sudo nano /etc/default/cpufrequtils
GOVERNOR="performance"

Memory Optimization

Swap Configuration

# Check current swap
swapon --show
free -h

# Create swap file (if needed)
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

# Make permanent
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# Optimize swap usage
sudo nano /etc/sysctl.conf
vm.swappiness=10
vm.vfs_cache_pressure=50

Memory Management

# Clear page cache
sudo sync && echo 1 | sudo tee /proc/sys/vm/drop_caches

# Clear dentries and inodes
sudo sync && echo 2 | sudo tee /proc/sys/vm/drop_caches

# Clear all caches
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches

# Optimize memory settings
sudo nano /etc/sysctl.conf
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5
vm.overcommit_memory = 1

Disk I/O Optimization

I/O Scheduler Optimization

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

# Set scheduler (for SSD)
echo noop | sudo tee /sys/block/sda/queue/scheduler

# Set scheduler (for HDD)
echo deadline | sudo tee /sys/block/sda/queue/scheduler

# Make permanent
sudo nano /etc/default/grub
GRUB_CMDLINE_LINUX_DEFAULT="elevator=noop"  # For SSD
sudo update-grub

Filesystem Optimization

# Mount options for better performance
sudo nano /etc/fstab

# For SSD (add noatime, discard)
/dev/sda1 / ext4 defaults,noatime,discard 0 1

# For HDD (add noatime)
/dev/sda1 / ext4 defaults,noatime 0 1

# Remount with new options
sudo mount -o remount /

🌐 Network Optimization

TCP/IP Stack Tuning

# Edit network parameters
sudo nano /etc/sysctl.conf

# TCP optimization
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_congestion_control = bbr

# Connection optimization
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.tcp_max_syn_backlog = 8192
net.core.somaxconn = 65535

# Apply changes
sudo sysctl -p

Network Interface Optimization

# Check network interface
ip addr show

# Optimize network interface
sudo ethtool -G eth0 rx 4096 tx 4096    # Ring buffer size
sudo ethtool -K eth0 gso on gro on       # Enable offloading
sudo ethtool -A eth0 rx on tx on         # Flow control

🚀 Web Server Optimization

Nginx Optimization

Core Configuration

# /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

http {
    # Basic optimization
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    
    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/xml+rss
        application/json;
    
    # File caching
    open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
}

Virtual Host Optimization

server {
    listen 80;
    server_name example.com;
    
    # Static file caching
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        access_log off;
    }
    
    # Enable compression for specific files
    location ~* \.(css|js|html|xml|txt)$ {
        gzip_static on;
    }
    
    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
}

Apache Optimization

Core Configuration

# /etc/apache2/apache2.conf
ServerTokens Prod
ServerSignature Off

# MPM Prefork optimization
<IfModule mpm_prefork_module>
    StartServers 8
    MinSpareServers 5
    MaxSpareServers 20
    MaxRequestWorkers 256
    MaxConnectionsPerChild 10000
</IfModule>

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

# Enable caching
LoadModule expires_module modules/mod_expires.so
<IfModule mod_expires.c>
    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"
</IfModule>

🗄️ Database Optimization

MySQL/MariaDB Optimization

Configuration Tuning

# /etc/mysql/my.cnf
[mysqld]
# Memory settings
innodb_buffer_pool_size = 1G          # 70-80% of available RAM
innodb_log_file_size = 256M
innodb_log_buffer_size = 16M
key_buffer_size = 256M

# Connection settings
max_connections = 200
max_connect_errors = 10000
thread_cache_size = 50
table_open_cache = 4000

# Query optimization
query_cache_type = 1
query_cache_size = 256M
query_cache_limit = 2M

# InnoDB optimization
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
innodb_file_per_table = 1

Query Optimization

-- Enable slow query log
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 2;

-- Analyze slow queries
SHOW PROCESSLIST;
EXPLAIN SELECT * FROM your_table WHERE condition;

-- Optimize tables
OPTIMIZE TABLE your_table;
ANALYZE TABLE your_table;

-- Add indexes for frequently queried columns
CREATE INDEX idx_column_name ON your_table(column_name);

PostgreSQL Optimization

Configuration Tuning

# /etc/postgresql/13/main/postgresql.conf
# Memory settings
shared_buffers = 256MB                 # 25% of RAM
effective_cache_size = 1GB             # 75% of RAM
work_mem = 4MB
maintenance_work_mem = 64MB

# Checkpoint settings
checkpoint_completion_target = 0.9
wal_buffers = 16MB
default_statistics_target = 100

# Connection settings
max_connections = 200

🚀 Caching Strategies

Redis Caching

Installation and Configuration

# Install Redis
sudo apt install redis-server

# Configure Redis
sudo nano /etc/redis/redis.conf

# Optimize settings
maxmemory 512mb
maxmemory-policy allkeys-lru
save 900 1
save 300 10
save 60 10000

# Start and enable Redis
sudo systemctl start redis-server
sudo systemctl enable redis-server

Application Integration

<?php
// PHP Redis example
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

// Cache data
$redis->setex('key', 3600, 'value');

// Retrieve cached data
$cachedData = $redis->get('key');
?>

Memcached

Installation and Configuration

# Install Memcached
sudo apt install memcached

# Configure Memcached
sudo nano /etc/memcached.conf

# Settings
-m 512          # Memory limit (MB)
-c 1024         # Max connections
-I 4m           # Max item size

# Start and enable
sudo systemctl start memcached
sudo systemctl enable memcached

Varnish Cache

Installation and Configuration

# Install Varnish
sudo apt install varnish

# Configure Varnish
sudo nano /etc/varnish/default.vcl

vcl 4.0;

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

sub vcl_recv {
    # Remove cookies for static content
    if (req.url ~ "\.(css|js|png|gif|jp(e)?g|swf|ico)") {
        unset req.http.cookie;
    }
}

sub vcl_backend_response {
    # Cache static content for 1 day
    if (bereq.url ~ "\.(css|js|png|gif|jp(e)?g|swf|ico)") {
        set beresp.ttl = 1d;
    }
}

📊 Monitoring and Profiling

System Monitoring Tools

Install Monitoring Stack

# Install monitoring tools
sudo apt install htop iotop nethogs ncdu

# Install Netdata for real-time monitoring
bash <(curl -Ss https://my-netdata.io/kickstart.sh)

# Install Prometheus and Grafana
sudo apt install prometheus grafana

Performance Profiling

# CPU profiling
perf top
perf record -g command
perf report

# Memory profiling
valgrind --tool=massif command
ms_print massif.out.pid

# I/O monitoring
iotop -o
iostat -x 1

# Network monitoring
nethogs
iftop

Application Performance Monitoring

Web Server Monitoring

# Nginx status module
location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

# Apache status module
<Location "/server-status">
    SetHandler server-status
    Require ip 127.0.0.1
</Location>

Database Monitoring

-- MySQL performance monitoring
SHOW GLOBAL STATUS;
SHOW PROCESSLIST;
SELECT * FROM information_schema.INNODB_METRICS;

-- PostgreSQL monitoring
SELECT * FROM pg_stat_activity;
SELECT * FROM pg_stat_database;

🔧 Automated Optimization Scripts

System Optimization Script

#!/bin/bash
# system-optimize.sh

echo "Starting system optimization..."

# Update system
apt update && apt upgrade -y

# Install performance tools
apt install -y htop iotop nethogs ncdu

# Optimize kernel parameters
cat >> /etc/sysctl.conf << EOF
# Network optimization
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216

# Memory optimization
vm.swappiness = 10
vm.vfs_cache_pressure = 50
EOF

sysctl -p

# Optimize limits
cat >> /etc/security/limits.conf << EOF
* soft nofile 65536
* hard nofile 65536
EOF

echo "System optimization completed!"

📋 Performance Checklist

Daily Monitoring

  • [ ] Check CPU usage (top, htop)
  • [ ] Monitor memory usage (free -h)
  • [ ] Check disk space (df -h)
  • [ ] Review system logs (journalctl -f)

Weekly Optimization

  • [ ] Analyze slow queries
  • [ ] Review cache hit rates
  • [ ] Check for memory leaks
  • [ ] Update system packages

Monthly Review

  • [ ] Performance benchmarking
  • [ ] Capacity planning
  • [ ] Security updates
  • [ ] Configuration review

🎯 Performance Targets

Response Time Goals

  • Web pages: < 2 seconds
  • API responses: < 500ms
  • Database queries: < 100ms
  • Static assets: < 100ms

Resource Utilization

  • CPU usage: < 70% average
  • Memory usage: < 80% of available
  • Disk I/O: < 80% capacity
  • Network: < 70% bandwidth

🔗 Related Resources

  • Server Setup Guide
  • Performance Testing Tools
  • Monitoring Solutions
  • Security Best Practices
Prev
Server Setup Guide