Skip to content
masdzub.com
~/articles/nginx — one from the notebook

Tuning Nginx Worker Processes and Connection Limits for Production

Configure Nginx worker_processes and worker_connections, align OS limits, validate changes, and resolve common file descriptor errors in production.

masdzub@website:~$ cat ~/articles/tuning-nginx-worker-processes-and-connection-limits.aspx.md
# 1 file · 19 min read · topic: nginx · status: published

Introduction

Tuning Nginx worker processes and connection limits means aligning worker_processes, worker_connections, and file descriptor ceilings with your CPU cores and operating system constraints so the server can handle expected concurrency without dropping connections or exhausting resources. A correct configuration starts by setting worker_processes to match available CPU cores (often auto), sizing worker_connections based on traffic patterns, raising worker_rlimit_nofile, and synchronizing those values with kernel and systemd limits. The sections below walk through inspection, configuration, validation, workload-specific sizing, monitoring, and troubleshooting with concrete commands and production-ready examples.

How Nginx Handles Connections

Nginx uses an event-driven architecture built around a master process and one or more worker processes. The master process reads the configuration, binds to network ports, and manages worker lifecycles. Worker processes handle all client traffic. Each worker runs a non-blocking event loop that can multiplex many connections on a single thread, which is why a small number of workers can serve thousands of concurrent clients when the system is tuned correctly.

Every connection consumes file descriptors. A client requesting a static file typically uses one file descriptor for the client socket and, depending on caching behavior, may briefly use another for the file on disk. When Nginx operates as a reverse proxy, a single client request often consumes at least two file descriptors: one for the downstream connection from the client and one for the upstream connection to the application server. Keepalive connections increase this count because idle sockets remain open between requests.

This connection model explains why tuning cannot stop at the Nginx configuration file. The effective concurrency limit is the lowest ceiling across several layers: the worker_connections directive, the per-worker file descriptor limit set by worker_rlimit_nofile, the per-process limits enforced by the operating system, and system-wide kernel limits. If any one of these layers is too low, Nginx will reject or fail to establish connections even when other values appear generous.

Inspecting System Resources Before Tuning

Before changing any configuration, collect baseline data about the host. Guessing values without knowing the CPU count, current limits, and active Nginx settings often leads to configurations that fail validation or silently cap throughput.

Start by identifying the number of processing units available to Nginx:

Terminal window
nproc
lscpu | grep -E '^CPU\(s\)|^Thread|^Core|^Socket'
grep -c ^processor /proc/cpuinfo

On a virtual machine, nproc reports the number of logical CPUs assigned to the guest. On bare metal, lscpu helps distinguish between physical cores and hardware threads, which matters when deciding whether to pin workers to specific CPUs.

Next, inspect file descriptor limits at the shell, kernel, and process levels:

Terminal window
ulimit -n
cat /proc/sys/fs/file-max
sysctl fs.nr_open

The ulimit -n command shows the soft limit for the current shell session. The fs.file-max value is the system-wide maximum number of file handles the kernel will allocate. The fs.nr_open value defines the upper bound for per-process limits that can be set with setrlimit. A common production mistake is raising Nginx limits above fs.nr_open, which causes the new limit to be rejected.

Review the running Nginx binary and its effective configuration:

Terminal window
nginx -v
nginx -V 2>&1 | tr ' ' '\n'
nginx -T

