Learnings

Cloud and DevOps

Nginx and Load Balancing

A reverse proxy is the one door in front of your app servers: it ends TLS, picks a backend, absorbs slow clients and turns backend failures into status codes. Every config line and terminal output here comes from one Docker Compose project: nginx 1.29.8 in front of three copies of a small Python bank API that says which instance answered.

The proxy

Part 1 of 6 · what sits in front of the app, and the project

Forward proxy and reverse proxy

The proxy

Both stand in the middle of a connection. The difference is whose side they are on.

Forward proxy: configured by the client, hides the client from servers.
Reverse proxy: run by the server side, hides the servers from clients.

Examples: forward is a corporate egress proxy. Reverse is nginx, HAProxy, Envoy, a cloud load balancer or a CDN edge.

What nginx does, and how it is built

The proxy

Everything that is the same for every request moves out of the app and into the proxy.

The app only sees clean, already-limited, plain HTTP requests.
One master, one single-threaded worker per core, each multiplexing its own sockets.

Why it scales: an idle connection costs a worker a few kilobytes of state, not a thread, so one worker holds thousands of slow or keep-alive clients.

The project: one nginx, three apps

The proxy

Only nginx publishes ports. The apps are reachable by service name inside the Compose network (Compose itself is covered in Docker for Backend Engineers).

  • docker compose up -d starts it. Every snippet below is a piece of the one nginx.conf, with one location prefix per demo (/weighted/, /least/, /cached/ and so on).
  • The app matches on the end of the path (/who, /slow, /balance), so any prefix works.

Config anatomy

Part 2 of 6 · contexts, how a request finds its block, safe reloads

Contexts, and picking a server

Config anatomy

A directive lives in a context and is inherited downward. A request is matched to one server, then to one location inside it.

Settings in http apply to every server unless a server or location overrides them.
Orderserver_name match against the Host header
1Exact name: bank.local
2Longest leading wildcard: *.bank.local
3Longest trailing wildcard: bank.*
4First matching regex, in file order: ~^api\d+\.bank\.local$
5The default_server for that port, or the first server listed

Trap: an unknown Host does not get a 404, it gets the default server. Make the default a block that returns 444 or 404 if stray hostnames should not reach the app.

Picking a location

Config anatomy

The order in the file matters only between regexes. Prefix locations compete on length.

StepRuleThen
1= /path matches exactlyUse it, stop
2Find the longest matching prefixIf it is marked ^~, use it, stop
3Try regexes (~, ~*) top to bottomFirst match wins
4No regex matchedUse the prefix from step 2

Trap: /balance.json has the prefix /balance, yet the regex takes it. A regex beats every prefix that is not = or ^~.

Test, then reload without dropping anyone

Config anatomy

A reload starts new workers on the new config and lets the old ones finish their requests. Here a 4-second request is in flight when the reload happens.

  • Always nginx -t && nginx -s reload. A copy with one semicolon removed failed the test with [emerg] unexpected "}" in /tmp/bad.conf:5, and a reload with a bad config is refused while the old workers keep serving.
  • Hostnames in upstream are resolved once, at start or reload. A backend that comes back with a new IP needs a reload (or a resolver).

Proxying to an app

Part 3 of 6 · paths, headers, timeouts, bodies

proxy_pass and the trailing slash

Proxying to an app

With no path after the upstream name, the request path is passed unchanged. With any path, even a single /, the matched location prefix is replaced by it.

Trap: one character decides whether the app must know its public prefix. Pick one style per service and write the mapping in a comment.

Forwarding headers

Proxying to an app

The app's TCP peer is always nginx. Who the client was, which host it asked for and whether it used HTTPS survive only as headers that you set.

  • peer is nginx's container address every time, and without Host the app sees the upstream's name, bank.
  • The third call shows the client can prepend anything to X-Forwarded-For. Trust only the entries added by your own proxies, counted from the right.

Timeouts

Proxying to an app

Each leg of a proxied request has its own clock. All three proxy timeouts default to 60 seconds.

Connect is one deadline. Send and read are gaps between two writes or two reads, not a total.
  • The app still finishes its 5 seconds of work after the 504. A timeout at the proxy does not cancel anything behind it.
  • Order the budgets: client timeout > proxy read timeout > app's own timeout to its database.

