System Buffer Tuning - TCP and Network Performance Optimization

Tuning de amortiguación del sistema: El culto oculto detrás de "Problemas de red"

Resumen

Los ingenieros de red suelen encontrar situaciones en las que las ventanas TCP o el rendimiento de las aplicaciones son culpados de la infraestructura de red. Después de realizar extensas capturas de paquetes, tcpdumps y análisis de red, el verdadero cuello de botella se descubre a menudo: agotado NIC (Network Interface Card) o buffers de nivel OS en los sistemas cliente o servidor.

Este artículo proporciona configuraciones de amortiguación heredadas (circa 2009) y actuales (2025-2026) para Linux, Windows y macOS, junto con técnicas de diagnóstico para identificar el agotamiento del búfer antes de convertirse en un problema crítico.

Síntomas comunes de escape de amortiguación

  • TCP Zero Window eventos en capturas de paquetes
  • Altas tasas de retransmisión a pesar de la baja latencia de la red
  • Entrada de aplicación significativamente debajo del ancho de banda disponible
  • Degradación de rendimiento bajo carga que mejora cuando la carga disminuye
  • Rendimiento inconsistente en configuraciones de hardware similares
  • Errores de bolsillo o mensajes "Resource temporary unvailable"

Comprender el problema

The TCP Window Scaling Mechanism

TCP utiliza un mecanismo de control de flujo donde el receptor anuncia un "tamaño de ventana" indicando cuántos datos puede aceptar. Cuando los búferes del sistema se llenan, esta ventana se contrae a cero, obligando al remitente a esperar. Esto parece un problema de red, pero en realidad es un problema de recursos de acogida.

Donde los amortiguadores importan

  • Socket Buffers (SO SNDBUF/SO RCVBUF):
  • TCP Window Buffers:
  • Buffers de dispositivos de red:
  • Memoria de todo el sistema:

Comandos de diagnóstico

Diagnósticos de Linux

# Check current TCP buffer settings
sysctl net.ipv4.tcp_rmem
sysctl net.ipv4.tcp_wmem
sysctl net.core.rmem_max
sysctl net.core.wmem_max

# Check NIC ring buffer sizes
ethtool -g eth0

# Monitor socket buffer usage
ss -tm

# Check for TCP zero window events
tcpdump -i any 'tcp[tcpflags] & tcp-push != 0' -vv

# Check network statistics for buffer issues
netstat -s | grep -i "buffer\|queue\|drop"

Diagnósticos de Windows

# Check TCP parameters
netsh interface tcp show global

# View network adapter buffer settings
Get-NetAdapterAdvancedProperty -Name "Ethernet" | Where-Object {$_.DisplayName -like "*buffer*"}

# Monitor TCP statistics
netstat -s -p tcp

# Check receive window auto-tuning
netsh interface tcp show global | findstr "Receive Window"

MacOS Diagnósticos

# Check current buffer settings
sysctl kern.ipc.maxsockbuf
sysctl net.inet.tcp.sendspace
sysctl net.inet.tcp.recvspace

# View network statistics
netstat -s -p tcp

# Monitor socket buffers
netstat -an -p tcp

Linux Buffer Tuning

Configuración Legacy Linux (Circa 2009)

parámetro Legacy Value (2009) Descripción
net.core.rmem default 124928 (122KB) Default receive socket buffer size
net.core.rmem max 131071 (128KB) Maximum receive socket buffer size
net.core.wmem default 124928 (122KB) Default envía el tamaño del buffer de socket
net.core.wmem max 131071 (128KB) Máximo envío de toma de corriente tamaño
net.ipv4.tcp rmem 4096 87380 174760 TCP recibe amortiguación: min, default, max (in bytes)
net.ipv4.tcp wmem 4096 16384 131072 TCP enviar buffer: min, default, max (in bytes)
net.ipv4.tcp mem 196608 262144 393216 Páginas de memoria TCP: baja, presión, alta
net.core.netdev max backlog 1000 Paquetes máximos en cola de entrada
net.core.optmem max 10240 (10KB) Tamaño máximo de buffer auxiliar por toma

