Operations 51 min read

20 Proven Linux Performance Tweaks to Supercharge CPU, Memory, and Network

This comprehensive guide walks you through the exact scenarios, prerequisites, a 20‑item checklist, and step‑by‑step implementations for tuning CPU scheduling, memory swappiness, huge pages, disk I/O schedulers, network queues, TCP parameters, IRQ affinity, cgroup limits, and monitoring, providing scripts, alert rules, benchmarks, security hardening, troubleshooting tables, rollback playbooks, and best‑practice recommendations for high‑performance Linux servers.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
20 Proven Linux Performance Tweaks to Supercharge CPU, Memory, and Network

Linux System Performance Tuning – 20 Practical Steps

Applicable Scenarios & Prerequisites : High‑concurrency web services, database servers, container platforms, and batch‑processing nodes. Minimum hardware is 4 CPU / 8 GB RAM; production clusters typically start at 16 CPU / 32 GB RAM. Root or sudo access, kernel 3.10+ (RHEL 7) or 4.15+ (Ubuntu 18.04), and sysstat, procps‑ng, net‑tools, perf must be installed.

Environment & Version Matrix

The guide targets RHEL 7/8/9 and Ubuntu 20.04/22.04 LTS with kernel 4.18/5.15. Component versions, minimum and recommended specifications, and required tool packages are listed.

Quick Checklist (20 Items)

Disable Transparent Huge Pages (avoid memory fragmentation spikes)

Adjust CPU Scheduler (choose performance/powersave/ondemand)

Set CPU Affinity (bind critical processes to dedicated cores)

Optimize vm.swappiness (reduce swap usage)

Enable Huge Pages (lower TLB misses)

Tune vm.dirty_ratio (control dirty page write‑back timing)

Raise File Descriptor Limits (increase concurrent connections)

Select Disk Scheduler (none/noop for SSD, deadline for HDD)

Mount Filesystem with noatime/nodiratime (reduce metadata writes)

Adjust net.core.netdev_max_backlog (increase network receive queue)

Tune TCP Window & Buffers (tcp_rmem/tcp_wmem/tcp_window_scaling)

Increase TCP Connection Queues (somaxconn & tcp_max_syn_backlog)

Enable TCP Fast Open (save one RTT on short connections)

Reuse TIME_WAIT sockets (tcp_tw_reuse & tcp_timestamps)

Set IRQ Affinity (distribute NIC interrupts across CPUs)

Disable CPU Idle States (prevent C‑state wake‑up latency)

Adjust Process Nice Values (raise priority for critical services)

Configure cgroup Resource Limits (CPU, memory, I/O isolation)

Enable perf/eBPF Monitoring (deep performance diagnostics)

Automate Cache & Log Cleanup (periodic drop_caches and logrotate)

Implementation Steps (Core Content)

Step 1 – Disable Transparent Huge Pages

Problem : THP causes memory fragmentation and latency spikes (P99 → hundreds ms).

Check Current State :

# cat /sys/kernel/mm/transparent_hugepage/enabled
# Expected output: [always] madvise never

Permanent Disable (RHEL/Ubuntu):

# Method 1: kernel boot parameter
echo 'transparent_hugepage=never' | sudo tee -a /etc/default/grub
sudo grub2-mkconfig -o /boot/grub2/grub.cfg   # RHEL/CentOS
sudo update-grub                               # Ubuntu/Debian

# Method 2: systemd service
cat <<EOF | sudo tee /etc/systemd/system/disable-thp.service
[Unit]
Description=Disable Transparent Huge Pages (THP)
DefaultDependencies=no
After=sysinit.target local-fs.target
Before=mongod.service mysql.service

[Service]
Type=oneshot
ExecStart=/bin/sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/enabled'
ExecStart=/bin/sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/defrag'

[Install]
WantedBy=basic.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now disable-thp.service
EOF

Verify :

# cat /sys/kernel/mm/transparent_hugepage/enabled
# Expected output: always madvise [never]

Step 2 – Adjust CPU Scheduler & Frequency Policy

Scenario : Use performance for low‑latency services, powersave for batch jobs.

Check Current Governor :

# cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
# or cpupower frequency-info

Set to performance (temporary):

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

Persist via systemd :

# cat <<EOF | sudo tee /etc/systemd/system/cpufreq-performance.service
[Unit]
Description=Set CPU governor to performance
After=multi-user.target