Buffering, body size, WebSocket

Proxying to an app

By default nginx reads the whole request body before it contacts the app, and reads the app's response as fast as the app can write it. A slow client then occupies nginx, not an app worker.

DirectiveDefaultChange it when
proxy_bufferingonServer-sent events or streamed output: set off
proxy_request_bufferingonLarge uploads the app should stream: set off
client_max_body_size1mUploads: raise it for that location only

A WebSocket starts as an HTTP request with Upgrade. That header is hop-by-hop, so the proxy must pass it on explicitly (config from the project, no WebSocket client was run for this page).

Trap: the 413 comes from nginx, so the app never logs it. "Uploads fail and the app shows nothing" usually means this limit.

Load balancing

Part 4 of 6 · upstream groups, algorithms, failures

upstream: round robin, weights, least_conn

Load balancing

An upstream block names a group of servers, and proxy_pass http://name sends each request to one of them. The default is round robin.

  • Round robin ignores how busy a server is. least_conn kept all 30 quick requests away from the two busy instances.
  • Weighted order was app1 app1 app2 app1 app3: the heavy server is interleaved, not hit three times in a row.

Trap: without the zone line each worker counts connections alone. The first run here, with 2 workers and no zone, gave 6 / 5 / 19 instead of 0 / 0 / 30.

ip_hash and consistent hash

Load balancing

Hashing sends the same key to the same server every time. ip_hash uses the client address, hash uses any variable you choose.

What happens to 300 account keys when app3 is removed from the group, measured against a 3-server and a 2-server copy of each upstream:

  • Plain hash is hash mod N: changing N moved 64% of keys. Consistent hashing moved only the 103 keys that lived on the removed server.
  • ip_hash hashes the first three octets of an IPv4 address, so a whole office behind one NAT lands on one server.

Algorithms compared, and sticky sessions

Load balancing

AlgorithmPicks30 requests hereUse when
Round robinNext in turn10 / 10 / 10Equal servers, similar request cost
WeightedIn turn, by weight18 / 6 / 6Unequal machines, canary share
least_connFewest active requests0 / 0 / 30 with two busyRequest times vary a lot
ip_hashHash of client IP0 / 0 / 30 from one clientStickiness with no cookie
hash key consistentHash ring of a keySame key, same serverPer-server caches, shards

A sticky session pins a user to one server because that server holds the user's state in memory.

  • It breaks on every deploy and every failure: the pinned server goes away and the session with it.
  • It unbalances load: one heavy user, or one NAT, overloads one instance.
  • The fix is to remove the need: keep sessions in Redis or in a signed token, and any instance can serve any request.

Related: where load balancers sit in a whole system, with DNS and global balancing, is in Building Blocks.

Passive health checks and backup servers

Load balancing

Open-source nginx has no probe. It learns a server is down when a real request to it fails, benches it for fail_timeout, then tries it again with a real request.

  • Request 2 was the one that found app2 dead: it waited the 1-second connect timeout, was retried on the next server and still returned 200.
  • That retry is proxy_next_upstream (default: error timeout). A POST that was already sent is not retried, so it gets the error.
  • Active probes (health_check) are an NGINX Plus feature. HAProxy, Envoy and cloud balancers probe in the free tier.

Keep-alive to the upstreams

Load balancing

Opening a TCP (or TLS) connection per request to the backend is wasted latency and wasted ports. An idle pool reuses them.

Version note: on this nginx 1.29.8 a plain proxy_pass with none of these lines also reused connections (the counter reached 2 on /raw/). Older releases default to HTTP/1.0 with Connection: close and need all three lines, so check what yours does.

Layers, TLS and protection

Part 5 of 6 · L4 and L7, certificates, limits, cache

Layer 4 and layer 7

Layers, TLS and protection

A layer 4 balancer forwards TCP connections and never reads what is inside. A layer 7 balancer parses HTTP and decides per request.

The usual stack: a cloud L4 balancer gives one stable address and spreads connections over several L7 proxies.
Layer 4 (TCP, UDP)Layer 7 (HTTP)
SeesIPs, ports, bytesHost, path, headers, cookies, status
BalancesConnectionsRequests
Can doAny protocol, TLS passthrough, very high throughputRouting by path, retries, caching, rate limits, header rewrite
Cannot doRoute by URL, add headers, retry a requestNon-HTTP protocols
Examplesnginx stream, AWS NLB, HAProxy TCP modenginx http, AWS ALB, Envoy

