← Back to Playbooks
    SEV-3Linux

    Slow Ubuntu System Diagnostics Playbook

    Comprehensive triage for a slow or unresponsive Ubuntu/Linux system. Covers CPU saturation, memory pressure, disk I/O bottlenecks, network issues, kernel tuning, swap thrashing, runaway processes, and systemd service debugging. This is the "everything is slow and I don't know why" playbook.

    Operator's Field Notes

    Jeremy Martinez · Incident Commander | Principal Site Reliability Engineer

    "When someone says 'the server is slow', there are exactly four resources that can be the bottleneck: CPU, memory, disk I/O, and network. That's it. Everything else - slow queries, unresponsive apps, timeout errors - is a symptom of one of these four being saturated. Your job is to figure out which one, then figure out why."

    "I always start with the same three commands: top (orhtop),vmstat 1 5, andiostat -xz 1 5. In 30 seconds, these three commands tell you if it's CPU, memory, or disk. Then you dig deeper."

    "The most common trap: the system has plenty of free memory but is swapping. Linux's OOM killer hasn't triggered because the system technically has swap space. But swap is 100x slower than RAM, and every page fault is killing latency. Check vmstat forsi/socolumns - if they're non-zero, you're swapping."

    First 60 Seconds - The Big Three

    1. top / htop - Overview

    # Quick system overview
    top -bn1 | head -20
    
    # Better: htop with tree view
    htop -t
    
    # What to look for in top:
    # - Load average: > number of CPUs = CPU saturated
    # - %CPU: which process is consuming most
    # - %MEM: memory hog identification
    # - RES: actual physical memory used per process
    # - S (state): D = uninterruptible sleep (usually IO wait)
    #              R = running, Z = zombie
    
    # Sort by CPU: press P
    # Sort by Memory: press M
    # Sort by Time: press T

    2. vmstat - CPU/Memory/Swap at a Glance

    # 5 samples, 1 second apart
    vmstat 1 5
    
    # Output columns:
    # procs:  r (run queue), b (blocked/IO wait)
    # memory: swpd, free, buff, cache
    # swap:   si (swap in), so (swap out) - MUST be 0 in steady state
    # io:     bi (blocks in), bo (blocks out)
    # system: in (interrupts), cs (context switches)
    # cpu:    us (user), sy (system), id (idle), wa (IO wait), st (stolen)
    
    # RED FLAGS:
    #   r > num_cpus → CPU saturated
    #   b > 0 consistently → processes blocked on IO
    #   si/so > 0 → swap thrashing (VERY BAD for latency)
    #   wa > 10% → disk IO bottleneck
    #   st > 5% → VM host is overcommitted (steal time)

    3. iostat - Disk I/O Analysis

    # Detailed disk stats, 5 samples, 1 second apart
    iostat -xz 1 5
    
    # Key columns:
    #   %util: disk utilization (>80% = saturated)
    #   await: average IO wait time in ms (>20ms = slow for SSD)
    #   r_await / w_await: read/write latency separately
    #   avgqu-sz: average queue length (>1 = queuing)
    #   iops (r/s + w/s): total IO operations per second
    
    # RED FLAGS:
    #   %util > 80% → disk is the bottleneck
    #   await > 50ms → slow disk (could be dying disk, or IO patterns)
    #   avgqu-sz > 4 → significant IO queuing

    CPU Investigation

    Identify CPU-Hungry Processes

    # Top CPU consumers
    ps aux --sort=-%cpu | head -20
    
    # CPU usage over time (if sar is installed)
    sar -u 1 10
    
    # Per-CPU utilization (check for imbalanced cores)
    mpstat -P ALL 1 5
    
    # If one core is at 100% while others are idle:
    # → Single-threaded application bottleneck
    # → IRQ affinity issue (network interrupts on one core)
    
    # Check IRQ distribution
    cat /proc/interrupts | head -20
    
    # Check for CPU throttling (thermal or power management)
    cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
    cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq

    perf top - What's Consuming CPU Cycles

    # Real-time CPU profiling (requires linux-tools-generic)
    sudo perf top
    
    # Profile a specific process
    sudo perf top -p $(pgrep myapp)
    
    # Record and analyze
    sudo perf record -p $(pgrep myapp) -g -- sleep 30
    sudo perf report
    
    # Flame graph generation
    sudo perf script | stackcollapse-perf.pl | flamegraph.pl > flamegraph.svg
    
    # If perf isn't installed:
    sudo apt install linux-tools-generic linux-tools-$(uname -r)

    strace - What's a Process Doing

    # Trace system calls for a slow process
    sudo strace -c -p $(pgrep myapp)
    # Wait 30 seconds, then Ctrl+C to see summary
    
    # Output shows:
    #   % time | seconds | calls | syscall
    # High % on futex → lock contention
    # High % on read/write → IO bound
    # High % on epoll_wait → idle, waiting for events
    # High % on clock_nanosleep → sleeping
    
    # Detailed trace with timing
    sudo strace -tt -T -p $(pgrep myapp) 2>&1 | head -100

    Memory Investigation

    Memory Usage Analysis

    # Detailed memory breakdown
    free -h
    # "available" is what matters - not "free"
    # Linux uses free memory for disk cache
    # "available" = free + reclaimable cache
    
    # Detailed memory info
    cat /proc/meminfo
    
    # Key values:
    #   MemAvailable: actual usable memory
    #   SwapTotal / SwapFree: swap usage
    #   Dirty: data waiting to be written to disk
    #   Slab: kernel data structures
    
    # Top memory consumers
    ps aux --sort=-%mem | head -20
    
    # Memory map of a specific process
    pmap -x $(pgrep myapp) | tail -5
    
    # Check for memory leaks - RSS growing over time
    watch -n 5 'ps -p $(pgrep myapp) -o pid,rss,vsz,%mem'

    Swap Thrashing - The Silent Killer

    # Check swap usage
    swapon --show
    
    # Check which processes are using swap
    for pid in $(ls /proc/[0-9]*/status 2>/dev/null | cut -d/ -f3); do
      swap=$(grep VmSwap /proc/$pid/status 2>/dev/null | awk '{print $2}')
      if [ "$swap" -gt 0 ] 2>/dev/null; then
        name=$(cat /proc/$pid/comm 2>/dev/null)
        echo "$swap kB - PID $pid - $name"
      fi
    done | sort -rn | head -20
    
    # Check swappiness (how aggressively Linux swaps)
    cat /proc/sys/vm/swappiness
    # Default: 60 - for servers, set to 10 or lower:
    sudo sysctl vm.swappiness=10
    
    # Emergency: Disable swap (CAREFUL - can trigger OOM killer)
    sudo swapoff -a
    
    # Monitor swap IO in real-time
    vmstat 1 | awk '{print $7, $8}'  # si and so columns

    Disk I/O Investigation

    Find IO-Heavy Processes

    # IO stats per process (requires iotop)
    sudo iotop -o -P  # -o shows only processes doing IO
    
    # If iotop isn't installed:
    sudo apt install iotop
    
    # Alternative: check /proc for IO stats
    for pid in $(ls /proc/[0-9]*/io 2>/dev/null | cut -d/ -f3); do
      name=$(cat /proc/$pid/comm 2>/dev/null)
      io=$(cat /proc/$pid/io 2>/dev/null | grep write_bytes | awk '{print $2}')
      if [ "$io" -gt 0 ] 2>/dev/null; then
        echo "$io - PID $pid - $name"
      fi
    done | sort -rn | head -10
    
    # Check what files a process has open
    sudo lsof -p $(pgrep myapp) | head -30
    
    # Check for processes in D state (uninterruptible IO wait)
    ps aux | awk '$8 ~ /D/ {print}'

    Filesystem Health

    # Check disk space
    df -h
    
    # Check inode usage
    df -i
    
    # Check for filesystem errors (read-only remount = FS error)
    dmesg | grep -i "ext4|xfs|error|readonly"
    
    # Check disk health (SMART data)
    sudo smartctl -a /dev/sda
    
    # Look for:
    #   Reallocated_Sector_Ct: > 0 = dying disk
    #   Current_Pending_Sector: > 0 = bad sectors
    #   Offline_Uncorrectable: > 0 = data loss risk
    
    # Check for deleted but open files (consuming space invisibly)
    sudo lsof +L1 | head -20

    Network Investigation

    # Check network interface stats
    ip -s link show
    
    # Look for:
    #   RX errors, dropped, overruns → NIC problem
    #   TX errors, dropped → congestion or driver issue
    
    # Check for packet loss and latency
    ping -c 10 GATEWAY_IP
    
    # Check TCP connection states
    ss -s
    # Many TIME_WAIT → connection churn
    # Many CLOSE_WAIT → application not closing connections
    
    # Check for network saturation
    sar -n DEV 1 5
    
    # Check DNS resolution speed
    time dig google.com
    # If > 1 second, DNS is a problem
    
    # Check for firewall drops
    sudo iptables -L -v -n | grep -i drop
    sudo nft list ruleset | grep drop

    systemd & Journal Analysis

    Service Health

    # List failed services
    systemctl list-units --state=failed
    
    # Check a specific service
    systemctl status myapp.service
    
    # View service logs
    journalctl -u myapp.service --since "1 hour ago" --no-pager | tail -50
    
    # Check for OOM kills
    journalctl -k | grep -i "oom|killed process"
    dmesg | grep -i "oom|killed process"
    
    # Check boot time (slow boot diagnosis)
    systemd-analyze
    systemd-analyze blame | head -20
    systemd-analyze critical-chain
    
    # Check for services that are restarting in a loop
    journalctl -u myapp.service --since "1 hour ago" | grep -c "Started|Stopped"

    Kernel Parameters to Check

    # File descriptor limits
    cat /proc/sys/fs/file-nr    # allocated / free / max
    ulimit -n                    # per-process limit
    
    # If running out of file descriptors:
    sudo sysctl fs.file-max=2097152
    ulimit -n 65535
    
    # Connection tracking (if running NAT/firewall)
    cat /proc/sys/net/netfilter/nf_conntrack_count
    cat /proc/sys/net/netfilter/nf_conntrack_max
    # If count ≈ max → connections being dropped
    
    # TCP tuning for high-traffic servers
    sysctl net.core.somaxconn                   # listen backlog
    sysctl net.ipv4.tcp_max_syn_backlog         # SYN queue
    sysctl net.core.netdev_max_backlog          # NIC queue
    
    # Check for kernel softlockups or panics
    dmesg | grep -i "soft lockup|hard lockup|panic|bug"

    Historical Analysis with sar

    # Install if not present
    sudo apt install sysstat
    sudo systemctl enable sysstat
    
    # CPU history for today
    sar -u
    
    # Memory history
    sar -r
    
    # Disk IO history
    sar -d
    
    # Network history
    sar -n DEV
    
    # Load average history
    sar -q
    
    # For yesterday's data
    sar -u -f /var/log/sysstat/sa$(date -d "yesterday" +%d)
    
    # Compare today vs yesterday to find when degradation started
    # Look for the timestamp where metrics changed

    Quick Diagnostic Decision Tree

    Load Average > CPU Count

    CPU saturated → check top for process, perf top for function

    vmstat si/so > 0

    Swap thrashing → add RAM or kill memory hog, reduce swappiness

    iostat %util > 80%

    Disk bottleneck → check iotop for culprit, upgrade disk

    vmstat wa > 20%

    IO wait → disk or network IO blocking CPU, check D state processes

    vmstat st > 5%

    Steal time → VM host overcommitted, migrate or resize instance

    Everything Looks Normal

    Network issue or application-level problem → check ss, DNS, app logs

    Prevention

    Monitoring Setup

    • • Install node_exporter + Prometheus
    • • Enable sysstat for historical data
    • • Alert on load average, swap usage, disk util
    • • Track process count and FD usage
    • • Monitor OOM killer events

    System Tuning

    • • Set vm.swappiness=10 for servers
    • • Increase file descriptor limits
    • • Configure log rotation
    • • Set up automatic SMART disk monitoring
    • • Tune kernel network parameters for workload

    Emergency Diagnostic Script

    Copy this script onto the machine and run it. It produces a single comprehensive report covering CPU, memory, swap, disk, I/O, network, processes, and kernel health - with suggestions on what's likely wrong. NFS mounts are intentionally skipped in filesystem checks (and flagged separately) to avoid hangs on unresponsive NFS servers.

    slow-diag.shchmod +x slow-diag.sh && sudo ./slow-diag.sh
    #!/usr/bin/env bash
    # ==============================================================
    # slow-diag.sh - Emergency Ubuntu/Linux Diagnostic Script
    # Run as root: chmod +x slow-diag.sh && sudo ./slow-diag.sh
    # Produces a single report with findings and suggestions.
    # ==============================================================
    set -euo pipefail
    
    RED='\033[0;31m'
    YEL='\033[0;33m'
    GRN='\033[0;32m'
    CYN='\033[0;36m'
    RST='\033[0m'
    DIVIDER="================================================================"
    
    warn()  { echo -e "${YEL}⚠  $1${RST}"; }
    crit()  { echo -e "${RED}✖  $1${RST}"; }
    ok()    { echo -e "${GRN}✔  $1${RST}"; }
    info()  { echo -e "${CYN}ℹ  $1${RST}"; }
    header(){ echo -e "\n${CYN}${DIVIDER}\n   $1\n${DIVIDER}${RST}"; }
    
    SUGGESTIONS=()
    add_suggestion() { SUGGESTIONS+=("$1"); }
    
    # ------ SYSTEM INFO ------
    header "SYSTEM OVERVIEW"
    echo "Hostname : $(hostname)"
    echo "Kernel   : $(uname -r)"
    echo "Uptime   : $(uptime -p)"
    echo "Date     : $(date)"
    echo "CPUs     : $(nproc)"
    echo "Load Avg : $(cat /proc/loadavg)"
    
    NUM_CPUS=$(nproc)
    LOAD_1=$(awk '{print $1}' /proc/loadavg)
    if (( $(echo "$LOAD_1 > $NUM_CPUS * 2" | bc -l) )); then
      crit "Load average ($LOAD_1) is >2x CPU count ($NUM_CPUS) - severely overloaded"
      add_suggestion "CPU: Load average is critically high. Check top consumers with 'ps aux --sort=-%cpu | head'."
    elif (( $(echo "$LOAD_1 > $NUM_CPUS" | bc -l) )); then
      warn "Load average ($LOAD_1) exceeds CPU count ($NUM_CPUS) - CPU saturated"
      add_suggestion "CPU: Load average exceeds core count. Identify top processes and consider scaling or killing runaway jobs."
    else
      ok "Load average ($LOAD_1) is within bounds for $NUM_CPUS CPUs"
    fi
    
    # ------ CPU ------
    header "CPU ANALYSIS"
    echo "--- Top 10 CPU consumers ---"
    ps aux --sort=-%cpu | head -11
    
    if command -v mpstat &>/dev/null; then
      echo ""
      echo "--- Per-CPU utilization (3s sample) ---"
      mpstat -P ALL 1 3 | tail -$((NUM_CPUS + 3))
    fi
    
    # Check for steal time (VM environments)
    if [ -f /proc/stat ]; then
      STEAL=$(awk '/^cpu / {total=0; for(i=2;i<=NF;i++) total+=$i; print ($9/total)*100}' /proc/stat)
      if (( $(echo "$STEAL > 10" | bc -l) )); then
        crit "Steal time is ${STEAL}% - hypervisor is starving this VM"
        add_suggestion "CPU: High steal time (${STEAL}%). Your VM host is overcommitted. Migrate or resize the instance."
      elif (( $(echo "$STEAL > 3" | bc -l) )); then
        warn "Steal time is ${STEAL}% - some hypervisor contention"
      else
        ok "Steal time is ${STEAL}% - no VM contention"
      fi
    fi
    
    # ------ MEMORY ------
    header "MEMORY ANALYSIS"
    free -h
    echo ""
    
    MEM_TOTAL_KB=$(grep MemTotal /proc/meminfo | awk '{print $2}')
    MEM_AVAIL_KB=$(grep MemAvailable /proc/meminfo | awk '{print $2}')
    MEM_PCT_USED=$(( (MEM_TOTAL_KB - MEM_AVAIL_KB) * 100 / MEM_TOTAL_KB ))
    
    if (( MEM_PCT_USED > 95 )); then
      crit "Memory ${MEM_PCT_USED}% used - critically low available memory"
      add_suggestion "MEMORY: Only $((MEM_AVAIL_KB / 1024))MB available. Identify the hog: 'ps aux --sort=-%mem | head'. Consider adding RAM or killing processes."
    elif (( MEM_PCT_USED > 85 )); then
      warn "Memory ${MEM_PCT_USED}% used - getting tight"
      add_suggestion "MEMORY: ${MEM_PCT_USED}% used. Monitor closely and identify top consumers."
    else
      ok "Memory ${MEM_PCT_USED}% used - healthy"
    fi
    
    echo ""
    echo "--- Top 10 memory consumers ---"
    ps aux --sort=-%mem | head -11
    
    # ------ SWAP ------
    header "SWAP ANALYSIS"
    swapon --show 2>/dev/null || echo "(no swap configured)"
    
    SWAP_TOTAL=$(grep SwapTotal /proc/meminfo | awk '{print $2}')
    SWAP_FREE=$(grep SwapFree /proc/meminfo | awk '{print $2}')
    if (( SWAP_TOTAL > 0 )); then
      SWAP_USED=$((SWAP_TOTAL - SWAP_FREE))
      SWAP_PCT=$((SWAP_USED * 100 / SWAP_TOTAL))
      echo "Swap used: ${SWAP_PCT}% (${SWAP_USED}kB / ${SWAP_TOTAL}kB)"
    
      if (( SWAP_PCT > 50 )); then
        crit "Swap is ${SWAP_PCT}% used - likely thrashing"
        add_suggestion "SWAP: ${SWAP_PCT}% swap used. This kills latency. Add RAM, reduce swappiness (sysctl vm.swappiness=10), or kill the memory hog."
      elif (( SWAP_PCT > 10 )); then
        warn "Swap is ${SWAP_PCT}% used - some swapping occurring"
        add_suggestion "SWAP: ${SWAP_PCT}% used. Check 'vmstat 1 5' for si/so columns - if non-zero, active thrashing."
      else
        ok "Swap usage is low (${SWAP_PCT}%)"
      fi
    else
      info "No swap configured"
    fi
    
    SWAPPINESS=$(cat /proc/sys/vm/swappiness)
    if (( SWAPPINESS > 30 )); then
      warn "Swappiness is ${SWAPPINESS} (default 60) - consider lowering to 10 for servers"
      add_suggestion "SWAP: Swappiness is ${SWAPPINESS}. For servers, set to 10: sysctl vm.swappiness=10"
    fi
    
    # ------ DISK SPACE (skip NFS) ------
    header "DISK SPACE (NFS skipped)"
    echo "--- Local filesystems only ---"
    df -h -x nfs -x nfs4 -x cifs -x tmpfs -x devtmpfs -x overlay 2>/dev/null || df -h
    echo ""
    
    # Flag NFS mounts separately
    NFS_MOUNTS=$(mount | grep -E ' type (nfs|nfs4|cifs) ' || true)
    if [ -n "$NFS_MOUNTS" ]; then
      warn "NFS/CIFS mounts detected (skipped to avoid hangs on unresponsive servers):"
      echo "$NFS_MOUNTS" | while read -r line; do
        echo "   $line"
      done
      add_suggestion "NFS: Remote mounts detected. If the system hangs during df, an NFS server may be unresponsive. Check with 'mount | grep nfs' and consider lazy unmount (umount -l) for dead mounts."
    else
      ok "No NFS/CIFS mounts detected"
    fi
    
    # Check for full filesystems
    while IFS= read -r line; do
      usage=$(echo "$line" | awk '{print $5}' | tr -d '%')
      mount=$(echo "$line" | awk '{print $6}')
      if (( usage > 95 )); then
        crit "Filesystem $mount is ${usage}% full"
        add_suggestion "DISK: $mount is ${usage}% full. Find large files: find $mount -xdev -type f -size +100M -exec ls -lh {} + | sort -k5 -rh | head"
      elif (( usage > 85 )); then
        warn "Filesystem $mount is ${usage}% full"
      fi
    done < <(df -h -x nfs -x nfs4 -x cifs -x tmpfs -x devtmpfs -x overlay 2>/dev/null | tail -n +2)
    
    # ------ INODE USAGE ------
    echo ""
    echo "--- Inode usage ---"
    df -i -x nfs -x nfs4 -x cifs -x tmpfs -x devtmpfs -x overlay 2>/dev/null | tail -n +2 | while IFS= read -r line; do
      usage=$(echo "$line" | awk '{print $5}' | tr -d '%')
      mount=$(echo "$line" | awk '{print $6}')
      if (( usage > 90 )) 2>/dev/null; then
        crit "Inode usage on $mount is ${usage}%"
        add_suggestion "INODES: $mount is at ${usage}% inode usage. Find dirs with many small files: find $mount -xdev -type d -exec sh -c 'echo \"\$(find "\$1" -maxdepth 1 | wc -l) \$1\"' _ {} \; | sort -rn | head"
      fi
    done
    
    # ------ DISK I/O ------
    header "DISK I/O (3s sample)"
    if command -v iostat &>/dev/null; then
      iostat -xz 1 3 | tail -20
      
      # Check for saturated disks
      iostat -xz 1 1 | awk 'NR>6 && $NF+0 > 80 {print $1, $NF"%"}' | while read -r dev util; do
        crit "Disk $dev is at ${util} utilization"
        add_suggestion "DISK I/O: $dev is saturated (${util}). Check with 'iotop -o' to find the IO-heavy process."
      done
    else
      warn "iostat not available - install with: apt install sysstat"
      add_suggestion "TOOLING: Install sysstat for disk analysis: apt install sysstat"
    fi
    
    # ------ PROCESSES IN D STATE ------
    header "BLOCKED PROCESSES (D state = uninterruptible I/O wait)"
    D_PROCS=$(ps aux | awk '$8 ~ /D/ {print}' || true)
    D_COUNT=$(echo "$D_PROCS" | grep -c . || true)
    if (( D_COUNT > 0 )); then
      warn "${D_COUNT} process(es) in D state (blocked on I/O):"
      echo "$D_PROCS"
      add_suggestion "BLOCKED: ${D_COUNT} processes stuck in D state (uninterruptible I/O). These are waiting on disk or NFS. Check if a disk is dying (smartctl) or NFS server is down."
    else
      ok "No processes in D state"
    fi
    
    # ------ ZOMBIE PROCESSES ------
    Z_COUNT=$(ps aux | awk '$8 ~ /Z/' | grep -c . || true)
    if (( Z_COUNT > 5 )); then
      warn "${Z_COUNT} zombie processes detected"
      add_suggestion "ZOMBIES: ${Z_COUNT} zombie processes. Parent isn't reaping children. Find parent: ps -eo ppid,pid,stat,cmd | grep Z"
    elif (( Z_COUNT > 0 )); then
      info "${Z_COUNT} zombie process(es) - usually harmless in small numbers"
    else
      ok "No zombie processes"
    fi
    
    # ------ NETWORK ------
    header "NETWORK OVERVIEW"
    echo "--- Interface errors/drops ---"
    ip -s link show | grep -E "^[0-9]|RX:|TX:|errors" | head -30
    
    echo ""
    echo "--- TCP connection states ---"
    ss -s
    
    CLOSE_WAIT=$(ss -tan state close-wait | wc -l)
    TIME_WAIT=$(ss -tan state time-wait | wc -l)
    if (( CLOSE_WAIT > 50 )); then
      warn "${CLOSE_WAIT} connections in CLOSE_WAIT - application not closing connections"
      add_suggestion "NETWORK: ${CLOSE_WAIT} CLOSE_WAIT connections. An application isn't closing its sockets. Find it: ss -tanp state close-wait"
    fi
    if (( TIME_WAIT > 5000 )); then
      warn "${TIME_WAIT} connections in TIME_WAIT - high connection churn"
      add_suggestion "NETWORK: ${TIME_WAIT} TIME_WAIT connections. Consider enabling tcp_tw_reuse: sysctl net.ipv4.tcp_tw_reuse=1"
    fi
    
    # ------ FILE DESCRIPTORS ------
    header "FILE DESCRIPTORS"
    FD_INFO=$(cat /proc/sys/fs/file-nr)
    FD_USED=$(echo "$FD_INFO" | awk '{print $1}')
    FD_MAX=$(echo "$FD_INFO" | awk '{print $3}')
    FD_PCT=$((FD_USED * 100 / FD_MAX))
    echo "Used: $FD_USED / Max: $FD_MAX (${FD_PCT}%)"
    if (( FD_PCT > 80 )); then
      crit "File descriptor usage at ${FD_PCT}%"
      add_suggestion "FD: File descriptors at ${FD_PCT}%. Increase with: sysctl fs.file-max=2097152. Find culprit: ls /proc/*/fd 2>/dev/null | wc -l"
    else
      ok "File descriptor usage is healthy (${FD_PCT}%)"
    fi
    
    # ------ OOM KILLS ------
    header "OOM KILLER HISTORY"
    OOM_COUNT=$(dmesg 2>/dev/null | grep -ci "oom-kill\|killed process" || true)
    if (( OOM_COUNT > 0 )); then
      crit "${OOM_COUNT} OOM kill event(s) found in dmesg:"
      dmesg | grep -i "oom-kill\|killed process" | tail -5
      add_suggestion "OOM: The kernel has killed ${OOM_COUNT} process(es) due to memory pressure. Add RAM or identify the memory leak."
    else
      ok "No OOM kills in current boot"
    fi
    
    # Also check journal if available
    if command -v journalctl &>/dev/null; then
      JOURNAL_OOM=$(journalctl -k --since "7 days ago" 2>/dev/null | grep -ci "oom-kill\|killed process" || true)
      if (( JOURNAL_OOM > 0 )); then
        warn "${JOURNAL_OOM} OOM events in journal (last 7 days)"
      fi
    fi
    
    # ------ FAILED SERVICES ------
    header "FAILED SYSTEMD SERVICES"
    FAILED=$(systemctl list-units --state=failed --no-legend 2>/dev/null || true)
    if [ -n "$FAILED" ]; then
      warn "Failed services detected:"
      echo "$FAILED"
      add_suggestion "SERVICES: Failed systemd services detected. Check with: systemctl status <service> && journalctl -u <service> --since '1 hour ago'"
    else
      ok "No failed systemd services"
    fi
    
    # ------ DISK HEALTH (if smartctl available) ------
    if command -v smartctl &>/dev/null; then
      header "DISK HEALTH (SMART)"
      for disk in $(lsblk -dno NAME | grep -E '^sd|^nvme'); do
        SMART=$(smartctl -H /dev/$disk 2>/dev/null | grep -i "result\|status" || echo "unknown")
        REALLOC=$(smartctl -A /dev/$disk 2>/dev/null | grep Reallocated_Sector_Ct | awk '{print $10}' || true)
        echo "/dev/$disk: $SMART"
        if [ -n "$REALLOC" ] && (( REALLOC > 0 )); then
          crit "/dev/$disk has $REALLOC reallocated sectors - disk is failing"
          add_suggestion "DISK HEALTH: /dev/$disk has reallocated sectors. This disk is dying. Plan replacement ASAP."
        fi
      done
    else
      info "smartctl not available - install with: apt install smartmontools"
    fi
    
    # ------ KERNEL ISSUES ------
    header "KERNEL MESSAGES (errors/warnings)"
    dmesg 2>/dev/null | grep -iE "error|fail|panic|lockup|bug|readonly" | tail -10 || info "No kernel errors found"
    
    # ------ SUMMARY ------
    header "DIAGNOSTIC SUMMARY"
    echo ""
    if (( ${#SUGGESTIONS[@]} == 0 )); then
      ok "No obvious issues found. The problem may be application-level."
      echo "  → Check application logs and network latency to external services."
    else
      echo -e "${RED}Found ${#SUGGESTIONS[@]} issue(s) requiring attention:${RST}"
      echo ""
      for i in "${!SUGGESTIONS[@]}"; do
        echo -e "  ${YEL}$((i+1)).${RST} ${SUGGESTIONS[$i]}"
        echo ""
      done
    fi
    
    echo ""
    echo "Report generated at $(date) on $(hostname)"
    echo "$DIVIDER"