[Service]
Type=oneshot
ExecStart=/usr/bin/cpupower frequency-set -g performance
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now cpufreq-performance.service
EOF

Verify :

# cpupower frequency-info | grep "current policy"
# Expected: governor "performance"

Step 3 – Configure CPU Affinity

Bind critical processes (e.g., Nginx, Redis, MySQL) to isolated cores using taskset or cgroup cpuset.

# Bind PID 1234 to CPUs 2‑5
sudo taskset -cp 2-5 1234
# Bind all Nginx workers via cpuset
echo "1-3" | sudo tee /sys/fs/cgroup/cpuset/nginx/cpuset.cpus
sudo pgrep nginx | sudo tee -a /sys/fs/cgroup/cpuset/nginx/tasks

Verify :

# taskset -cp $(pgrep nginx | head -1)
# Expected output: pid 1234's current affinity list: 2-5

Step 4 – Optimize vm.swappiness

Reduce swap pressure for databases.

# Check current value
cat /proc/sys/vm/swappiness   # default 60
# Set to 10 (recommended)
sudo sysctl -w vm.swappiness=10
echo "vm.swappiness = 10" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

Step 5 – Enable Huge Pages

Useful for large‑memory databases and Redis.

# Calculate required pages for 32 GB RAM with 2 MB pages
echo $((32*1024/2))   # 16384 pages
# Apply
echo 16384 | sudo tee /proc/sys/vm/nr_hugepages
echo "vm.nr_hugepages = 16384" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

Verify :

# cat /proc/meminfo | grep -i huge
# Expected: HugePages_Total: 16384

Step 6 – Tune vm.dirty_* Parameters

# Recommended production values
sudo sysctl -w vm.dirty_ratio=10
sudo sysctl -w vm.dirty_background_ratio=5
sudo sysctl -w vm.dirty_expire_centisecs=500
sudo sysctl -w vm.dirty_writeback_centisecs=100
# Persist
cat <<EOF | sudo tee -a /etc/sysctl.conf
vm.dirty_ratio = 10
vm.dirty_background_ratio = 5
vm.dirty_expire_centisecs = 500
vm.dirty_writeback_centisecs = 100
EOF
sudo sysctl -p

Step 7 – Raise File Descriptor Limits

# Temporary per‑shell limit
ulimit -n 1048576
# Global limit
echo "fs.file-max = 2097152" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
# System‑wide limits via limits.conf
cat <<EOF | sudo tee -a /etc/security/limits.conf
* soft nofile 1048576
* hard nofile 1048576
root soft nofile 1048576
root hard nofile 1048576
EOF
# Service‑specific limit (example: Nginx)
cat <<EOF | sudo tee /etc/systemd/system/nginx.service.d/limits.conf
[Service]
LimitNOFILE=1048576
EOF
sudo systemctl daemon-reload
sudo systemctl restart nginx

Step 8 – Choose Disk Scheduler

# SSD/NVMe – use none (or noop)
echo none | sudo tee /sys/block/sda/queue/scheduler
# HDD – use mq-deadline
echo mq-deadline | sudo tee /sys/block/sdb/queue/scheduler
# Persist via udev rule
cat <<EOF | sudo tee /etc/udev/rules.d/60-scheduler.rules
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="none"
ACTION=="add|change", KERNEL=="nvme[0-9]n[0-9]", ATTR{queue/scheduler}="none"
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="1", ATTR{queue/scheduler}="mq-deadline"
EOF
sudo udevadm control --reload-rules && sudo udevadm trigger

Step 9 – Optimize Filesystem Mount Options

# Example for ext4
sudo cp /etc/fstab /etc/fstab.bak.$(date +%F)
sudo sed -i 's/defaults.*/defaults,noatime,nodiratime,discard,errors=remount-ro/' /etc/fstab
# XFS example
# /dev/sdb1 /mnt/data xfs defaults,noatime,nodiratime,logbufs=8,logbsize=256k,inode64 0 2
sudo mount -o remount,noatime,nodiratime /data

Step 10 – Adjust Network Receive Queue

