AlgoViz

NGINX

medium 28 min

NGINX (say "engine x") is a web server, reverse proxy, load balancer and response cache.

Video lesson · Chapter 1 of 5

A browser reaches the shop

0:00 / 3:33

NGINX in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

NGINX is a program that listens for network connections, usually on ports 80 and 443, and decides what to do with each HTTP request: answer it with a file, answer it from a cache, or pass it on to an application server.

One installation often does several of these jobs at once. It ends the encrypted connection, checks limits, looks in its cache, chooses a healthy server, and sends the answer back to the client at whatever speed the client can take it. The same program can also forward plain TCP and UDP through its stream module.

It does not run your business logic. It stands in front of the programs that do.

Why it exists

A server that gives every connection its own thread or process pays for each one, even when the client is slow or silent. With ten thousand open connections most of those threads only wait. This is the problem known as C10K.

NGINX was built so that waiting costs almost nothing. The operating system tells a worker which connections are ready, the worker does a little work on each, and goes on. So a small machine can shield application servers from slow networks, encryption work and repeated questions.

A short history

  1. 2002

    Igor Sysoev begins to write NGINX.

  2. October 2004

    The first public release, aimed at many simultaneous connections.

  3. July 2011

    A company, Nginx, Inc., is founded to support the software and later sells NGINX Plus.

  4. March 2019

    F5 acquires the company.

  5. May 2023

    Version 1.25.0 adds experimental support for HTTP/3 over QUIC.

  6. February 2024

    Maxim Dounin, a core developer, starts the freenginx fork.

  7. 2025 and 2026

    Features that were commercial move to the open source version: name resolution of upstream servers in 1.27.3, sticky sessions in 1.29.6 and the least_time method in 1.31.0.

Words to know

Master process
Reads the configuration, opens the ports and starts the workers. It serves no requests.
Worker process
Handles connections. Usually one per CPU core.
Event loop
Ask which connections are ready, do a little for each, ask again.
Reverse proxy
A server that answers on behalf of servers behind it.
Upstream
A named group of servers that requests are passed to.
Location
A block of settings for the URLs that match a pattern.
Shared memory zone
Memory that all workers of one machine can read: cache keys, limits, server states.
Micro-caching
Caching a response for about a second to absorb a burst.

How it works

Step through the idea, or press Play.

Step 1 of 3

Accept. A worker accepts the connection, ends TLS and reads the headers

Understand it

Start here

The hotel porter

Imagine a hotel corridor with three rooms and one porter. Some guests need a minute before they can open the door. What should the porter do in that minute?

One porter, many guests
101102103JOBS101Standing still at door 101

The trick is not being faster. It is never waiting at one door.

The idea

What it does for a system

One front door

Browsers and phones reach one NGINX machine over HTTPS. Inside our system it handles TLS, cache, limits and balancing, and passes plain HTTP to three separate app servers, which all use one database.
Clients see only NGINX. Servers behind it can change without clients noticing.
  • High concurrency

    The project's own figure: 10,000 inactive keep-alive connections take about 2.5 MB of memory.

  • Load balancing

    Round robin, least connections, hashes, random of two, and passive failure checks.

  • TLS termination

    Certificates live in one place. Behind it, HTTP or a fresh TLS connection.

  • Response cache

    Answers kept on disk, keys in shared memory. Even one second helps in a burst.

  • Limits

    Requests per second, connections, and bandwidth per client.

  • Reloads without a gap

    New workers take new connections while old ones finish theirs.

The ideas behind these jobs have their own pages: load balancing, L4 and L7 balancers, API gateway, caching and rate limiting. This page is about how the product does them.

Inside

Master, workers and the event loop

One machine, several workers

Clients connect to one NGINX machine that contains two worker processes, each with one event loop. Both workers send requests to the app servers behind it.
A connection stays with the worker that accepted it. Workers share only shared-memory zones and files.

Who does what

ProcessRuns asWork
MasterUsually rootReads configuration, binds ports such as 443, starts and replaces workers
WorkerThe user in the configuration, such as www-data or nginxAll network and disk work for its connections
Cache manager and loaderLike a workerRemove old cache files; read existing ones after a start

One turn of the event loop

Nothing in this circle waits for a single client. Slow disk reads can be moved to a thread pool with aio threads.

How many clients can one proxy hold?

clients≤workers×worker_connections24×40962=8192\text{clients} \le \frac{\text{workers} \times \text{worker\_connections}}{2} \qquad \frac{4 \times 4096}{2} = 8192
A proxied request can need two connections, one to the client and one to the server, so divide by two. The limit of open files must allow it too.

Configuration

Contexts: http, server, location

Settings are nested. http holds everything about HTTP, a server block is one site on one address and port, and a location block holds the rules for some URLs. Modules supply the directives: gzip, TLS, proxying, limits and the rest.

