NGINX
medium 28 minNGINX (say "engine x") is a web server, reverse proxy, load balancer and response cache.
See it run
One request through the proxy, the event loop, balancing, the cache, the limit and a reload.
Operations
One request
From the TLS handshake to the answer, with a cache miss and a server that fails.
Step 1 of 6
Connect
A worker accepts the connection and ends TLS.
Step 1: Connect
def handle(conn): req = read_headers(decrypt(conn)) loc = location_for(server_for(req.host), req.path) check_limits(loc, req) if fresh(cache, req): return send(cache[req]) resp = try_servers(loc.upstream, req) store_if_allowed(cache, req, resp) send(resp)- Backend work
- 1 request
- Where state lives
- Connection, cache
Say what happens when the first server fails. That is what the upstream group is for.
In the real world
The same nginx doing real jobs. Pick one and step through it.
A 1 MB answer to a client with 250 kbit/s, without and with buffering.
Step 1 of 3
No buffering
App busy for 32 s
The app worker feeds the phone for 32 seconds.
Step 1: No buffering
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Caching a private page
criticalThe default key has no cookie or token in it, so the next visitor can receive another person's page.
Wrongproxy_ignore_headers Set-Cookie Cache-Control;proxy_cache_valid 200 10m;Rightproxy_cache_bypass $http_authorization;proxy_no_cache $http_authorization;proxy_cache_valid 200 1s;A limit per machine read as a total
majorZones are local. Four machines let through four times the rate.
Wronglimit_req_zone $http_x_api_key zone=k:10m rate=100r/m;# on 4 machines = 400 a minuteRight# local limit for protection,# shared counter for the promised totalToo few connections
majorThe default is 512 per worker, and a proxied request can take two. New clients wait or fail while the CPU is idle.
Wrongevents { }Rightworker_processes auto;worker_rlimit_nofile 16384;events { worker_connections 4096; }Reload without a test
minorA broken file leaves the old configuration running, and the next restart then fails.
Wrongnginx -s reloadRightnginx -t && nginx -s reloadRaising timeouts during overload
majorRequests wait longer, connections pile up and users retry.
Wrongproxy_read_timeout 300s;Rightproxy_read_timeout 10s;# plus a cache, a limit, or more servers
Interview tips
How to explain it
- A few workers, each with an event loop.
- It touches only connections that are ready.
- So slow clients are cheap.
Where state lives
- Idle upstream connections: per worker.
- Cache and limit zones: per machine.
- Nothing is shared between machines.
Reach for it when
- Several app servers need one door.
- Public pages see bursts.
- You want control over the edge.
Before production
- Two machines in two zones.
- nginx -t in the pipeline.
- Upstream time and status in the logs.