Ajustes actuales de Linux (2025-2026)

Parameter Valor recomendado actual Description
net.core.rmem_default 16777216 (16MB) Default receive socket buffer size
net.core.rmem_max 134217728 (128MB) Maximum receive socket buffer size
net.core.wmem_default 16777216 (16MB) Default send socket buffer size
net.core.wmem_max 134217728 (128MB) Maximum send socket buffer size
net.ipv4.tcp_rmem 4096 87380 134217728 TCP recibe amortiguación: min, default, max (128MB max)
net.ipv4.tcp_wmem 4096 65536 134217728 TCP enviar buffer: min, default, max (128MB max)
net.ipv4.tcp_mem 8388608 12582912 16777216 Páginas de memoria TCP: baja, presión, alta (sistema 64GB)
net.core.netdev_max_backlog 250000 Paquetes máximos en cola de entrada (10GbE+)
net.core.optmem_max 65536 (64KB) Maximum ancillary buffer size per socket
net.ipv4.tcp congestion control bbr Use el control de congestión BBR ( algoritmo de Google)
net.ipv4.tcp window scaling 1 Activar el escalado de ventanas TCP (RFC 1323)
net.ipv4.tcp timestamps 1 Habilitar las marcas TCP para una mejor estimación RTT
net.ipv4.tcp sack 1 Agradecimiento selectivo
net.ipv4.tcp no metrics save 1 Caché deshabilitado de métricas TCP

Aplicación de configuración de Linux

Añadir estos ajustes o crear un nuevo archivo :

# Network Buffer Tuning for High-Performance Applications
# Optimized for 10GbE+ networks with RTT up to 300ms

# Core socket buffer settings
net.core.rmem_default = 16777216
net.core.rmem_max = 134217728
net.core.wmem_default = 16777216
net.core.wmem_max = 134217728

# TCP buffer settings
net.ipv4.tcp_rmem = 4096 87380 134217728
net.ipv4.tcp_wmem = 4096 65536 134217728
net.ipv4.tcp_mem = 8388608 12582912 16777216

# Device buffer settings
net.core.netdev_max_backlog = 250000
net.core.netdev_budget = 50000
net.core.netdev_budget_usecs = 5000
net.core.optmem_max = 65536

# TCP optimizations
net.ipv4.tcp_congestion_control = bbr
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_sack = 1
net.ipv4.tcp_no_metrics_save = 1
net.ipv4.tcp_moderate_rcvbuf = 1

# Apply with: sysctl -p /etc/sysctl.d/99-network-tuning.conf

NIC Ring Buffer Tuning

# Check current ring buffer sizes
ethtool -g eth0

# Set maximum ring buffer sizes (adjust based on NIC capabilities)
ethtool -G eth0 rx 4096 tx 4096

# Make persistent by adding to /etc/network/interfaces or systemd service
Advertencia crítica - Consumo de memoria:
  • Memoria de conexión: Cada conexión puede utilizar hasta rmem max + wmem max (256MB con 128MB buffers)
  • Impacto total del sistema: 1.000 conexiones × 256MB = 256 GB de uso potencial
  • Estimación segura: Max concurrent connections × 256MB no debe exceder el 50% del sistema RAM
  • Ejemplo: Un servidor de 64 GB debe limitar las conexiones máximas a ~125 conexiones simultáneas de alto rendimiento con buffers 128MB
  • Recomendación para servidores con RAM de 0,116 GB: Reducir los búferes a 16-32MB max y ajustar tcp mem proporcionalmente

Windows Buffer Tuning

Configuración de Windows Legacy (Circa 2009 - Windows Vista/7/Server 2008)

Parameter Legacy Value (2009) Ubicación
TcpWindowSize 65535 (64KB) Registro: HKLM\System\CurrentControlSet\Services\Tcpip\Parameters
Tcp1323Opts 0 (discapacitados) Escalada de ventanas deshabilitada por defecto
DefaultReceiveWindow 8192 (8KB) Ventana por defecto
DefaultSendWindow 8192 (8KB) Default envía ventana
GlobalMaxTcpWindowSize 65535 (64KB) Tamaño máximo de la ventana TCP
TcpNumConnections 16777214 Conexión TCP máxima