The nginx -T command dumps the full configuration, including included files. This is more reliable than reading nginx.conf in isolation because production setups frequently split configuration across /etc/nginx/conf.d/*.conf, /etc/nginx/sites-enabled/*, or custom include paths. Confirm the current values of worker_processes, worker_connections, and worker_rlimit_nofile before making changes so you can compare behavior after a reload.

Finally, check the limits applied to running worker processes:

Terminal window
pidof nginx
cat /proc/$(pidof nginx | awk '{print $1}')/limits | grep "Max open files"

If multiple worker PIDs are returned, inspect one of them. This output shows the actual soft and hard file descriptor limits in effect for the process, which may differ from what you expect based on configuration files alone.

Configuring worker_processes

The worker_processes directive controls how many worker processes Nginx spawns. It belongs in the main context of nginx.conf, outside the events and http blocks.

/etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 4096;
}

Setting worker_processes auto; instructs Nginx to detect the number of available CPU cores and start one worker per core. This is the right default for most servers because it maps worker parallelism to hardware without requiring manual updates when the machine size changes. On Nginx 1.3.8 and later, auto is widely supported and stable in production distributions such as Ubuntu 22.04 (Nginx 1.18 in the default repository, newer in nginx.org packages) and RHEL 9 (Nginx 1.20+).

A fixed value is appropriate when you need explicit control. For example, on a 16-core host where Nginx shares CPU time with a database or application runtime, you might allocate only 4 or 8 workers to Nginx:

worker_processes 4;

You can also pin workers to specific CPU cores using worker_cpu_affinity. This can reduce cache misses on busy systems, but it requires careful maintenance. If the number of affinity masks does not match worker_processes, or if the host’s CPU topology changes (common in virtualized environments), the configuration can behave differently than intended.

worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;

Running more workers than available cores rarely improves throughput. Each worker has its own memory footprint and event loop overhead. Extra workers increase context switching and can make latency less predictable under load. Running too few workers leaves CPU capacity unused, especially when TLS termination, compression, or complex rewrite rules consume significant CPU time. The practical goal is to keep workers busy without forcing the scheduler to juggle unnecessary processes.

Configuring worker_connections and worker_rlimit_nofile

The worker_connections directive sets the maximum number of simultaneous connections that each worker process can open. It is defined inside the events block. The worker_rlimit_nofile directive sets the limit on the maximum number of open file descriptors for worker processes and is defined in the main context.

worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 8192;
multi_accept on;
}

The theoretical maximum number of concurrent client connections is:

max_clients = worker_processes * worker_connections

This formula is a ceiling, not a guarantee. For a static file server, one client connection may map closely to one worker connection slot. For a reverse proxy, each client request can require an upstream connection as well, so the effective number of simultaneous clients is often closer to:

max_proxy_clients ≈ (worker_processes * worker_connections) / 2

If upstream keepalive is enabled, idle upstream connections also occupy slots, which further reduces the number of new clients that can be served concurrently. Sizing must account for these patterns rather than relying on the raw multiplication alone.

The worker_rlimit_nofile value should be high enough to cover all file descriptors a worker may need: client sockets, upstream sockets, log files, cached file handles, and any temporary files. A safe practice is to set it at least equal to worker_connections, and often higher when proxying traffic. For example, if worker_connections is 8192, setting worker_rlimit_nofile to 16384 or 65535 provides headroom.

The multi_accept directive controls whether a worker accepts all new connections at once when awakened, or accepts them one by one. Enabling multi_accept on; can improve throughput under sudden bursts of new connections, but it may also cause uneven load distribution across workers. On systems with steady traffic, the default behavior (multi_accept off;) is often easier to reason about. Test this setting under realistic load rather than assuming it will help.

OS-Level Limits: File Descriptors and Network Tuning

Nginx cannot use more file descriptors than the operating system allows. Even a correct nginx.conf will fail in practice if kernel or service manager limits are lower than the requested values.

Kernel and Shell Limits

To raise system-wide and per-process ceilings, update kernel parameters. Create or edit a sysctl configuration file:

Terminal window
sudo tee /etc/sysctl.d/99-nginx.conf > /dev/null <<'EOF'
fs.file-max = 2097152
fs.nr_open = 2097152
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.ip_local_port_range = 10240 65535
EOF
sudo sysctl --system

The fs.file-max parameter increases the total number of file handles available to the kernel. The net.core.somaxconn parameter raises the maximum length of the listen backlog queue; if this value is too low, bursts of incoming connections can be dropped before Nginx accepts them. The net.ipv4.ip_local_port_range setting expands the ephemeral port range, which is important for reverse proxies that open many outbound connections to upstream servers.

You can also adjust the listening socket backlog in Nginx to match the kernel setting:

server {
listen 80 backlog=65535 reuseport;
server_name example.com;
}

The reuseport option (available on Linux 3.9+ with Nginx 1.9.1+) allows multiple worker processes to accept connections from separate listen sockets, reducing lock contention under high connection rates. It is useful for high-traffic edge servers, but it changes connection distribution behavior and should be evaluated in staging.

Per-User Limits with limits.conf

On systems that rely on PAM limits, you can raise limits for the Nginx user in /etc/security/limits.conf or in a dedicated file under /etc/security/limits.d/:

/etc/security/limits.d/nginx.conf
www-data soft nofile 65535
www-data hard nofile 65535
nginx soft nofile 65535
nginx hard nofile 65535

The correct user depends on your distribution and configuration (www-data on Debian/Ubuntu, nginx on RHEL-based systems). These settings apply to user sessions and services that honor PAM limits. Many modern systemd-managed services do not inherit them as you might expect, so a systemd override is often required.

Systemd Service Limits

For Nginx managed by systemd, set the file descriptor limit in a service drop-in:

Terminal window
sudo systemctl edit nginx

Add the following content:

[Service]
LimitNOFILE=65535

Then reload the systemd daemon and restart Nginx:

Terminal window
sudo systemctl daemon-reload
sudo systemctl restart nginx

A reload (systemctl reload nginx) applies Nginx configuration changes but does not change the service’s process limits if only the unit file was modified. When adjusting LimitNOFILE, a restart is the reliable way to ensure workers inherit the new ceiling. Plan restarts during a maintenance window or use a load balancer to drain traffic if uptime requirements are strict.

Applying Changes and Validating Configuration

Configuration changes should follow a consistent validation sequence. Applying untested changes directly on a busy server risks failed reloads or degraded behavior that is hard to diagnose under pressure.

First, test the Nginx configuration syntax and basic integrity:

Terminal window
sudo nginx -t

A successful test prints messages similar to:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

If the test fails, fix the reported file and line number before proceeding. After a successful test, reload Nginx to apply changes without dropping existing connections:

Terminal window
sudo systemctl reload nginx

Confirm that the service is active and that workers were respawned as expected:

Terminal window
sudo systemctl status nginx --no-pager
ps -ef | grep '[n]ginx'

Verify that the new file descriptor limits are in effect on a worker process:

Terminal window
PID=$(pidof nginx | awk '{print $1}')
cat /proc/$PID/limits | grep "Max open files"

The output should reflect the values set via worker_rlimit_nofile and LimitNOFILE. If the reported soft limit is still 1024 or another low value, the service manager override or kernel ceiling is likely constraining the process.

Inspect active connection state at the socket level:

Terminal window
ss -s
ss -Htan state established '( sport = :80 or sport = :443 )' | wc -l

The ss -s summary provides a quick view of TCP socket usage. Comparing this with your configured capacity helps you determine whether the new limits provide adequate headroom during peak traffic.

Sizing for Different Workloads

There is no single set of values that fits every Nginx deployment. The correct numbers depend on whether Nginx serves static assets, proxies to an application, or handles a mix of both. The table below illustrates typical starting points for a server with 4 CPU cores. These values are examples to adapt, not universal prescriptions.

Workload profileworker_processesworker_connectionsworker_rlimit_nofileNotes
Static file serverauto (4)40968192Most connections are short-lived; file cache and disk I/O behavior matter.
Reverse proxy (HTTP)auto (4)819265535Each client may require an upstream socket; account for keepalive.
TLS termination proxyauto (4)409632768TLS handshakes increase CPU cost per connection; prioritize CPU headroom.
High-concurrency API gateway4 to 8 (based on testing)1638465535Requires matching kernel, systemd, and upstream pool limits.

Static File Serving

For static assets, Nginx often closes upstream-like complexity and serves responses directly from disk or cache. A worker_connections value of 4096 per worker on a 4-core machine yields a theoretical ceiling of 16,384 concurrent connections. In practice, bandwidth, disk latency, and sendfile behavior will limit throughput before the connection ceiling becomes the primary bottleneck. Monitor memory usage because each connection consumes state, and very high connection counts can increase memory pressure.

Reverse Proxying

Reverse proxy deployments require more careful accounting. If 8,000 clients maintain active connections and each request is forwarded to an upstream application, Nginx may need roughly 16,000 file descriptors at the same time, plus descriptors for logs and other files. Upstream keepalive reduces connection churn but keeps sockets open:

upstream app_backend {
server 10.0.0.10:8080;
server 10.0.0.11:8080;
keepalive 256;
}
server {
listen 443 ssl;
server_name api.example.com;
location / {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://app_backend;
}
}

The keepalive 256 directive defines the maximum number of idle keepalive connections to upstream servers preserved in each worker process cache. This improves upstream connection reuse but consumes connection slots even when idle. When raising worker_connections, review upstream server limits as well; Nginx can only open as many upstream connections as the backend and the network path can sustain.

Mixed Workloads

Servers that handle both static content and proxied application traffic sit between these profiles. In these cases, observe the ratio of request types from access logs and size for the more demanding path. If proxied API calls dominate peak concurrency, tune as a reverse proxy. If large static downloads dominate connection duration, account for long-lived sockets that occupy worker slots for extended periods.

Monitoring Connections Under Load

Tuning is incomplete without visibility into how Nginx behaves under real traffic. Monitoring confirms whether the new limits are sufficient and reveals symptoms of exhaustion before they become outages.

Enabling stub_status

The ngx_http_stub_status_module provides a simple endpoint for active connection metrics. Ensure the module is available in your build (nginx -V 2>&1 | grep -o with-http_stub_status_module) and configure a restricted location:

server {
listen 127.0.0.1:8080;
server_name localhost;
location /nginx_status {
stub_status;
allow 127.0.0.1;
deny all;
}
}

After reloading, query the endpoint:

Terminal window
curl -s http://127.0.0.1:8080/nginx_status

Typical output looks like this:

Active connections: 291
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106

The Active connections value includes all current connections, including waiting keepalive connections. Reading indicates connections where Nginx is reading the request header, Writing indicates responses being sent, and Waiting indicates idle keepalive connections. A consistently high Waiting count relative to total capacity may suggest that keepalive timeouts are too generous for your traffic pattern, tying up slots that could serve new clients.

Observing Errors and Socket Pressure

Watch error logs during and after configuration changes:

Terminal window
sudo tail -f /var/log/nginx/error.log

Correlate log entries with system-level metrics:

Terminal window
ss -tan | awk '{print $1}' | sort | uniq -c | sort -rn
cat /proc/sys/fs/file-nr

The /proc/sys/fs/file-nr file reports allocated file handles, unused allocated handles, and the system maximum. If allocated handles approach fs.file-max, the host is nearing a system-wide limit that affects all processes, not just Nginx.

For load testing in a staging environment, tools such as wrk or ApacheBench can help validate behavior under controlled concurrency:

Terminal window
wrk -t4 -c800 -d30s https://staging.example.com/

Run these tests against non-production systems or carefully controlled environments. Synthetic tests can reveal configuration ceilings, but they do not perfectly reproduce production traffic mixes, TLS session reuse patterns, or upstream latency.

Troubleshooting Common Errors

When worker or connection tuning is incorrect, Nginx usually reports clear errors in the error log. The messages below are common in production and map to specific layers of the configuration stack.

worker_connections exceed open file resource limit

Error message:

[alert] 12345#12345: 10000 worker_connections exceed open file resource limit: 1024

This alert appears at startup or reload when worker_connections is higher than the file descriptor limit available to the worker. The process is effectively capped at the lower value. Fix it by raising worker_rlimit_nofile in nginx.conf, increasing LimitNOFILE in the systemd service, and ensuring kernel ceilings (fs.nr_open) are high enough. After updating the systemd unit, run daemon-reload and restart Nginx, then verify with /proc/<pid>/limits.

accept4() failed (24: Too many open files)

Error message:

[crit] 12346#12346: *889012 accept4() failed (24: Too many open files)

Error code 24 (EMFILE) means the worker process reached its per-process open file limit and cannot accept a new client socket. This can happen even when worker_connections looks reasonable if the worker also holds many upstream sockets, log descriptors, or cached file handles. Check current open descriptors for the worker:

Terminal window
PID=$(pidof nginx | awk '{print $1}')
ls /proc/$PID/fd | wc -l
cat /proc/$PID/limits | grep "Max open files"

If the count is near the limit, increase worker_rlimit_nofile and the corresponding OS limits. Also investigate whether keepalive settings or slow upstreams are causing connections to accumulate.

socket() failed (24: Too many open files) while connecting to upstream

Error message:

[crit] 12347#12347: *889045 socket() failed (24: Too many open files) while connecting to upstream, client: 203.0.113.50, server: api.example.com, request: "GET /v1/orders HTTP/1.1", upstream: "http://10.0.0.10:8080/v1/orders"

This variant indicates the worker cannot create a new socket to the upstream server. The client-side connection may already be established, but Nginx fails before completing the proxy request. The root cause is usually the same file descriptor exhaustion, but the impact is more visible as upstream failures. In addition to raising descriptor limits, review upstream keepalive pool sizing and application latency. If backends respond slowly, both client and upstream sockets remain open longer, multiplying descriptor usage.

worker_connections are not enough

Error message:

[warn] 12348#12348: 1024 worker_connections are not enough

This warning means a worker attempted to handle more connections than worker_connections allows. Unlike the EMFILE case, the descriptor limit may be sufficient, but the Nginx directive itself is the bottleneck. Increase worker_connections in the events block and ensure worker_rlimit_nofile is raised accordingly. If this warning appears frequently during normal traffic, it is a signal to revisit capacity planning rather than applying a minimal increment.

Persistent Connection Failures After Tuning

If clients still experience failed connections after raising limits, verify the listen backlog and kernel queue settings. A symptom pattern includes successful Nginx reloads but connection resets during bursts. Check net.core.somaxconn, the backlog parameter on the listen directive, and application-level accept rates. Also confirm that changes were applied to the correct Nginx instance; servers running multiple Nginx binaries (for example, one from the OS package and one compiled manually) can read different configuration paths and unit files.

Complete Configuration Example

The following example shows a coherent configuration for a 4-core reverse proxy handling TLS termination and forwarding traffic to an application backend. Paths and user names follow a Debian/Ubuntu layout; adjust user, package paths, and service names for RHEL-based distributions.

/etc/nginx/nginx.conf

user www-data;
worker_processes auto;
worker_rlimit_nofile 65535;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log warn;
events {
worker_connections 8192;
multi_accept off;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$upstream_addr" '
'$request_time $upstream_response_time';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 1000;
upstream app_backend {
server 10.0.0.10:8080;
server 10.0.0.11:8080;
keepalive 256;
}
server {
listen 443 ssl backlog=65535 reuseport;
server_name api.example.com;
ssl_certificate /etc/nginx/tls/fullchain.pem;
ssl_certificate_key /etc/nginx/tls/privkey.pem;
location / {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://app_backend;
}
}
}

/etc/systemd/system/nginx.service.d/limits.conf

[Service]
LimitNOFILE=65535

/etc/sysctl.d/99-nginx.conf

fs.file-max = 2097152
fs.nr_open = 2097152
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.ip_local_port_range = 10240 65535

Apply the operating system and service changes with the following sequence:

Terminal window
sudo sysctl --system
sudo systemctl daemon-reload
sudo nginx -t
sudo systemctl restart nginx

This example prioritizes consistency across layers. The Nginx worker limit, systemd process limit, and kernel ceilings are aligned so that the configured worker_connections value can be used in practice.

Trade-offs and Capacity Planning

Raising connection limits is not free. Each open connection consumes kernel memory, file descriptors, and userspace state inside the worker process. Idle keepalive connections are cheaper than active TLS sessions, but they still occupy slots that cannot be used by new clients. Setting worker_connections and worker_rlimit_nofile far above realistic demand can mask inefficiencies in application response times, keepalive policies, or upstream capacity.

CPU utilization is another boundary. Adding workers or allowing more concurrent connections increases the amount of work the server can accept, but it does not reduce the cost of TLS handshakes, compression, request parsing, or logging. If workers spend most of their time saturated at high CPU usage, raising connection limits will increase queueing and tail latency rather than improving throughput.

Capacity planning should combine configuration limits with observed metrics. Track active connections, request rates, response times, error rates, and file descriptor usage over time. Use those measurements to choose limits that provide headroom for traffic spikes without drifting into untested territory. When a single host consistently approaches safe CPU, memory, or network limits, horizontal scaling behind a load balancer is usually more predictable than continuing to raise per-node connection ceilings.

A disciplined tuning process treats worker_processes, worker_connections, and operating system limits as a coordinated set. Inspect the host, change one layer at a time, validate after each step, and monitor the result under representative load. That approach produces a configuration that is explainable, stable, and easier to operate as traffic grows.

found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.