# Increase backlog and budget
sudo sysctl -w net.core.netdev_max_backlog=50000
sudo sysctl -w net.core.netdev_budget=600
sudo sysctl -w net.core.netdev_budget_usecs=8000
# Persist
cat <<EOF | sudo tee -a /etc/sysctl.conf
net.core.netdev_max_backlog = 50000
net.core.netdev_budget = 600
net.core.netdev_budget_usecs = 8000
EOF
sudo sysctl -p

Step 11 – Tune TCP Window & Buffers

# Large buffers for 10 Gbps links
cat <<EOF | sudo tee -a /etc/sysctl.conf
net.ipv4.tcp_rmem = 4096 87380 134217728
net.ipv4.tcp_wmem = 4096 65536 134217728
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_moderate_rcvbuf = 1
net.core.rmem_max = 134217728
net.core.wmem_max = 134217728
EOF
sudo sysctl -p

Step 12 – Increase TCP Connection Queues

# Max listen queue and SYN backlog
cat <<EOF | sudo tee -a /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_synack_retries = 3
EOF
sudo sysctl -p
# Nginx example
cat <<EOF | sudo tee /etc/nginx/nginx.conf
events { worker_connections 65535; }
http { server { listen 80 backlog=65535; } }
EOF
sudo systemctl restart nginx

Step 13 – Enable TCP Fast Open

# Enable both client and server
echo "net.ipv4.tcp_fastopen = 3" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
# Nginx listen fastopen
cat <<EOF | sudo tee -a /etc/nginx/nginx.conf
server { listen 80 fastopen=256; }
EOF
sudo systemctl reload nginx

Step 14 – Reuse TIME_WAIT Sockets

# Enable reuse and timestamps
cat <<EOF | sudo tee -a /etc/sysctl.conf
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.ip_local_port_range = 10000 65535
net.ipv4.tcp_max_orphans = 262144
EOF
sudo sysctl -p

Step 15 – Set IRQ Affinity

# View current IRQs for eth0
cat /proc/interrupts | grep eth0
# Bind IRQ 89 to CPU 2, IRQ 90 to CPU 3
echo 2 | sudo tee /proc/irq/89/smp_affinity_list
echo 3 | sudo tee /proc/irq/90/smp_affinity_list
# Automated script (set‑irq‑affinity.sh) – see appendix

Step 16 – Disable Deep CPU Idle States

# Kernel boot parameter (reboot required)
sudo grubby --update-kernel=ALL --args="intel_idle.max_cstate=0 processor.max_cstate=1"
sudo reboot
# Temporary disable
for state in /sys/devices/system/cpu/cpu*/cpuidle/state*/disable; do echo 1 | sudo tee $state; done

Step 17 – Adjust Process Nice Values

# Raise MySQL priority
sudo renice -n -10 -p $(pgrep mysqld)
# Lower backup script priority
nice -n 19 /usr/local/bin/backup.sh
ionice -c3 nice -n 19 /usr/local/bin/backup.sh

Step 18 – Configure cgroup Resource Limits

# cgroup v1 example (CPU 50%, memory 2 GB)
sudo cgcreate -g cpu,memory:/myapp
echo 50000 | sudo tee /sys/fs/cgroup/cpu/myapp/cpu.cfs_quota_us
echo 100000 | sudo tee /sys/fs/cgroup/cpu/myapp/cpu.cfs_period_us
echo 2147483648 | sudo tee /sys/fs/cgroup/memory/myapp/memory.limit_in_bytes
sudo cgexec -g cpu,memory:/myapp /usr/bin/myapp

# cgroup v2 via systemd
sudo systemctl edit myapp.service
# Add:
# [Service]
# CPUQuota=50%
# MemoryMax=2G
# IOWeight=100

Step 19 – Enable Performance Monitoring (perf/eBPF)

# Install tools (RHEL)
sudo yum install -y perf bcc-tools bpftrace
# Ubuntu
sudo apt install -y linux-tools-common linux-tools-$(uname -r) bpfcc-tools bpftrace

# perf sampling (30 s)
sudo perf record -F 99 -a -g -- sleep 30
sudo perf report --stdio

# eBPF example – biolatency
sudo /usr/share/bcc/tools/biolatency -m 10
# bpftrace one‑liner
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_* { @[probe] = count(); }'

Step 20 – Periodic Cache & Log Cleanup

