Pertemuan 13: Optimasi Sistem

1. Pendahuluan

Optimasi sistem adalah proses meningkatkan kinerja dan efisiensi sistem dengan memanfaatkan sumber daya yang ada secara optimal.

Fokus Pembelajaran: Setelah mempelajari monitoring dan penjadwalan tugas, sekarang kita akan fokus pada teknik-teknik untuk mengoptimalkan kinerja sistem secara keseluruhan.
CPU Optimization
Processing efficiency
Memory Optimization
Memory utilization
I/O Optimization
Disk & network throughput
Application Tuning
Code & configuration

2. Filosofi Optimasi Sistem

Prinsip Dasar Optimasi
Measure Before Optimizing

Selalu ukur sebelum melakukan optimasi. Tanpa metrics, optimasi hanya guessing.

80/20 Rule

80% hasil berasal dari 20% usaha optimasi. Fokus pada bottleneck terbesar.

Law of Diminishing Returns

Optimasi berlebihan justru kontra-produktif. Cari sweet spot.

Holistic Approach

Optimasi harus mempertimbangkan seluruh stack sistem.

Metodologi Optimasi
1
Identify
2
Measure
3
Analyze
4
Implement
5
Validate
6
Monitor
Key Performance Areas:
CPU Optimization
Processing efficiency
Memory Optimization
Memory utilization
I/O Optimization
Disk & network throughput
Application Optimization
Code & configuration tuning

3. Optimasi Kernel dan Sistem Operasi

Kernel Parameter Tuning:
/etc/sysctl.conf - Linux Kernel Parameters
Memory Management:
# Reduce swapping tendency
vm.swappiness = 10

# Limit dirty pages
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5

# Cache retention
vm.vfs_cache_pressure = 50
Network Optimization:
# Increase connection backlog
net.core.somaxconn = 65536

# Network device backlog
net.core.netdev_max_backlog = 65536

# TCP SYN backlog
net.ipv4.tcp_max_syn_backlog = 65536

# Maximum file handles
fs.file-max = 2097152
Apply Changes:
# Reload sysctl settings
sudo sysctl -p

# Check current values
sudo sysctl -a | grep swappiness
I/O Scheduler Optimization:
Available Schedulers
  • CFQ - Completely Fair Queuing
    Default untuk HDD
  • Deadline - Untuk database dan real-time
    Predictable latency
  • NOOP - Untuk SSD dan virtualized
    Simple FIFO queue
  • Kyber - Modern scheduler
    Untuk fast devices
Configure I/O Scheduler
Check Current Scheduler:
cat /sys/block/sda/queue/scheduler
# Output: [noop] deadline cfq
Change Scheduler Temporarily:
echo deadline > /sys/block/sda/queue/scheduler
Permanent Change via GRUB:
# Edit /etc/default/grub:
GRUB_CMDLINE_LINUX_DEFAULT="elevator=deadline"

# Update GRUB
sudo update-grub
Filesystem Optimization:
/etc/fstab - Mount Options
EXT4 Optimization:
UUID=xxx / ext4 defaults,noatime,nodiratime,barrier=0,data=writeback 0 1
XFS Optimization:
UUID=xxx /data xfs defaults,noatime,nodiratime,logbufs=8,logbsize=256k 0 2
SSD Optimization:
UUID=xxx /ssd ext4 defaults,noatime,nodiratime,discard 0 2
Explanation of Options:
  • noatime, nodiratime - Disable access time updates
  • barrier=0 - Disable write barriers (use with UPS)
  • data=writeback - Faster but less safe write mode
  • discard - Enable TRIM for SSDs

4. Memory Optimization

Memory Management Techniques
Transparent HugePages:
# Check status
cat /sys/kernel/mm/transparent_hugepage/enabled

# Disable for database workloads
echo never > /sys/kernel/mm/transparent_hugepage/enabled

# Permanent disable
echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' >> /etc/rc.local
Kernel Samepage Merging (KSM):
# Check KSM status
cat /sys/kernel/mm/ksm/run

# Enable for virtualization hosts
echo 1 > /sys/kernel/mm/ksm/run
Memory Overcommit Settings:
# Check overcommit policy
cat /proc/sys/vm/overcommit_memory

