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
Both stand in the middle of a connection. The difference is whose side they are on.
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
Everything that is the same for every request moves out of the app and into the proxy.
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
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 -dstarts it. Every snippet below is a piece of the onenginx.conf, with onelocationprefix 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
A directive lives in a context and is inherited downward. A request is matched to one server, then to one location inside it.
http apply to every server unless a server or location overrides them.| Order | server_name match against the Host header |
|---|---|
| 1 | Exact name: bank.local |
| 2 | Longest leading wildcard: *.bank.local |
| 3 | Longest trailing wildcard: bank.* |
| 4 | First matching regex, in file order: ~^api\d+\.bank\.local$ |
| 5 | The 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
The order in the file matters only between regexes. Prefix locations compete on length.
| Step | Rule | Then |
|---|---|---|
| 1 | = /path matches exactly | Use it, stop |
| 2 | Find the longest matching prefix | If it is marked ^~, use it, stop |
| 3 | Try regexes (~, ~*) top to bottom | First match wins |
| 4 | No regex matched | Use 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
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
upstreamare resolved once, at start or reload. A backend that comes back with a new IP needs a reload (or aresolver).
Proxying to an app
Part 3 of 6 · paths, headers, timeouts, bodies
proxy_pass and the trailing slash
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
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.
peeris nginx's container address every time, and withoutHostthe 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
Each leg of a proxied request has its own clock. All three proxy timeouts default to 60 seconds.
- 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
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.
| Directive | Default | Change it when |
|---|---|---|
proxy_buffering | on | Server-sent events or streamed output: set off |
proxy_request_buffering | on | Large uploads the app should stream: set off |
client_max_body_size | 1m | Uploads: 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
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_connkept 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
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_hashhashes the first three octets of an IPv4 address, so a whole office behind one NAT lands on one server.
Algorithms compared, and sticky sessions
| Algorithm | Picks | 30 requests here | Use when |
|---|---|---|---|
| Round robin | Next in turn | 10 / 10 / 10 | Equal servers, similar request cost |
| Weighted | In turn, by weight | 18 / 6 / 6 | Unequal machines, canary share |
least_conn | Fewest active requests | 0 / 0 / 30 with two busy | Request times vary a lot |
ip_hash | Hash of client IP | 0 / 0 / 30 from one client | Stickiness with no cookie |
hash key consistent | Hash ring of a key | Same key, same server | Per-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
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
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
A layer 4 balancer forwards TCP connections and never reads what is inside. A layer 7 balancer parses HTTP and decides per request.
| Layer 4 (TCP, UDP) | Layer 7 (HTTP) | |
|---|---|---|
| Sees | IPs, ports, bytes | Host, path, headers, cookies, status |
| Balances | Connections | Requests |
| Can do | Any protocol, TLS passthrough, very high throughput | Routing by path, retries, caching, rate limits, header rewrite |
| Cannot do | Route by URL, add headers, retry a request | Non-HTTP protocols |
| Examples | nginx stream, AWS NLB, HAProxy TCP mode | nginx 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
- 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
The demo uses a self-signed certificate, which encrypts but proves nothing: clients must be told to trust it.
-kskips verification, and without it curl refuses (exit 60).--cacert certs/bank.crtwith a name in the certificate verifies properly.- The app sees
x_forwarded_proto: httpsalthough 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-ageseconds, 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
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 nodelaylet 1 + 5 through at once. Withoutnodelaythe 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
realipmodule) or on an API key.
proxy_cache and gzip
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_staleserves the old copy while the app is down or one request refreshes it.
Security headers and version tokens
The proxy is the one place to add the headers every response should carry.
| Header | Value used here | Stops |
|---|---|---|
Strict-Transport-Security | max-age=31536000; includeSubDomains | Downgrade to plain HTTP |
X-Content-Type-Options | nosniff | Browsers guessing a script out of an upload |
X-Frame-Options | DENY | Clickjacking through an iframe |
Referrer-Policy | strict-origin-when-cross-origin | Full URLs leaking to other sites |
Content-Security-Policy | Not set here: it is per application | Injected scripts (XSS) |
server_tokens offalso removes the version from error pages. It hides nothing from a determined scanner, it just stops advertising.add_headerneedsalwaysto 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
All three strategies are the same move: change which servers the balancer sends to, and never kill a server that still has requests.
| Endpoint | Question | Checks | On failure |
|---|---|---|---|
Liveness (/healthz) | Is the process stuck? | Nothing external | Restart it |
Readiness (/readyz) | Can it take traffic now? | Warm-up done, dependencies reachable, not shutting down | Stop routing to it, do not restart |
- Draining: fail readiness (or mark the server
downand 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
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.
| Field | First line | Meaning |
|---|---|---|
$status | 200 | What the client got |
rt | 2.006 | Total seconds in nginx, first byte in to last byte out |
uct | 0.000 | Time to connect to the app. High: network, or a full accept queue |
uht | 2.007 | Time until the app's response headers. High: the app is slow |
urt | 2.007 | Time until the app's last byte |
up, us | 172.20.0.3:8000, 200 | Which instance, and its status. Several values, comma separated, mean retries |
id | 7e65... | 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. rtmuch larger thanurtmeans 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
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:rtequals 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
| Code | Who failed | Usual cause at the proxy | Look at |
|---|---|---|---|
| 301 / 308 | Nobody | HTTP to HTTPS redirect, missing trailing slash | Location header |
| 400 | Client | Malformed request, plain HTTP sent to the TLS port, header too large | Error log |
| 403 | Client | deny rule (/nginx_status from outside gave 403 here) | allow / deny |
| 404 | Config or client | No location proxied the path, so nginx looked for a file | Location match order |
| 413 | Client | Body larger than client_max_body_size | That directive |
| 429 | Client | Rate limit, when limit_req_status 429 is set | "limiting requests" in the error log |
| 499 | Client | Client closed the connection before the response | Client timeout vs rt |
| 502 | App | Connection refused or reset, app crashed mid-response, invalid response, no live upstreams | Is the process up and listening? |
| 503 | nginx on purpose, or app | limit_req / limit_conn default, maintenance, app overloaded | up=- means nginx sent it |
| 504 | App | No connect within proxy_connect_timeout, or no bytes within proxy_read_timeout | Slow 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
| Need | Directive |
|---|---|
| Check and apply config | nginx -t && nginx -s reload, nginx -T to print the effective config |
| Send to a group | upstream name { server host:port; } and proxy_pass http://name; |
| Strip the location prefix | proxy_pass http://name/; (trailing slash) |
| Tell the app who called | proxy_set_header Host, X-Forwarded-For, X-Forwarded-Proto, X-Request-ID |
| Algorithm | default, weight=N, least_conn, ip_hash, hash $key consistent |
| Shared balancing state | zone name 64k; in the upstream |
| Bench a failing server | max_fails=1 fail_timeout=10s, spare with backup, drain with down |
| Reuse upstream connections | keepalive N;, proxy_http_version 1.1;, Connection "" |
| Timeouts | proxy_connect_timeout, proxy_send_timeout, proxy_read_timeout |
| Uploads, streaming | client_max_body_size, proxy_buffering off; |
| TLS | listen 443 ssl;, ssl_certificate, ssl_certificate_key, return 301 https://... |
| Rate and connection limits | limit_req_zone + limit_req, limit_conn_zone + limit_conn |
| Cache | proxy_cache_path, proxy_cache, proxy_cache_valid, $upstream_cache_status |
| See what happened | log_format with $request_time and $upstream_*, stub_status |
- A Kubernetes Ingress (or a Gateway API route) is the
serverandlocationrules 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.