# Drop caches (page cache only)
sync && echo 1 | sudo tee /proc/sys/vm/drop_caches
# Drop dentries & inodes
sync && echo 2 | sudo tee /proc/sys/vm/drop_caches
# Drop all
sync && echo 3 | sudo tee /proc/sys/vm/drop_caches

# Logrotate example for custom app logs
cat <<EOF | sudo tee /etc/logrotate.d/myapp
/var/log/myapp/*.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
    create 0640 appuser appgroup
    sharedscripts
    postrotate
        /usr/bin/systemctl reload myapp || true
    endscript
}
EOF

Monitoring & Alerting (Ready to Use)

Prometheus Metrics & PromQL Queries

# CPU usage (excluding idle)
100 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)

# Memory available percentage
100 * (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)

# Disk I/O utilization
rate(node_disk_io_time_seconds_total[5m]) * 100

# Network receive drop rate
rate(node_network_receive_drop_total[5m])

# TCP TIME_WAIT count
node_netstat_Tcp_CurrEstab{state="time_wait"}

# File descriptor usage
100 * (process_open_fds / process_max_fds)

# Filesystem usage
100 - ((node_filesystem_avail_bytes / node_filesystem_size_bytes) * 100)

# 1‑minute load average per CPU
node_load1 / count(node_cpu_seconds_total{mode="idle"})

Alertmanager Rules (example)

groups:
- name: system_performance
  interval: 30s
  rules:
  - alert: HighCPUUsage
    expr: 100 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: "High CPU usage on {{ $labels.instance }}"
      description: "CPU usage is {{ $value }}%"

  - alert: HighMemoryPressure
    expr: 100 * (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) < 10
    for: 3m
    labels:
      severity: critical
    annotations:
      summary: "High memory pressure on {{ $labels.instance }}"

  - alert: NetworkDrops
    expr: rate(node_network_receive_drop_total[5m]) > 100
    for: 2m
    labels:
      severity: warning
    annotations:
      summary: "Network packet drops detected on {{ $labels.instance }}"

  - alert: DiskSpaceLow
    expr: 100 - ((node_filesystem_avail_bytes / node_filesystem_size_bytes) * 100) > 85
    for: 10m
    labels:
      severity: warning

Linux Native Monitoring Commands

#!/bin/bash
# Simple real‑time performance monitor (updates every 5 s)
while true; do
  clear
  echo "=== System Performance Monitor ==="
  echo "Timestamp: $(date '+%Y-%m-%d %H:%M:%S')"
  echo "--- CPU Usage ---"
  mpstat 1 1 | tail -1
  echo "--- Memory Usage ---"
  free -h | grep -E 'Mem|Swap'
  echo "--- Disk I/O ---"
  iostat -x 1 1 | tail -n +4
  echo "--- Network Traffic ---"
  sar -n DEV 1 1 | grep -E 'eth0|ens'
  echo "--- TCP Connections ---"
  ss -ant | awk '{print $1}' | sort | uniq -c
  echo "--- Load Average ---"
  uptime
  sleep 5
done

Performance & Capacity (Reproducible)

Benchmark Commands

# CPU benchmark (sysbench prime)
sysbench cpu --cpu-max-prime=20000 --threads=4 run

# Memory benchmark
sysbench memory --memory-block-size=1K --memory-total-size=100G --threads=4 run

# Disk I/O (fio random read/write)
fio --name=randread --ioengine=libaio --iodepth=32 --rw=randread --bs=4k --direct=1 --size=10G --numjobs=4 --runtime=60 --group_reporting
fio --name=randwrite --ioengine=libaio --iodepth=32 --rw=randwrite --bs=4k --direct=1 --size=10G --numjobs=4 --runtime=60 --group_reporting

# Network bandwidth (iperf3)
iperf3 -s   # on server
iperf3 -c <server_ip> -P 10 -t 60   # on client

# HTTP performance (wrk)
wrk -t12 -c400 -d60s --latency http://localhost/

Security & Compliance

Minimum‑Privilege Configuration

# Disable root SSH login
sudo sed -i 's/^PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
sudo systemctl restart sshd

# Audit sudo commands
echo "Defaults logfile=\"/var/log/sudo.log\"" | sudo tee /etc/sudoers.d/audit
echo "Defaults log_input,log_output" | sudo tee -a /etc/sudoers.d/audit

Network Security Settings

# Allow only required services
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

# Restrict SSH to internal subnet (example 10.0.0.0/8)
sudo firewall-cmd --permanent --zone=public \
  --add-rich-rule='rule family="ipv4" source address="10.0.0.0/8" service name="ssh" accept'
sudo firewall-cmd --reload

Compliance Checklist

[ ] System logs retained ≥90 days (journald + logrotate)

[ ] All sudo activity logged to dedicated file

[ ] Direct root SSH login disabled (key‑based sudo only)

[ ] Network parameter changes audited via auditd

[ ] /etc/sysctl.conf and service configs regularly backed up

[ ] SELinux or AppArmor enforced for critical services

Common Issues & Troubleshooting

Network packet loss : Check netdev_max_backlog – increase to 50000.

Port exhaustion (TIME_WAIT) : Enable net.ipv4.tcp_tw_reuse=1 and expand ip_local_port_range.

High disk I/O utilization : Use none scheduler on SSD, mq-deadline on HDD.

Memory pressure with swap activity : Lower vm.swappiness to 10 and adjust vm.dirty_ratio.

CPU appears idle but load is high : Investigate kernel‑mode CPU usage via perf top and IRQ distribution.

SYN queue overflow : Raise net.core.somaxconn and net.ipv4.tcp_max_syn_backlog.

File descriptor limit reached : Increase ulimit -n and fs.file-max.

Change & Rollback Playbooks

Pre‑Change Health Check

#!/bin/bash
# Backup current sysctl
sudo cp /etc/sysctl.conf /etc/sysctl.conf.bak.$(date +%F-%H%M)
# Record baseline performance
echo "=== Baseline ==="
mpstat 1 1 | tail -1
free -h
iostat -x 1 1 | tail -n +4
ss -s
# Verify monitoring endpoint
curl -s http://localhost:9090/-/healthy || echo "Prometheus unhealthy"
# Disk space warning
df -h | awk '$5+0 > 85 {print "WARNING: " $0}'

Post‑Change Validation

#!/bin/bash
# Verify sysctl values
sysctl -a | grep -E 'swappiness|somaxconn|tcp_rmem' > /tmp/sysctl-current.txt
diff /tmp/sysctl-baseline.txt /tmp/sysctl-current.txt || echo "Parameters changed"
# Service health
systemctl is-active nginx mysql redis || echo "Service issue"
# Basic connectivity tests
curl -I http://localhost/ || echo "HTTP error"
mysql -u root -e "SELECT 1;" || echo "MySQL error"
# Simple load test comparison
wrk -t4 -c100 -d10s http://localhost/ > /tmp/perf-after.txt
echo "Compare QPS with baseline"

Rollback Procedure

#!/bin/bash
# Restore sysctl backup
sudo cp /etc/sysctl.conf.bak.* /etc/sysctl.conf
sudo sysctl -p
# Restart affected services
sudo systemctl restart nginx mysql redis
# Verify restoration
sysctl -a | grep -E 'swappiness|somaxconn|tcp_rmem'

Best Practices (10 Key Points)

Always capture a performance baseline (sysbench/fio/wrk) before any tuning.

Prioritize kernel parameter adjustments over application code changes; >80 % of latency issues are solved via sysctl.

Force SSDs to use the none scheduler and mount with noatime to cut I/O latency.

For database servers set vm.swappiness=1 and disable THP to eliminate latency spikes.

High‑concurrency web stacks should apply the three‑pronged network tweak: somaxconn=65535, tcp_tw_reuse=1, and raise fs.file-max / ulimit -n.

Match NIC queue count to CPU core count and bind IRQs to isolated cores for optimal packet processing.

Leverage tuned‑adm profiles (e.g., throughput-performance or latency-performance) for quick baseline configurations.

Continuously monitor the four golden metrics: CPU util, memory free %, disk await, and network drop rate, with automated alerts.

All changes must be reversible: backup /etc/sysctl.conf, use systemctl edit for service overrides, and keep rollback scripts ready.

Run full‑stack load tests quarterly to verify that the current configuration can handle at least twice the expected peak traffic.

Appendix: Full Configuration Samples

sysctl.conf Production Template

# /etc/sysctl.conf – Linux Performance Tuning Profile
# Memory management
vm.swappiness = 10
vm.dirty_ratio = 10
vm.dirty_background_ratio = 5
vm.dirty_expire_centisecs = 500
vm.dirty_writeback_centisecs = 100
vm.overcommit_memory = 1
vm.nr_hugepages = 16384

# File descriptor limits
fs.file-max = 2097152
fs.inotify.max_user_watches = 524288
fs.aio-max-nr = 1048576

# Network core parameters
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 50000
net.core.rmem_max = 134217728
net.core.wmem_max = 134217728
net.core.rmem_default = 87380
net.core.wmem_default = 65536
net.core.netdev_budget = 600
net.core.netdev_budget_usecs = 8000

# TCP parameters
net.ipv4.tcp_rmem = 4096 87380 134217728
net.ipv4.tcp_wmem = 4096 65536 134217728
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_moderate_rcvbuf = 1
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_max_orphans = 262144
net.ipv4.tcp_fastopen = 3
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_synack_retries = 3
net.ipv4.ip_local_port_range = 10000 65535

# Connection tracking
net.netfilter.nf_conntrack_max = 1048576
net.netfilter.nf_conntrack_tcp_timeout_established = 7200

# Security hardening
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

# Kernel limits
kernel.pid_max = 4194304
kernel.threads-max = 4194304
kernel.sysrq = 1
kernel.core_uses_pid = 1

systemd Service Optimization Template

# /etc/systemd/system/myapp.service.d/performance.conf
[Service]
Nice=-10                     # higher CPU priority
CPUSchedulingPolicy=other    # default CFS policy
CPUSchedulingPriority=0
MemoryMax=16G                # hard memory limit
MemoryHigh=14G               # soft limit for reclaim
IOSchedulingClass=realtime
IOSchedulingPriority=0
LimitNOFILE=1048576
LimitNPROC=65535
LimitCORE=infinity
LogRateLimitIntervalSec=30s
LogRateLimitBurst=1000
OOMScoreAdjust=-500

Nginx Performance Configuration Snippet

# /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 1048576;

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

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 1000;
    client_body_buffer_size 128k;
    client_max_body_size 10m;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 8k;
    open_file_cache max=10000 inactive=30s;
    open_file_cache_valid 60s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    server {
        listen 80 reuseport backlog=65535 fastopen=256;
        location / {
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_connect_timeout 5s;
            proxy_send_timeout 10s;
            proxy_read_timeout 10s;
            proxy_pass http://backend;
        }
    }

    upstream backend {
        least_conn;
        keepalive 1024;
        keepalive_requests 10000;
        keepalive_timeout 60s;
        server 10.0.0.1:8080 max_fails=3 fail_timeout=30s;
        server 10.0.0.2:8080 max_fails=3 fail_timeout=30s;
    }
}

Ansible Playbook for Automated Deployment

# deploy-tuning.yml
---
- name: Linux Performance Tuning Deployment
  hosts: all
  become: yes
  tasks:
    - name: Backup current sysctl
      copy:
        src: /etc/sysctl.conf
        dest: "/etc/sysctl.conf.bak.{{ ansible_date_time.iso8601_basic_short }}"
        remote_src: yes

    - name: Deploy tuned sysctl configuration
      copy:
        src: files/sysctl.conf
        dest: /etc/sysctl.conf
        owner: root
        group: root
        mode: '0644'
      notify: Reload sysctl

    - name: Configure file descriptor limits
      blockinfile:
        path: /etc/security/limits.conf
        block: |
          * soft nofile 1048576
          * hard nofile 1048576
          root soft nofile 1048576
          root hard nofile 1048576

    - name: Install and enable THP disabling service
      copy:
        dest: /etc/systemd/system/disable-thp.service
        content: |
          [Unit]
          Description=Disable Transparent Huge Pages
          DefaultDependencies=no
          After=sysinit.target

          [Service]
          Type=oneshot
          ExecStart=/bin/sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/enabled'
          ExecStart=/bin/sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/defrag'

          [Install]
          WantedBy=basic.target
      notify: Enable disable-thp service

    - name: Set CPU governor to performance (if >4 CPUs)
      command: cpupower frequency-set -g performance
      when: ansible_processor_count > 4

  handlers:
    - name: Reload sysctl
      command: sysctl -p

    - name: Enable disable-thp service
      systemd:
        name: disable-thp
        enabled: yes
        state: started
        daemon_reload: yes
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

monitoringperformancesysctlTuning
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.