Ajustes actuales de Windows (Windows 10/11/Server 2019-2025)

Windows moderno utiliza el función, que ajusta dinámicamente recibe amortiguadores basados en condiciones de red.

Característica Ajuste recomendado actual Description
Nivel de alimentación automática normal (o altamente experimental para 10GbE+) Ajuste dinámico de la ventana
Escalado de presión (RSS) habilitado Distribuir procesamiento de red a través de CPU
Chimney Offload automático (o desactivado en NIC modernos) Descarga de TCP a hardware NIC
NetDMA discapacitados Acceso directo a la memoria (dependido)
Parámetros mundiales TCP Ver comandos abajo Ajustes TCP a nivel de todo el sistema
Proveedor de Congestión CUBIC (o NewReno) algoritmo de control de congestión TCP

Mandos de configuración de Windows

# Check current auto-tuning level
netsh interface tcp show global

# Enable auto-tuning (normal mode - default for most scenarios)
netsh interface tcp set global autotuninglevel=normal

# For high-bandwidth, high-latency networks (10GbE+, data center environments)
netsh interface tcp set global autotuninglevel=experimental

# For conservative tuning (if experimental causes issues)
netsh interface tcp set global autotuninglevel=restricted

# For very conservative tuning (not recommended for high-performance networks)
netsh interface tcp set global autotuninglevel=highlyrestricted

# Enable CUBIC congestion provider (Windows Server 2022/Windows 11+ only)
netsh interface tcp set supplemental template=Internet congestionprovider=cubic

# Note: Windows 10 and Server 2019 use Compound TCP or NewReno by default
# CUBIC is not available on these older versions

# Enable Receive-Side Scaling (RSS)
netsh interface tcp set global rss=enabled

# Set chimney offload (automatic is recommended)
netsh interface tcp set global chimney=automatic

# Disable NetDMA (recommended for modern systems)
netsh interface tcp set global netdma=disabled

# Enable Direct Cache Access (if supported)
netsh interface tcp set global dca=enabled

# Enable ECN (Explicit Congestion Notification)
netsh interface tcp set global ecncapability=enabled

# Set initial congestion window to 10 (RFC 6928)
netsh interface tcp set global initialRto=3000

Configuración avanzada de amortiguación NIC (a través de Administrador de dispositivos o PowerShell)

# View current adapter settings
Get-NetAdapterAdvancedProperty -Name "Ethernet"

# Increase receive buffers (adjust based on NIC)
Set-NetAdapterAdvancedProperty -Name "Ethernet" -DisplayName "Receive Buffers" -DisplayValue 2048

# Increase transmit buffers
Set-NetAdapterAdvancedProperty -Name "Ethernet" -DisplayName "Transmit Buffers" -DisplayValue 2048

# Enable Jumbo Frames (if network supports it)
Set-NetAdapterAdvancedProperty -Name "Ethernet" -DisplayName "Jumbo Packet" -DisplayValue 9014

# Enable Large Send Offload (LSO)
Set-NetAdapterAdvancedProperty -Name "Ethernet" -DisplayName "Large Send Offload V2 (IPv4)" -DisplayValue Enabled
Set-NetAdapterAdvancedProperty -Name "Ethernet" -DisplayName "Large Send Offload V2 (IPv6)" -DisplayValue Enabled

Ajustes del registro (Advanced - Uso con precaución)

# These settings are typically NOT needed on Windows 10/11 due to auto-tuning
# Only modify if auto-tuning is disabled or problematic

# Registry path: HKLM\System\CurrentControlSet\Services\Tcpip\Parameters

# Maximum TCP window size (if auto-tuning disabled)
# TcpWindowSize = 16777216 (16MB) - REG_DWORD

# Enable window scaling (enabled by default on modern Windows)
# Tcp1323Opts = 3 - REG_DWORD

# Number of TCP Timed Wait Delay
# TcpTimedWaitDelay = 30 - REG_DWORD (default 240)
Advertencia:

macOS Buffer Tuning

Ajustes de macOS Legados (Circa 2009 - Mac OS X 10.5/10.6)

Parameter Legacy Value (2009) Description
kern.ipc.maxsockbuf 262144 (256KB) Tamaño máximo del búfer
net.inet.tcp.sendspace 32768 (32KB) Default TCP enviar buffer
net.inet.tcp.recvspace 32768 (32KB) TCP predeterminado recibe amortiguación
net.inet.tcp.autorcvbufmax 131072 (128KB) Máximo amortiguador automático recibir buffer
net.inet.tcp.autosndbufmax 131072 (128KB) Máximo buffer autofinanciado
net.inet.tcp.rfc1323 0 (disabled) Escalada de ventanas TCP

Ajustes de macOS actuales (macOS 12-15 Monterey a través de Sequoia)

Parameter Current Recommended Value Description
kern.ipc.maxsockbuf 8388608 (8MB) Maximum socket buffer size
net.inet.tcp.sendspace 131072 (128KB) Default TCP send buffer
net.inet.tcp.recvspace 131072 (128KB) Default TCP receive buffer
net.inet.tcp.autorcvbufmax 16777216 (16MB) Maximum auto-tuned receive buffer
net.inet.tcp.autosndbufmax 16777216 (16MB) Maximum auto-tuned send buffer
net.inet.tcp.rfc1323 1 (disponible) Activar el escalado de la ventana TCP
net.inet.tcp.sack 1 (enabled) Enable Selective Acknowledgment
net.inet.tcp.msdflt 1440 Tamaño máximo del segmento TCP predeterminado
net.inet.tcp.delayed ack 3 Delayed ACK behaviour

Aplicación de configuración de macOS

# Check current settings
sysctl kern.ipc.maxsockbuf
sysctl net.inet.tcp.sendspace
sysctl net.inet.tcp.recvspace
sysctl net.inet.tcp.autorcvbufmax
sysctl net.inet.tcp.autosndbufmax

# Apply settings temporarily (until reboot)
sudo sysctl -w kern.ipc.maxsockbuf=8388608
sudo sysctl -w net.inet.tcp.sendspace=131072
sudo sysctl -w net.inet.tcp.recvspace=131072
sudo sysctl -w net.inet.tcp.autorcvbufmax=16777216
sudo sysctl -w net.inet.tcp.autosndbufmax=16777216
sudo sysctl -w net.inet.tcp.rfc1323=1
sudo sysctl -w net.inet.tcp.sack=1

# Make settings persistent (create /etc/sysctl.conf)
sudo tee /etc/sysctl.conf <

Crear un Daemon de lanzamiento para configuraciones persistentes

# Create /Library/LaunchDaemons/com.local.sysctl.plist
sudo tee /Library/LaunchDaemons/com.local.sysctl.plist <Labelcom.local.sysctlProgramArguments/usr/sbin/sysctl-wkern.ipc.maxsockbuf=8388608RunAtLoad
EOF

sudo chmod 644 /Library/LaunchDaemons/com.local.sysctl.plist
sudo launchctl load /Library/LaunchDaemons/com.local.sysctl.plist
Advertencia:

Pruebas de rendimiento y validación

Herramientas para probar el rendimiento del amortiguador

iperf3 - Pruebas de rendimiento de red

# Server side
iperf3 -s

# Client side - test TCP throughput
iperf3 -c server_ip -t 60 -i 5 -w 16M

# Test with multiple parallel streams
iperf3 -c server_ip -P 10 -t 60

# Test UDP performance
iperf3 -c server_ip -u -b 1000M -t 60

tcpdump - Capture TCP Window Tamaños

# Capture and display TCP window sizes
tcpdump -i any -n 'tcp' -vv | grep -i window

# Save capture for Wireshark analysis
tcpdump -i any -w /tmp/capture.pcap 'tcp port 443'

Wireshark Analysis

Busque estos indicadores de problemas de amortiguación:

  • TCP Zero Window messages
  • Paquetes de actualización de la ventana TCP
  • TCP Window Notificaciones completas
  • Altas tasas de retransmisión con bajo RTT