# 0 = heuristic, 1 = always, 2 = no overcommit
echo 0 > /proc/sys/vm/overcommit_memory
Swap Optimization
Swappiness Tuning:
# Reduce swap usage (0-100, lower = less swapping)
echo 10 > /proc/sys/vm/swappiness

# For database servers, set even lower
echo 1 > /proc/sys/vm/swappiness
Multiple Swap Files:
# Create additional swap file
sudo fallocate -l 2G /swap2
sudo chmod 600 /swap2
sudo mkswap /swap2
sudo swapon /swap2

# Add to /etc/fstab
/swap2 none swap sw 0 0
Swap Monitoring:
# Check swap usage
free -h
swapon --show

# Monitor swap activity
vmstat 1

5. CPU dan Process Optimization

CPU Frequency Scaling
CPU Governors:
  • performance - Maximum clock speed
  • powersave - Minimum clock speed
  • ondemand - Scale based on load
  • conservative - Similar to ondemand but gradual
Set CPU Governor:
# Check current governor
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor

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

# Install cpufrequtils for permanent control
sudo apt install cpufrequtils
echo 'GOVERNOR="performance"' | sudo tee /etc/default/cpufrequtils
Process Priority & Affinity
Nice Values:
# Start process with low priority
nice -n 19 ./cpu_intensive_script.sh

# Change priority of running process
renice -n 15 -p 1234
CPU Affinity:
# Set process to specific CPU cores
taskset -cp 0,1 1234

# Start process bound to cores 2-3
taskset -c 2,3 ./application
Interrupt Balancing:
# Check interrupt distribution
cat /proc/interrupts

# Set IRQ affinity
echo 2 > /proc/irq/24/smp_affinity # CPU core 1
echo 4 > /proc/irq/25/smp_affinity # CPU core 2

6. Disk I/O Optimization

RAID Optimization
RAID Level Selection:
  • RAID 0 - Striping (performance, no redundancy)
  • RAID 1 - Mirroring (redundancy, read performance)
  • RAID 5 - Striping + Parity (balance, good for reads)
  • RAID 10 - Mirroring + Striping (performance + redundancy)
RAID Configuration:
# Create RAID 10 array
sudo mdadm --create /dev/md0 --level=10 --raid-devices=4 /dev/sdb /dev/sdc /dev/sdd /dev/sde

# Optimize read-ahead
echo 4096 > /sys/block/md0/queue/read_ahead_kb
LVM & SSD Optimization
LVM Stripped Volumes:
# Create striped logical volume
sudo lvcreate -L 100G -i 4 -I 64 -n fast_vol vg0

# -i 4: 4 stripes, -I 64: 64KB stripe size
LVM Caching:
# Add SSD cache to HDD volume
sudo lvconvert --type cache --cachepool vg0/ssd_cache vg0/slow_volume
SSD TRIM Support:
# Enable periodic TRIM
sudo systemctl enable fstrim.timer
sudo systemctl start fstrim.timer

# Manual TRIM
sudo fstrim -v /
SSD Mount Options:
# /etc/fstab for SSD
UUID=xxx /ssd ext4 defaults,noatime,nodiratime,discard 0 2

7. Network Optimization

Kernel Network Parameters
# /etc/sysctl.conf network optimizations
net.core.rmem_max = 134217728 # Max receive buffer
net.core.wmem_max = 134217728 # Max send buffer
net.ipv4.tcp_rmem = 4096 65536 134217728
net.ipv4.tcp_wmem = 4096 65536 134217728
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_sack = 1
Network Interface Tuning
# Increase ring buffers
sudo ethtool -G eth0 rx 4096 tx 4096

# Enable Jumbo Frames (if supported)
sudo ethtool -K eth0 mtu 9000

# Disable flow control
sudo ethtool -A eth0 rx off tx off

# Check interface settings
sudo ethtool eth0
TCP Optimization
# TCP congestion control
echo 'net.ipv4.tcp_congestion_control = bbr' >> /etc/sysctl.conf

# TCP keepalive settings
echo 'net.ipv4.tcp_keepalive_time = 300' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_keepalive_intvl = 60' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_keepalive_probes = 5' >> /etc/sysctl.conf

8. Application-Specific Optimization

Web Server Optimization
Nginx Tuning:
# /etc/nginx/nginx.conf
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65536;

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

