Blog
IntermediateReferenceInfrastructure

NGINX

NGINX as a reverse proxy and load balancer - the event-driven process model, the configuration hierarchy, upstream keepalives that silently do not work, and what open source will not do for you.

Applies to
NGINX1.30-1.31supported branches; defaults for 1.28 and older flagged where they differ
matureUpdated Reviewed

Every connection NGINX handles is a file descriptor in an event loop. A worker process registers thousands of sockets with the kernel - epoll on Linux, kqueue on FreeBSD and macOS - and the kernel tells it which ones are ready. There is no thread per connection, so memory use stays flat as connection count climbs, and an idle keepalive connection costs almost nothing.

That single fact explains the whole architecture: one master process that owns the configuration and the lifecycle, and a set of worker processes that do all request handling inside their own non-blocking loop. If a worker blocks, every connection it holds stalls. The configuration exists mostly to keep workers non-blocking and to decide which upstream each request goes to.

How NGINX is built

The master process reads nginx.conf, validates it, and spawns workers. Workers inherit the listening sockets and accept connections directly - there is no queue inside the master handing work out. On Linux each worker calls epoll_wait, and the kernel wakes whichever worker should take the next connection.

Directive Default What it actually controls
worker_processes 1 How many worker processes run. auto (since 1.9.10) sets one per CPU core. Most packaged configs set auto in nginx.conf, which is why the printed default surprises people.
worker_connections 512 Maximum simultaneous connections per worker. Total capacity is worker_processes × worker_connections; raise both or neither.
accept_mutex off since 1.11.3 (on before) Whether workers take turns accepting connections. Unnecessary on kernels supporting EPOLLEXCLUSIVE (Linux 4.5+, used since NGINX 1.11.3) or with reuseport.
use auto Forces a connection method - epoll, kqueue, select, poll. NGINX picks the most efficient available; you almost never set this.

Reloading does not restart connections. nginx -s reload makes the master validate the new configuration, spawn new workers with it, and ask the old workers to finish their current requests and exit. A reload in the middle of a slow request does not kill it; stop shuts down immediately, quit waits for in-flight work.

The path a request takes through NGINX
The path a request takes through NGINXClients connect to worker processes, which run an epoll event loop. The worker matches the request URI against location blocks using longest-prefix matching, then proxies to a member of the upstream pool - or serves a file from disk for static locations. The master process owns configuration and reloads.clientsthousands of socketsworkerepoll event looplocationlongest prefix winsupstreamserver poolapp serveryour backendmasterconfig + reloadfile cachestatic content123456
Workers do all request handling inside one event loop each; the master only owns configuration. Select a shape to jump to the relevant section.
Text equivalent
  1. Clients connect; each connection is a socket watched by a worker’s epoll loop.
  2. The master process owns the configuration and spawns or replaces workers on reload.
  3. The worker matches the request URI against location blocks, longest prefix first.
  4. A proxied location resolves to an upstream pool of backend servers.
  5. The worker forwards the request to one member of the pool and streams the response back.
  6. A static location serves the file directly from disk.

The configuration model

NGINX configuration is a hierarchy of contexts: main at the top, events and http inside it, server inside http, location inside server. A directive’s context decides where it is legal and what it inherits down.

worker_processes auto;
error_log /var/log/nginx/error.log warn;

events {
    worker_connections 4096;
}

http {
    include       /etc/nginx/mime.types;
    sendfile      on;
    tcp_nopush    on;
    keepalive_timeout 65;

    upstream app {
        least_conn;
        server app1.internal:8080;
        server app2.internal:8080;
        server app3.internal:8080;
    }

    server {
        listen 443 ssl;
        server_name api.example.com;

        ssl_certificate     /etc/nginx/tls/api.crt;
        ssl_certificate_key /etc/nginx/tls/api.key;

        location / {
            proxy_pass http://app;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /static/ {
            root /srv/site;
        }
    }
}

Two details in that file trip people repeatedly:

Location matching is longest-prefix, not first-match. location /static/ wins over location / for any URI starting with /static/, regardless of order in the file. root then joins the URI to the filesystem path: a request for /static/logo.png reads /srv/site/static/logo.png. Exact match exists too - location = /health - and wins outright.

proxy_set_header inheritance is all-or-nothing. These directives are inherited from the outer level only if the inner level defines none of its own. One proxy_set_header inside a location silently discards every proxy_set_header set in the enclosing server block. If your X-Forwarded-For disappears on one path only, this is why.

