Skip to content
Back to Blog
Performance10 min read

Tuning Nginx for Performance: Workers, Gzip, and Buffers

Learn how to optimize Nginx performance by configuring worker processes, enabling gzip compression, and tuning buffer sizes for better throughput and lower latency.

Written by Abdul AbrorTechnical Hosting Support Engineer
Tuning Nginx for Performance: Workers, Gzip, and Buffers
On this page

Nginx has earned its reputation as a high-performance web server and reverse proxy, but out-of-the-box configurations rarely deliver optimal performance for your specific workload. The good news is that a handful of directives in nginx.conf have outsized impact on throughput and latency. This guide walks you through the most important tuning knobs: worker process configuration, gzip compression, and buffer settings.

Understanding Nginx Architecture

Before diving into configuration, it helps to understand how Nginx handles requests. Unlike traditional process-per-connection servers, Nginx uses an event-driven, asynchronous architecture. A small number of worker processes handle thousands of concurrent connections efficiently through non-blocking I/O and an event loop.

This architecture means that tuning is about matching worker capacity to your CPU resources and optimizing how Nginx buffers and compresses data flowing through those workers.

Worker Process Configuration

Worker processes are the heart of Nginx performance. Each worker runs independently and handles multiple connections simultaneously.

worker_processes

The worker_processes directive controls how many worker processes Nginx spawns. The general rule is one worker per CPU core.

worker_processes auto;

The auto value tells Nginx to detect available CPU cores and create one worker per core. This is the recommended starting point for most servers. Alternatively, you can specify an exact number:

worker_processes 4;

More workers than cores creates unnecessary context switching. Fewer workers than cores leaves CPU capacity unused. Start with auto and only adjust if you have specific isolation or resource allocation requirements.

worker_connections

Each worker process can handle a limited number of simultaneous connections, controlled by worker_connections:

events {
    worker_connections 1024;
}

The default is often conservative. Modern servers can typically handle much higher values. A reasonable production setting ranges from 2048 to 8192 depending on your use case:

events {
    worker_connections 4096;
}

Your theoretical maximum concurrent connections is worker_processes × worker_connections. However, when Nginx acts as a reverse proxy, each client connection may require an additional upstream connection, effectively halving your capacity.

Check your system's file descriptor limit before increasing worker_connections significantly:

ulimit -n

If the limit is too low, increase it in /etc/security/limits.conf or your systemd service file.

worker_cpu_affinity

For maximum performance on multi-core systems, pin worker processes to specific CPU cores:

worker_cpu_affinity auto;

This prevents workers from migrating between cores, reducing cache misses and improving CPU cache efficiency. On older Nginx versions without auto, you can specify a bitmask manually, but auto is simpler and handles most scenarios well.

worker_rlimit_nofile

This directive sets the maximum number of open files for worker processes, independent of system-wide limits:

worker_rlimit_nofile 65535;

Set this to at least twice your worker_connections value to account for client connections, upstream connections, and file operations. This ensures workers never hit file descriptor limits during peak load.

Gzip Compression

Enabling gzip compression reduces bandwidth usage and speeds up page loads, especially for text-based content like HTML, CSS, and JavaScript. The tradeoff is CPU time spent compressing responses.

Basic Gzip Configuration

Start with these essential directives:

gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/json
    application/javascript
    application/xml+rss
    application/atom+xml
    image/svg+xml;

Let's break down each directive:

  • gzip on enables compression
  • gzip_vary on adds the Vary: Accept-Encoding header, ensuring proxies cache compressed and uncompressed versions separately
  • gzip_proxied any compresses responses even when they come from upstream proxies
  • gzip_comp_level 6 sets compression level (1-9). Level 6 offers good compression with reasonable CPU usage
  • gzip_types specifies which MIME types to compress. Never compress already-compressed formats like images or videos

Gzip Compression Level

The compression level trades CPU time for smaller files. Level 1 is fastest with least compression; level 9 is slowest with maximum compression. In practice, levels above 6 offer diminishing returns:

  • Levels 1-3: Fast, minimal compression, good for CPU-constrained servers
  • Level 6: Balanced default, recommended for most use cases
  • Levels 7-9: Marginal size reduction, significantly higher CPU cost

For high-traffic sites, test different levels under realistic load. Monitor CPU usage and response times to find the sweet spot.

gzip_min_length

Avoid compressing tiny responses where overhead exceeds benefit:

gzip_min_length 256;

This skips compression for responses smaller than 256 bytes. Files this small often grow after compression due to gzip headers and metadata.

gzip_buffers

Control memory allocation for compression:

gzip_buffers 16 8k;

This allocates 16 buffers of 8KB each for compression operations. The default is usually fine, but if you serve large files, you might increase buffer size to reduce memory allocations.

Buffer Configuration

Buffers control how Nginx stores request and response data in memory. Proper buffer sizing reduces disk I/O and prevents unnecessary temporary file creation.

Client Request Buffers

client_body_buffer_size controls how much of the request body Nginx stores in memory:

client_body_buffer_size 16k;

If the request body exceeds this size, Nginx writes the excess to disk. For APIs receiving JSON payloads or file upload endpoints, increase this value to avoid disk writes:

client_body_buffer_size 128k;