http {
  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout 30;
  keepalive_requests 1000;
}
Database Optimization
MySQL/MariaDB:
# /etc/mysql/my.cnf
[mysqld]
# Memory settings
innodb_buffer_pool_size = 4G
innodb_log_file_size = 512M
key_buffer_size = 256M

# I/O settings
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
PostgreSQL:
# postgresql.conf
shared_buffers = 4GB
effective_cache_size = 12GB
work_mem = 64MB
maintenance_work_mem = 512MB

9. Monitoring dan Validation Optimasi

Performance Benchmarking
Disk I/O Benchmark:
# Sequential read/write
sudo hdparm -tT /dev/sda

# Random I/O with fio
sudo fio --name=randwrite --ioengine=libaio --iodepth=64 \
--rw=randwrite --bs=4k --direct=1 --size=1G --numjobs=4
Network Benchmark:
# Throughput test
iperf3 -c server-ip -t 30

# Latency test
ping -c 10 server-ip
Memory Benchmark:
# Memory bandwidth
sudo apt install mbw
mbw -n 5 256
Continuous Monitoring
Custom Monitoring Script:
#!/bin/bash
# performance_monitor.sh

LOG_FILE="/var/log/performance.log"

{
echo "=== Performance Snapshot $(date) ==="
echo "Load: $(uptime | awk -F'load average:' '{print $2}')"
echo "Memory: $(free -h | grep Mem)"
echo "Disk I/O: $(iostat -d | grep sda)"
echo ""
} >> $LOG_FILE
Automated Alerting:
#!/bin/bash
# performance_alert.sh

THRESHOLD_LOAD=5.0
THRESHOLD_MEM=90

CURRENT_LOAD=$(cat /proc/loadavg | awk '{print $1}')
if (( $(echo "$CURRENT_LOAD > $THRESHOLD_LOAD" | bc -l) )); then
  echo "High load" | mail -s "Alert" admin@company.com
fi

10. Best Practices dan Anti-Patterns

Optimization Best Practices
  • Test in Staging - Selalu test optimasi di environment staging
  • One Change at a Time - Implement perubahan satu per satu
  • Document Changes - Dokumentasi semua perubahan konfigurasi
  • Monitor Impact - Pantau impact optimasi secara kontinu
  • Have Rollback Plan - Siapkan plan untuk rollback perubahan
Common Optimization Mistakes
  • Over-Optimization - Optimasi berlebihan tanpa measurable benefit
  • Wrong Metrics - Fokus pada metrics yang salah
  • Ignoring Bottlenecks - Optimasi area yang bukan bottleneck
  • No Baseline - Tidak ada baseline measurement sebelum optimasi
  • Production Testing - Test optimasi langsung di production

11. Studi Kasus: E-commerce Platform Optimization

Scenario:

E-commerce site mengalami slow performance selama flash sales dengan gejala:

  • Response time meningkat dari 200ms ke 2000ms
  • Database connection timeouts
  • High CPU usage pada web servers
  • Slow checkout process
Optimization Strategy:
Infrastructure
  • Implement Redis caching
  • Database read replicas
  • CDN for static assets
  • Load balancer tuning
Application
  • Query optimization
  • Connection pooling
  • Async processing
  • Code profiling
System
  • Kernel parameter tuning
  • I/O scheduler optimization
  • Memory management tuning
  • Network stack optimization
Specific Optimizations Applied:
# Database Optimization
innodb_buffer_pool_size = 8G
innodb_log_file_size = 1G
max_connections = 500

# Web Server Tuning
worker_processes = 8;
worker_connections = 4096;
keepalive_timeout = 15;

# Caching Implementation
redis_maxmemory = 2gb
redis_maxmemory-policy = allkeys-lru
Results:

60%

Improvement in response time

3x

Increase in concurrent user capacity

99.9%

Uptime during peak loads

12. System Optimization Advisor

Optimization Recommendation Engine
System Profile:
Optimization Recommendations:

Ringkasan Pembelajaran

Key Optimization Areas:
  • Kernel parameter tuning untuk performance
  • Memory management dan swap optimization
  • I/O scheduler dan filesystem tuning
  • Network stack optimization
  • Application-specific configuration
Best Practices:
  • Measure before optimizing
  • Focus on actual bottlenecks
  • Test changes in staging
  • Monitor impact continuously
  • Document all optimizations