Supervisión del sistema

# Linux - Monitor network buffer statistics
watch -n 1 'cat /proc/net/sockstat'
watch -n 1 'ss -tm | grep -i mem'

# Check for drops
netstat -s | grep -i drop

# Windows - Monitor TCP statistics
netstat -e 1

# macOS - Monitor network statistics
netstat -s -p tcp

Cálculo de producto de ancho de banda (BDP)

Para determinar los tamaños óptimos de amortiguación para su red, calcule el producto de ancho de banda:

BDP = Bandwidth (bits/sec) × RTT (seconds)

Example for 10 Gigabit Ethernet with 50ms RTT:
BDP = 10,000,000,000 × 0.050 = 500,000,000 bits = 62.5 MB

Buffer Size = BDP × 2 (for bidirectional traffic and headroom)
Buffer Size = 62.5 MB × 2 = 125 MB

This is why modern settings recommend 128MB maximum buffers.

Recomendaciones específicas sobre el volumen de trabajo

Tipo de carga de trabajo Tamaño de Buffer recomendado Parámetros clave
Servidor Web (Low latency) 4 a 16 MB Búferes inferiores, más conexiones, respuesta rápida
Servidor de base 16 a 32 MB Buffers moderados, rendimiento consistente
Transferencia de archivos / Copia de seguridad 64-128 MB Buffers máximos, alta prioridad de rendimiento
Flujo de vídeo 32-64 MB Grandes amortiguadores, tasa de entrega consistente
HPC / Centro de Datos 128-256 MB Buffers máximos, control de congestión especializado
Wireless / Mobile 2-8 MB Buffers conservadores, manejo de latencia variable

Errores comunes y Pitfalls

Errores para evitar

  • Over-buffering:
  • Ignorando las limitaciones de memoria:
  • Disabling auto-tuning sin razón:
  • No probar después de cambios:
  • Olvidando los búferes NIC:
  • Ajustes inconsistentes:
  • Ignorar el control de la congestión:

Solución de problemas flujo de trabajo

  1. Establecer la base de referencia:
  2. Paquetes de captura:
  3. Estadísticas del sistema de verificación:
  4. Cálculo BDP:
  5. Aplicar cambios incrementales:
  6. Prueba y validación:
  7. Supervisar con el tiempo:

Referencias y lectura posterior

  • RFC 1323 - TCP Extensiones for High Performance (Window Scaling)
  • RFC 2018 - Opciones de reconocimiento selectivo TCP
  • RFC 6928 - Aumentar la ventana inicial de TCP
  • RFC 8312 - CUBIC Congestion Control Algorithm
  • BBR Congestion Control (Google) - https://research.google/pubs/pub45646/
  • Linux Kernel Documentation - networking/ip-sysctl.txt
  • Windows TCP/IP Performance Tuning Guide (Microsoft)
  • ESnet Network Tuning Guide - https://fasterdata.es.net/

Conclusión

El agotamiento de los amortiguadores es una causa común de problemas de rendimiento que parecen estar relacionados con la red. Al comprender la evolución del tamaño del búfer desde los límites 128KB de 2009 hasta las capacidades 128MB de hoy, los ingenieros de red pueden identificar y resolver rápidamente estos problemas.

Escapadas clave:

  • Los sistemas modernos necesitan mayores amortiguadores que las configuraciones heredadas (2009)
  • Calcula siempre BDP para sus condiciones de red específicas
  • Utilice las funciones de ajuste automático de OS cuando esté disponible (Windows, Linux moderno)
  • Monitor y prueba para validar los cambios
  • Considerar las necesidades específicas de la carga de trabajo al ajustarse

Recuerde: Un "problema de red" revelado por el análisis de paquetes para mostrar las ventanas TCP cero es en realidad un problema de recursos del sistema anfitrión. Con una adecuada afinación de amortiguadores, puede eliminar estos falsos diagnósticos y lograr un rendimiento óptimo.


Última actualización: 2 de febrero de 2026

Author: Baud9600 Technical Team