Nginx as a reverse proxy
Upstreams, TLS termination, timeouts, buffering, headers that must be forwarded, and the 502 that was really a JVM pause.
nginx sits between the internet and the Java service: it terminates TLS, serves the static files, forwards /api to the JVM, adds the headers, and answers with a 502 when the JVM does not answer at all. Every backend engineer ends up reading its configuration during an incident, and this lesson is what that configuration means, using a typical one for a Java service.
What a reverse proxy is for
A forward proxy sits in front of clients; a reverse proxy sits in front of servers, and clients talk to it as if it were the server. In front of a Java service it does the work the JVM should not:
- TLS termination — certificates, ciphers, HTTP/2, renewal — in one place, so the service speaks plain HTTP on the loopback interface.
- Static files, from disk, at a speed and a memory cost no servlet container matches, so a typical setup sends only the API paths to the JVM.
- One public port in front of several processes, and the routing between them by path.
- Buffering slow clients so a worker thread in Tomcat is not held for the duration of a mobile upload.
- Limits — body size, request rate, connections — enforced before a request costs the JVM anything.
location /api/ {
proxy_pass http://127.0.0.1:8082;
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;
client_max_body_size 8m;
}
location / {
root /srv/app/current/site;
try_files $uri $uri.html $uri/index.html =404;
}TLS
listen 443 ssl http2;
ssl_certificate /etc/letsencrypt/live/code10x.in/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/code10x.in/privkey.pem;Certbot writes those lines and renews the certificate on a timer. The http2 flag on the listen line enables multiplexing for the static assets (the file's comment notes it is the 1.24 spelling; newer versions use http2 on;). Port 80 exists only to redirect to 443.
The security headers (HSTS, X-Content-Type-Options, the Content-Security-Policy) are added here on every response. In this repository they are generated from the same table next.config.mjs uses for development, so the two cannot disagree.
add_header has one trap worth knowing, which the generated file's comment states. A location that adds any header of its own drops the inherited ones, so the include appears in every such block.
Forwarded headers: the service must know who really asked
Behind a proxy, the connection the JVM sees comes from 127.0.0.1, over plain HTTP. If the application reads request.getRemoteAddr() it gets the proxy; if it builds an absolute URL it gets http://. The proxy_set_header lines carry the truth: X-Real-IP and X-Forwarded-For for the client's address, X-Forwarded-Proto for the scheme, Host for the name the client used. Spring reads them when told to — server.forward-headers-strategy=native for Tomcat's own valve, or framework for Spring's ForwardedHeaderFilter — and only then, because trusting X-Forwarded-For from an arbitrary client is how rate limits and audit logs get a forged address. This repository's throttles read X-Real-IP, else the last X-Forwarded-For entry — the one nginx appended — and never the first, which the client controls; the learner-test that checks this names exactly that reason.
Timeouts and buffering
Three timeouts on the proxy side, and they must agree with the JVM's:
proxy_connect_timeout— to open the connection to the upstream (seconds; the JVM is on loopback, so a failure here is "not listening").proxy_read_timeout— between two reads from the upstream, default 60 s. A request the JVM takes 90 s to answer is a 504 from nginx at 60 s while the JVM keeps working, which is the microservices course's "timeout that was measured, then wrong" from the other side. Set it at or above the slowest legitimate request, and make that request faster instead.proxy_send_timeout— between two writes to the upstream.
Buffering (proxy_buffering on, the default) reads the upstream's whole response into memory or a temp file and then sends it to the client at the client's pace, freeing the JVM's thread early. That is right for a JSON API. It is wrong for a server-sent event stream or a large download, where proxy_buffering off (or X-Accel-Buffering: no from the application) streams through.
client_max_body_size is the request-body cap, 8 MB here for cover uploads. Exceeding it is a 413 from nginx before the JVM sees a byte. proxy_request_buffering is the same idea for uploads.
Reading a 502, a 504 and a 499
- 502 Bad Gateway — nginx could not get a valid response: the upstream is not listening (the JVM is restarting — the deploy script's few-second window), refused the connection, closed it mid-response, or answered with something nginx could not parse.
systemctl statusthe service,ss -tlnp | grep 8082, then nginx's error log:connect() failed (111: Connection refused)is the JVM down;upstream prematurely closed connectionis the JVM dying mid-request, usually the OOM killer, so the kernel log is next. - 504 Gateway Timeout — the upstream was reached and did not answer within
proxy_read_timeout. The JVM is alive and slow: a thread dump or the slow-query checklist from the production course. - 499 — nginx's own code for the client went away before the response; a burst of them means clients timing out on their side, which is a latency problem that the 504s have not caught yet.
- 413 — the body limit above. 404 on a static site is
try_filesfinding nothing, and a build check that every promised page is on disk before the switchover is how you keep it from happening.
The two logs: /var/log/nginx/access.log with the status, the upstream time ($upstream_response_time, worth adding to the log format) and the request; /var/log/nginx/error.log with the reason. nginx -t validates a configuration before systemctl reload nginx applies it without dropping connections — which is what the deploy script runs, in that order, at every switchover.
Under the hood: how a handful of nginx processes hold thousands of connections
nginx starts one master process (reads the config, opens the listening sockets, manages the workers) and a small number of worker processes. The usual number is one per CPU core (worker_processes auto;), because a worker is CPU-bound between I/O waits, and more workers than cores just adds context-switching.
That number looks tiny next to "thousands of concurrent connections". The reason it is enough is that each worker is not one thread per connection. It is a single-threaded event loop built on the operating system's async I/O multiplexing facility (epoll on Linux, kqueue on BSD).
A thread-per-connection server (the classic Apache prefork model, or a naive servlet container's request-handling thread pool) blocks a whole OS thread on each connection's socket read or write. An idle keep-alive connection still owns that thread's stack (typically hundreds of kilobytes to a few megabytes), and costs the kernel a context switch every time the scheduler visits it. That is why such a server runs out of threads, and then memory, long before it runs out of CPU.
nginx's worker works differently. It registers every socket it is watching with epoll, and makes one call that returns only the sockets that actually have something ready: a request arrived, a write buffer drained, a connection closed. Then it services exactly those, in a tight loop, on one thread. A connection sitting idle between keep-alive requests costs the worker almost nothing: a file descriptor and a small amount of state, not a blocked thread.
This is the answer to the historical "C10K problem" (ten thousand concurrent connections defeating thread-per-connection servers). It is why a handful of nginx workers routinely hold tens of thousands of connections that a thread-per-connection model could not.
proxy_pass fits into the same loop. nginx is simultaneously a server to the client and a client to the upstream, and both of those sockets are handled by the same non-blocking event loop. nginx does not block one connection waiting on the other. That is what lets it buffer a slow client's request without holding up a fast upstream, or buffer a slow upstream's response without holding up a fast client (the buffering behaviour this lesson covers above).
An upstream block with keepalive reuses already-open TCP connections to the upstream across requests, instead of opening a new one each time. That matters because a fresh connection costs a TCP handshake (and a TLS handshake, if the hop to the upstream is encrypted) before a single byte of the actual request goes anywhere.
Try it yourself
Why 4 nginx workers can outperform 4,000 Java threads at the same connection count
A Java service using a classic thread-per-connection model (one thread blocked on each open socket) is compared against nginx with 4 worker processes. Both hold 4,000 simultaneous keep-alive connections. Most are idle at any given instant, and only a few have data to read or write right now.
Using the event-loop mechanics above, reason about what each server is actually doing with its CPU and memory at that moment, and why the Java model's problem gets worse as connection count grows while nginx's mostly does not.
Where the cost actually comes from
The Java thread-per-connection model pays for every one of the 4,000 connections all the time. 4,000 OS threads exist, each with its own stack reserved in memory, whether or not that connection currently has anything to do. The OS scheduler has to consider all 4,000 when deciding what to run next, context-switching among threads that are mostly just blocked waiting on an idle socket. The cost scales roughly with the number of connections, active or not.
nginx's 4 workers pay only for the connections that currently have something ready. Each worker's single epoll_wait call returns just the handful of sockets (out of however many thousand it is watching) that actually became readable or writable since the last check. The worker's one thread processes only those before calling epoll_wait again.
The cost scales with the number of events, not the number of open connections: an idle connection sits in the kernel's watch set essentially for free. That is why doubling the idle-but-open connection count barely moves nginx's CPU usage, while doubling it for the thread-per-connection model roughly doubles the number of threads the scheduler is juggling.
Misconceptions
- "nginx is fast because it's multi-threaded." Each worker process is, by design, essentially single-threaded for the connection-handling event loop — that is the source of the performance, not a limitation on it. (Later nginx versions added a small thread pool for specific blocking operations like disk reads on cold cache files, but the connection-handling loop itself stays single-threaded per worker.)
- "Adding more worker_processes than CPU cores gives more throughput." Past the core count, extra workers compete for the same CPUs the existing workers already saturate between them. They add scheduling overhead without adding capacity to do work.
worker_processes autopicks the core count for exactly this reason.
Sources
- nginx documentation, "Beginner's Guide" — the master/worker process model and how a worker processes connections.
man 7 epoll— the readiness-notification model nginx's event loop is built on.- Dan Kegel, "The C10K problem" — why thread-per-connection stops scaling and what an event-driven server does instead.