Interview point: at L4 both requests went to app3, because the connection was balanced once. Long-lived connections (gRPC, HTTP/2) behind an L4 balancer stay on old servers and miss new ones.

Where TLS ends

Layers, TLS and protection

Termination: the proxy decrypts. Simple, full L7 features, plain text inside the network.
Passthrough: the proxy cannot read anything, so no routing by path, no headers, no caching.
Re-encryption: decrypt, inspect, encrypt again. L7 features and no plain text on the wire, at more CPU and two sets of certificates.
  • Termination is the default choice. Re-encryption is what "encryption in transit everywhere" (PCI, zero trust) asks for.
  • Passthrough fits when the app must see the client certificate itself, or the protocol is not HTTP.

TLS at the proxy

Layers, TLS and protection

The demo uses a self-signed certificate, which encrypts but proves nothing: clients must be told to trust it.

  • -k skips verification, and without it curl refuses (exit 60). --cacert certs/bank.crt with a name in the certificate verifies properly.
  • The app sees x_forwarded_proto: https although its own connection is plain HTTP. Frameworks use that header to build redirect URLs and secure cookies.
  • HSTS tells the browser to use HTTPS for this host for max-age seconds, with no first plain request to hijack.

Real certificates (not run here): an ACME client such as certbot proves you control the domain (a file served over HTTP, or a DNS record) and Let's Encrypt issues a free 90-day certificate. Renewal is a scheduled job that ends with nginx -s reload.

Rate and connection limits

Layers, TLS and protection

limit_req is a leaky bucket per key: requests drain at a fixed rate, burst is how many may wait, and the rest are rejected.

rate=5r/s means one request per 200 ms, not five at once each second.
  • burst=5 nodelay let 1 + 5 through at once. Without nodelay the 5 would be held and released one per 200 ms.
  • The default reject status is 503, which looks like an outage on dashboards. Set limit_req_status 429.
  • Behind another balancer every request has the balancer's IP. Key the zone on the real client (the realip module) or on an API key.

proxy_cache and gzip

Layers, TLS and protection

nginx can keep whole responses on disk and answer repeats without touching the app.

  • A HIT is byte-identical to the stored response, instance name included. After 5 seconds the entry expired and a different instance answered.
  • The default key is scheme, host and URI. A balance cached this way is served to anyone with the URL, so cache only public responses or put the user in proxy_cache_key.
  • proxy_cache_use_stale serves the old copy while the app is down or one request refreshes it.

Security headers and version tokens

Layers, TLS and protection

The proxy is the one place to add the headers every response should carry.

HeaderValue used hereStops
Strict-Transport-Securitymax-age=31536000; includeSubDomainsDowngrade to plain HTTP
X-Content-Type-OptionsnosniffBrowsers guessing a script out of an upload
X-Frame-OptionsDENYClickjacking through an iframe
Referrer-Policystrict-origin-when-cross-originFull URLs leaking to other sites
Content-Security-PolicyNot set here: it is per applicationInjected scripts (XSS)
  • server_tokens off also removes the version from error pages. It hides nothing from a determined scanner, it just stops advertising.
  • add_header needs always to apply to error responses.

Trap: a location with its own add_header does not inherit the ones from the server block. Repeat them or put them in an included file.

Deploys and debugging

Part 6 of 6 · releasing behind a balancer, reading logs and status codes

Zero-downtime deploys

Deploys and debugging

All three strategies are the same move: change which servers the balancer sends to, and never kill a server that still has requests.

Rolling: one instance at a time. Cheap, but v1 and v2 serve together.
Blue-green: a full second fleet, one switch, instant rollback, double the cost.
Canary: a small weighted share first, widened only if the metrics hold.
EndpointQuestionChecksOn failure
Liveness (/healthz)Is the process stuck?Nothing externalRestart it
Readiness (/readyz)Can it take traffic now?Warm-up done, dependencies reachable, not shutting downStop routing to it, do not restart
  • Draining: fail readiness (or mark the server down and reload), wait for in-flight requests, then stop. The reload chapter showed nginx doing this for its own workers.
  • A liveness check that queries the database turns one database blip into a restart of every instance.