nginx
worker_processes auto;worker_rlimit_nofile 16384;events {    worker_connections 4096;}http {    include mime.types;    sendfile on;    tcp_nopush on;    keepalive_timeout 65s;    gzip on;    gzip_types text/plain application/json text/css;    server {        listen 80;        server_name shop.example;        root /var/www/shop;        location /images/ { expires 1h; }        location /api/    { proxy_pass http://127.0.0.1:8080; }    }}
A complete small file. worker_connections belongs inside events; at the top level the file is rejected.

Which block answers?

Regular expressions beat a plain prefix. If no server name matches, the default server for that port answers.

Request

The life of one request

A proxied request with a cache miss

  1. 1

    Connection

    A worker accepts it. With HTTPS the TLS handshake follows; returning clients can resume a session.

  2. 2

    Matching and checks

    Server block by host and port, location by URL. Rewrites, access rules and limits apply.

  3. 3

    Cache check

    The key is, by default, the scheme, the proxied host and the request URI. A hit ends here.

  4. 4

    Upstream

    A server is chosen, an idle connection reused if there is one, and the request sent with the headers you set.

  5. 5

    Response

    Filters such as gzip run, the answer is stored if it may be, and the client gets it. A slow client is now NGINX's problem, not the app's.

Upstreams

Choosing a server

Balancing methods in the open source version

MethodRuleUse it when
Round robin (default)In turn, by weightServers and requests are alike
least_connFewest active connections, by weightSome requests take much longer than others
ip_hashHash of the first three parts of an IPv4 address, or the whole IPv6 addressSimple stickiness; unfair when many users share an address
hash key consistentKetama consistent hashing of any variableCache servers, or a cookie
random twoPick two at random, take the one with fewer connectionsSeveral NGINX machines balance the same group
sticky cookieA cookie names the server (open source since 1.29.6)Sticky sessions you cannot avoid
least_timeLowest average response time (open source since 1.31.0)Servers differ in speed

Which method?

nginx
upstream backend {    least_conn;    zone backend 64k;                 # shared by all workers    server 10.0.0.1:8080 weight=5;    server 10.0.0.2:8080 weight=3 max_fails=3 fail_timeout=10s;    server 10.0.0.3:8080 backup;      # only when the others are down    keepalive 32;                     # idle connections kept, per worker}server {    listen 80;    location / {        proxy_pass http://backend;        proxy_http_version 1.1;             # default since 1.29.7        proxy_set_header Connection "";     # needed before 1.29.7        proxy_set_header Host $host;        proxy_set_header X-Real-IP $remote_addr;        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;        proxy_set_header X-Forwarded-Proto $scheme;        proxy_connect_timeout 5s;        proxy_read_timeout 30s;    }}
Without zone, every worker counts connections and failures on its own.

Health checks. The open source version checks passively: after max_fails failed tries within fail_timeout (defaults 1 and 10 seconds) a server is left out for that time. Checks that probe servers on a timer are part of the commercial version. A failed try is passed to the next server for errors and timeouts; non-idempotent requests such as POST are not repeated once sent, unless you allow it. See retries.

Buffering

Shielding servers from slow clients

With proxy_buffering on, the default, NGINX reads the answer from the app at full speed into memory, and to a temporary file if it is large. The app's worker is free at once. Without it, a phone on a weak network holds that worker for the whole download.

What one slow client costs

t=1 MB×8250 kbit/s=32 swith buffering: 1 MB×81 Gbit/s=8 mst = \frac{1\,\text{MB} \times 8}{250\,\text{kbit/s}} = 32\,\text{s} \qquad \text{with buffering: } \frac{1\,\text{MB} \times 8}{1\,\text{Gbit/s}} = 8\,\text{ms}
Assumed sizes and speeds. That is how long the app worker stays busy.

Turn buffering off, or send X-Accel-Buffering: no, for answers that must arrive piece by piece, such as server-sent events. WebSockets need the Upgrade and Connection headers passed on.

Cache

Caching and micro-caching

nginx
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=pages:10m                 max_size=10g inactive=60m use_temp_path=off;server {    listen 80;    location /api/ {        proxy_pass http://backend;        proxy_cache pages;        proxy_cache_valid 200 1s;        proxy_cache_lock on;        proxy_cache_use_stale updating error timeout;        proxy_cache_background_update on;        proxy_cache_bypass $http_authorization;        proxy_no_cache $http_authorization;        add_header X-Cache-Status $upstream_cache_status always;    }}
One second of caching, one refresh at a time, and never for requests with an Authorization header.

Cache status

ValueMeaning
HITServed from the cache; no backend contact
MISSNot in the cache; fetched from the backend
EXPIREDIt was there but too old; fetched again
STALEAn old copy was served because the backend failed
UPDATINGAn old copy was served while another request refreshes it
REVALIDATEDThe backend confirmed that the old copy is still good
BYPASSThe cache was skipped on purpose, for example for a login

Example: 10,000 requests a second for one page and a lifetime of one second. With the lock, about 1 request a second reaches the backend, and 9,999 do not. That holds per key and per NGINX machine. proxy_cache_lock is off by default, and waiting requests give up after 5 seconds and go to the backend. See thundering herd.

Limits

Rate limiting

limit_req uses the leaky bucket method: requests of one key leave at a fixed rate. burst says how many may wait above it, and nodelay lets that burst through at once while still counting it. Other methods are compared in rate limiter algorithms.

nginx
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;limit_req_status 429;      # the default is 503server {    listen 80;    location /api/ {        limit_req zone=api burst=20 nodelay;        proxy_pass http://backend;    }}
One megabyte of zone holds about 16 thousand small states, so 10 MB is about 160 thousand addresses.

30 requests from one address in the same instant, rate 10 per second

SettingPassed at onceDelayedRefused
no burst1029
burst=20120, one every 100 ms9
burst=20 nodelay2109

Limits live in the memory of one machine. Five NGINX machines can let through five times the rate. For one exact total, keep the counter in a shared store; see rate limiter. Login pages deserve a strict limit, read-heavy public pages a loose one.

TLS

Ending encryption at the edge

Where the encryption ends

nginx
server {    listen 443 ssl;    http2 on;                              # replaces "listen ... http2"    server_name shop.example;    ssl_certificate     /etc/ssl/shop.pem;    ssl_certificate_key /etc/ssl/shop.key;    ssl_protocols TLSv1.2 TLSv1.3;         # already the default    ssl_session_cache shared:SSL:10m;      # about 40,000 sessions}
Without a shared cache, TLS 1.2 session resumption by ID does not work across workers.

One place to renew certificates, and no encryption work in the apps. The cost is that traffic behind NGINX is readable unless you encrypt again with proxy_pass https:// and proxy_ssl_verify on. Some rules demand that. X-Forwarded-Proto tells the app what the client used.

Availability

Two of them, and reloads

Surviving the loss of one NGINX

Two arrangements. Active-passive: users reach NGINX 1, which holds the virtual IP; a dashed arrow shows traffic moving to the standby NGINX 2 after failover. Active-active: users reach a cloud load balancer that sends traffic to NGINX 1 and NGINX 2.
One NGINX is a single point of failure, however many servers stand behind it.
Active-passive (keepalived)Active-active (balancer in front)
HowVRRP heartbeats decide who holds the virtual IP; a check script watches NGINXA cloud balancer or DNS spreads traffic over all
Hardware in useHalfAll, but keep room to lose one
Cache and limitsOne set, empty after a failoverOne per machine
NeedsA shared network segmentSomething in front
Shell
nginx -t               # test the files firstnginx -s reload        # new workers start, old ones finish their requestsnginx -s quit          # graceful stop; "stop" drops connectionsnginx -T | less        # print the configuration that is really in use
Long-lived WebSockets keep old workers alive after a reload. worker_shutdown_timeout puts an end to that.

Decide

When to choose it, and when not

Choose NGINX when

  • You serve many connections or static files
  • You want a reverse proxy or balancer you control
  • TLS should end in one place
  • A response cache near the app helps
  • You need limits and traffic protection
  • Reloads must not drop requests

Look elsewhere when

  • You need application logic: put it in an app server behind
  • One small server with modest traffic is enough
  • Nobody should operate it: use a cloud balancer
  • You want a service mesh or constant changes by API: consider Envoy

Neighbours

ProductAlikeDifferentChoose it for
Apache HTTP ServerFiles, proxying, TLS, many modulesPer-directory .htaccess, embedded languages; its event MPM also frees threads from idle connectionsExisting sites that rely on those
HAProxyEvent driven, balancing, health checksDedicated balancer: active checks and a stats page built in; not a file server, and its cache is smallPure TCP and HTTP balancing
EnvoyHTTP/2, gRPC, edge or service proxyConfigured live by xDS APIs, tracing built in, common in service meshesMeshes and dynamic discovery
AWS ALB or NLBBalancing, checks, TLSManaged and scaled for you, fewer settings, no response cacheLittle operation work; see cloud load balancing

Strengths

  • Many connections, little memory
  • Several jobs in one program
  • Changes without dropping connections
  • Long production history, 2-clause BSD licence

Costs

  • Changes are files and reloads; live APIs are limited in open source
  • Cache and limits per machine, idle upstream connections per worker
  • No business logic
  • Small configuration mistakes have large effects: matching, caching, limits

Summary

The whole topic in one minute.

NGINX is a small set of worker processes that each watch thousands of connections and only touch the ones that are ready. That makes it good at everything that is mostly waiting: serving files, ending TLS, buffering slow clients, and passing requests on.

Use it as the front door with an upstream group, buffering, a cache with a lock, and limits. Remember what is per machine (limits, cache) and per worker (idle upstream connections), run two of them, and test the configuration before every reload.

  • One master, a few workers, each with an event loop that never waits for one client.
  • Server block by host, location by URL; a regex beats a plain prefix.
  • Buffering frees the app; a one-second cache with a lock absorbs bursts.
  • Limits and cache are per machine; idle upstream connections are per worker.
  • Run two, test with nginx -t, reload instead of restart.

Sources