Load balancing

An upstream block names a pool; proxy_pass http://name sends traffic to it. With no method directive the default is round-robin.

Method Directive Choose when
Round-robin default Requests are uniform and cheap; simple to reason about.
Least connected least_conn; Requests vary in duration - the default long-lived-request choice.
Least time least_time header|last_byte You want latency-aware routing, not just connection counts.
IP hash ip_hash; Session affinity is required and you cannot move session state server-side. Sticky by client IP, which collapses behind NATs and CDNs.

Weights skew the distribution: server app1.internal weight=3; sends three of every five requests to app1 under round-robin. backup marks a server that only receives traffic when the others are down; down marks one administratively out of rotation.

Health checks are passive in open source. If a server fails max_fails times (default 1) within fail_timeout, NGINX marks it failed and stops routing to it for fail_timeout seconds, then probes it with live traffic. That is client-visible by construction: the first request that discovers a dead backend is a real request that fails. Active health checks - NGINX probing backends without client traffic - require NGINX Plus, as do on-the-fly upstream changes via the API and least_time outside HTTP upstreams.

The upstream keepalive trap

This is the configuration bug that survives the most code review, and it is worth its own section.

By default, NGINX sends every proxied request with Connection: close and, on versions before 1.29.7, speaks HTTP/1.0 to the upstream. Connection: close is a default proxy_set_header, so no amount of keepalive 64; on the upstream block changes what is on the wire. The upstream opens a fresh TCP connection per request, keepalive pooling is silently dead, and under load you burn ephemeral ports and TLS handshakes against your own backends.

The fix requires three things together:

upstream app {
    server app1.internal:8080;
    server app2.internal:8080;
    keepalive 64;
}

location / {
    proxy_pass http://app;
    proxy_http_version 1.1;            # required on 1.29.6 and earlier
    proxy_set_header Connection "";    # required on every version
    proxy_set_header Host $host;
}
What changed, and in which release Behaviour before Behaviour now
1.29.4 proxy_http_version accepted 1.0 or 1.1 Also accepts 2 (requires ngx_http_v2_module)
1.29.7 Upstream connections defaulted to HTTP/1.0 Default is HTTP/1.1; proxy_http_version 1.1 only needed for older workers or explicit downgrade
1.27.2 No trailer support proxy_pass_trailers can forward trailing headers

Connection "" is still required on every version - the header default did not change, only the protocol version did.

Failure modes and how you see them

Symptom Likely cause Where to look
One backend getting most of the traffic ip_hash on an upstream whose clients share NAT addresses; or a dead peer being retried constantly Compare per-upstream request counts in the access log ($upstream_addr)
502s spiking, backends healthy Ephemeral port exhaustion from Connection: close upstream connections ss -s for timewait growth; check proxy_http_version and the Connection header
Config looks right, headers missing upstream A proxy_set_header inside location erased the server-level set Read the effective config, not the intent - nginx -T dumps it
Reload “worked” but old behaviour persists The reload failed validation and the master rolled back silently, or new workers have not started error.log for the last reload; ps -ef | grep nginx for worker counts
Slow backends starving fast ones Round-robin with heterogeneous upstreams Switch to least_conn; the symptom disappears because busy servers stop getting new work

What NGINX is not for

  • Application logic. njs (the NGINX JavaScript module) can route and transform, but a request pipeline that needs business rules belongs in the application or an API gateway, not in if blocks in the config. if inside location has well-documented edge cases and the docs warn against it.
  • Active health checking. Open source NGINX only learns a backend is down from a real request failing. If you need out-of-band probes, that is NGINX Plus, HAProxy’s active checks, or a service mesh - see the Envoy guide for what a data plane with a real control-plane API looks like.
  • Long-lived connection services. WebSockets work, but TCP/UDP load balancing in the stream module is a different feature set from the HTTP module; do not conflate the two.

The reference configuration above runs against the supported branches (1.30 stable, 1.31 mainline). On 1.28 and older, proxy_http_version 1.1 is mandatory in the upstream keepalive stanza - it is not the default there.

NGINX release support

2 supported
ReleaseLatestReleased
1.311.31.9May 2026
1.301.30.7Apr 2026

Data as of 2026-11-21 from endoflife.date. Refresh with node scripts/fetch-versions.mjs.