Access log, error log, stub_status

Deploys and debugging

The default log format has no timings. Add the upstream fields and one line tells you whether nginx, the network or the app was slow.

FieldFirst lineMeaning
$status200What the client got
rt2.006Total seconds in nginx, first byte in to last byte out
uct0.000Time to connect to the app. High: network, or a full accept queue
uht2.007Time until the app's response headers. High: the app is slow
urt2.007Time until the app's last byte
up, us172.20.0.3:8000, 200Which instance, and its status. Several values, comma separated, mean retries
id7e65...The request id also sent to the app
  • The second line has - in every upstream field: nginx answered on its own, the app was never called.
  • rt much larger than urt means a slow client, not a slow app.

Reading it: accepts above handled means connections were dropped at the worker_connections limit. Waiting is idle keep-alive clients.

502, 504 and 499 reproduced

Deploys and debugging

A 5xx from the proxy says how the conversation with the app failed. The error log line says exactly where.

  • 502: rt=0.000, refused at once. 504: rt equals the timeout exactly. That pattern alone tells them apart on a dashboard.
  • 499 is nginx's own code, written to the log only. The client had already gone, so nobody received it.
  • A wave of 499 at a round number (1.0 s, 30 s) is some client's timeout, set shorter than your slow path.

Which status code means what

Deploys and debugging

CodeWho failedUsual cause at the proxyLook at
301 / 308NobodyHTTP to HTTPS redirect, missing trailing slashLocation header
400ClientMalformed request, plain HTTP sent to the TLS port, header too largeError log
403Clientdeny rule (/nginx_status from outside gave 403 here)allow / deny
404Config or clientNo location proxied the path, so nginx looked for a fileLocation match order
413ClientBody larger than client_max_body_sizeThat directive
429ClientRate limit, when limit_req_status 429 is set"limiting requests" in the error log
499ClientClient closed the connection before the responseClient timeout vs rt
502AppConnection refused or reset, app crashed mid-response, invalid response, no live upstreamsIs the process up and listening?
503nginx on purpose, or applimit_req / limit_conn default, maintenance, app overloadedup=- means nginx sent it
504AppNo connect within proxy_connect_timeout, or no bytes within proxy_read_timeoutSlow query, deadlock, exhausted workers

Interview point: 502 is "the app answered badly or not at all", 504 is "the app did not answer in time", 503 is "we chose not to try". Check us= first: it separates the proxy's status from the app's.

Cheat sheet, and the bridge to Kubernetes

Deploys and debugging

NeedDirective
Check and apply confignginx -t && nginx -s reload, nginx -T to print the effective config
Send to a groupupstream name { server host:port; } and proxy_pass http://name;
Strip the location prefixproxy_pass http://name/; (trailing slash)
Tell the app who calledproxy_set_header Host, X-Forwarded-For, X-Forwarded-Proto, X-Request-ID
Algorithmdefault, weight=N, least_conn, ip_hash, hash $key consistent
Shared balancing statezone name 64k; in the upstream
Bench a failing servermax_fails=1 fail_timeout=10s, spare with backup, drain with down
Reuse upstream connectionskeepalive N;, proxy_http_version 1.1;, Connection ""
Timeoutsproxy_connect_timeout, proxy_send_timeout, proxy_read_timeout
Uploads, streamingclient_max_body_size, proxy_buffering off;
TLSlisten 443 ssl;, ssl_certificate, ssl_certificate_key, return 301 https://...
Rate and connection limitslimit_req_zone + limit_req, limit_conn_zone + limit_conn
Cacheproxy_cache_path, proxy_cache, proxy_cache_valid, $upstream_cache_status
See what happenedlog_format with $request_time and $upstream_*, stub_status
  • A Kubernetes Ingress (or a Gateway API route) is the server and location rules of this page written as YAML: host, path, backend Service.
  • An ingress controller is a proxy such as nginx that watches those objects and rewrites its own upstreams as pods come and go, with readiness probes deciding membership.
  • A cloud L4 load balancer still sits in front of it, exactly as in the layer 4 and layer 7 diagram.

Back to Cloud and DevOps.