client_header_buffer_size sets the buffer for request headers:

client_header_buffer_size 1k;

Most headers fit in 1KB. For requests with unusually large headers (many cookies, long URLs), use large_client_header_buffers:

large_client_header_buffers 4 8k;

This allocates up to 4 buffers of 8KB for oversized headers.

Proxy Buffers

When Nginx acts as a reverse proxy, proxy buffers control how responses from upstream servers are handled.

proxy_buffering should typically remain enabled:

proxy_buffering on;

Buffering allows Nginx to receive the full upstream response quickly and then send it to slow clients at their own pace, freeing the upstream connection sooner.

proxy_buffer_size sets the buffer for response headers from upstream:

proxy_buffer_size 4k;

This buffer holds only the headers, not the body. Most applications work fine with 4KB.

proxy_buffers controls body buffering:

proxy_buffers 8 4k;

This allocates 8 buffers of 4KB each. For larger responses, increase both the count and size:

proxy_buffers 16 8k;

proxy_busy_buffers_size limits how much buffered data can be sent to the client while Nginx is still receiving from upstream:

proxy_busy_buffers_size 8k;

Set this to roughly twice your proxy_buffer_size to allow Nginx to start sending data before the full response arrives.

FastCGI Buffers

For PHP applications using FastCGI, similar buffering rules apply:

fastcgi_buffering on;
fastcgi_buffer_size 4k;
fastcgi_buffers 8 4k;
fastcgi_busy_buffers_size 8k;

If you see upstream sent too big header errors, increase fastcgi_buffer_size and fastcgi_buffers.

Timeouts

While not strictly performance tuning, timeout configuration prevents workers from being tied up by slow or stalled connections.

client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
  • client_body_timeout and client_header_timeout prevent slow clients from holding connections indefinitely
  • keepalive_timeout allows connection reuse but closes idle connections promptly
  • send_timeout terminates connections if the client stops reading data

Adjust these based on your application. API servers handling mobile clients over poor networks might need longer timeouts. Static asset servers can use shorter values.

Upstream Keepalive

For reverse proxy configurations, maintaining persistent connections to upstream servers dramatically reduces latency:

upstream backend {
    server 127.0.0.1:8080;
    keepalive 32;
}

server {
    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

The keepalive directive keeps up to 32 idle connections per worker to upstream servers. This eliminates TCP handshake and connection setup overhead for subsequent requests.

Putting It All Together

Here's a complete example combining these optimizations:

user nginx;
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 4096;
    use epoll;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_min_length 256;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml+rss
        application/atom+xml
        image/svg+xml;

    # Buffer configuration
    client_body_buffer_size 128k;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 8k;

    proxy_buffering on;
    proxy_buffer_size 4k;
    proxy_buffers 16 8k;
    proxy_busy_buffers_size 16k;

    # Timeouts
    client_body_timeout 12;
    client_header_timeout 12;
    keepalive_timeout 15;
    send_timeout 10;

    # Other performance settings
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    include /etc/nginx/conf.d/*.conf;
}

Testing and Monitoring

After making changes, always test under realistic load. Use tools like ab (ApacheBench), wrk, or siege to simulate concurrent requests:

wrk -t12 -c400 -d30s http://your-site.com/

Monitor key metrics:

  • Request throughput (requests per second)
  • Response latency (p50, p95, p99)
  • CPU utilization per worker
  • Memory usage
  • Active connections

Check Nginx's stub_status module for real-time statistics:

location /nginx_status {
    stub_status;
    allow 127.0.0.1;
    deny all;
}

Compare before and after metrics to validate your changes. Make one category of changes at a time so you can identify what helps and what doesn't.

Conclusion

Nginx performance tuning doesn't require exotic configurations or dozens of obscure directives. Focus on the fundamentals: match worker processes to CPU cores, enable gzip compression for text content, and size buffers appropriately for your workload. These three areas deliver the most measurable improvements in throughput and latency.

Start with the complete example configuration above, test under load, and adjust based on your specific traffic patterns and resource constraints. Monitor your metrics before and after changes to validate improvements. With these core optimizations in place, your Nginx server will handle significantly more traffic with lower latency and better resource efficiency.

FAQ

How many worker processes should I use?

Start with worker_processes auto to match your CPU core count. This handles most scenarios optimally. Only deviate if you need specific CPU isolation or resource allocation.

Should I disable gzip to save CPU?

Rarely. Gzip typically reduces bandwidth by 60-80% for text content, which often saves more time in network transfer than it costs in CPU. Only disable gzip if CPU is your bottleneck and bandwidth is abundant.

What's the difference between proxy_buffer_size and proxy_buffers?

proxy_buffer_size handles only the response headers from upstream. proxy_buffers handles the response body. Keep proxy_buffer_size small (4k is typical) and scale proxy_buffers based on your response sizes.

How do I know if my buffers are too small?

Check your error logs for messages like "upstream sent too big header" or "an upstream response is buffered to a temporary file". These indicate buffer exhaustion. Increase the relevant buffer sizes incrementally.

Can I set worker_connections higher than my file descriptor limit?

No. Nginx will fail to start if worker_connections exceeds worker_rlimit_nofile or the system limit. Always check ulimit -n and ensure your limits accommodate your connection target.