NGINX: How One Worker Handles Thousands of Connections

Outline

Transcript

0:00 NGINX is a web server that answers HTTP requests. We'll follow one unfinished request through its worker, the process handling that traffic, to see how it keeps serving other clients. Our test held 3,000 incomplete requests while 12 other clients got replies. My first thought is a thread waiting behind each slow client. Where are those threads? There's just one worker thread. NGINX keeps each client's progress in memory while the worker handles other work. Now follow an unfinished client from our test.

0:31 It sent headers without their final empty line and kept its socket open. Right. A master process manages configuration and workers; our thread count describes just this worker. We traced the signed NGINX source and Linux's epoll manual; version and code links are in the description. Epoll reports readiness, a signal to try reading or writing a socket. Now follow that same client's bytes. It sends a request line and its header lines, including the host name. Then it omits the blank line that ends the headers.

1:01 So bytes have arrived, but NGINX can't yet treat the headers as complete. The connection exists before there's a complete request to handle. Exactly. NGINX accepts a socket and keeps a connection structure. Its file descriptor is the process's handle for that socket. The handle identifies the open connection. What remembers where the unfinished request got to? Request state and buffers. They retain the parsing progress and received bytes, so later work can continue from there. So that parsing state keeps the client's place.

1:33 But what lets the read call return instead of occupying the worker until the remaining bytes arrive? With a nonblocking socket, a read can instead say that no more bytes are available now. NGINX calls that a try-again result. And then the function returns, while the connection and its request state stay alive. Execution can move on without forgetting the client. Yeah. Think of one clerk whose desk has 3,000 numbered open folders. A folder can retain an unfinished application without the clerk holding it until its owner comes back. I like that: the clerk can put the unfinished form down.

2:08 But the folder doesn't ring a bell on its own. How does NGINX know which socket to revisit? It asks the operating system for readiness notifications. That's the step that lets the worker find useful work among all those open connections. So a readiness event has to get NGINX back to the right client's saved state. Does it have to search every open connection to find our client? NGINX attaches a connection reference when it registers a socket. Linux returns that reference with a ready event. NGINX checks that it's still current, then reaches the read handler.

2:42 Ah, Linux is handing back NGINX's own reference. That handler is a callback, a function the worker invokes for this connection. Calling it doesn't create another thread. Right. That identifies a connection, not a finished request. Let's give our client another fragment and see what arrives. Now suppose our incomplete client sends another header line, but still no final blank line. The socket can become readable because there are bytes to read. Reading those bytes still leaves the headers incomplete.

3:10 The kernel hasn't promised an HTTP message. One new page can make a folder worth checking without completing the application. The header reader keeps a timeout on this wait and asks for notification when the socket can be read again. Then it returns try-again. Then its caller stops that round of header work and the event loop gets control back. Needing more bytes doesn't become a waiting thread. Readiness can also accompany closure or errors. The handler still needs to inspect what happened. For a concrete case, return to our local test.

3:44 It doesn't tell us production speed. We sent complete requests on 12 other connections while the held set still had incomplete headers. Each got a successful response with a tiny body. Afterward, the worker still owned 3,000 established connections and still had one thread. That's the combination I wanted to see, with the waiting clients keeping their state while those 12 replies get out. And when we finally sent that missing blank line? Then NGINX replied on that connection and kept the socket open.

4:13 Nice, that's the request we left unfinished. The installed handler picks up where parsing stopped. But we haven't closed that connection yet. Does completing the request mean the socket's job is over? With HTTP keep alive, no. The socket can remain open after a response. NGINX changes what its read handler is waiting for: another request. We used that same socket for a second complete request. It got another successful response, then closed. The other 2,999 incomplete connections remained. The connection is an open socket.

4:46 Each request is one HTTP operation carried over it. Their lifetimes differ: an operation can finish while the connection stays open. Think of one numbered folder holding two successive applications. Counting folders doesn't tell us how many applications finish each minute. Another place to retain unfinished work is output. For example, a client may receive a response slowly, even after NGINX has produced the content. Does the worker have to finish writing every byte before it can return to the other connections? No. Suppose a reply has two parts: one written, one still pending.

5:20 NGINX retains the unsent buffer state and continues through writable-event handling. Writable still means try, not a promise to finish. Ah, the clerk can leave the second reply page in that client's folder and handle someone else. The code shows that path. Our tiny replies didn't fill a send buffer, so we didn't test a slow reader. So we can leave reads or writes pending. Now suppose two clients are ready together. I think we've let the clerk off rather easily. What happens when both clients need the worker's CPU time at once?

5:52 When the code calls a handler directly, the loop needs control back before calling another. CPU work inside that function can keep the second client waiting, even though it's ready. NGINX can use several workers for more CPU cores, and some file operations can use helper thread pools. It doesn't need a dedicated waiting thread per connection. We still owe those 3,000 folders some shelf space, though. Let's look at what the open connections keep using while their clients wait. But a waiting client still costs the worker resources.

6:23 A connected client occupies one socket at NGINX. If NGINX forwards its request to another server, the connection to that upstream server occupies another. Oh, the same worker has connections on both sides. I'd have counted only incoming clients. Right. Worker connections is NGINX's configured limit on simultaneous connections in a worker, including upstream sockets. Returning from code also leaves socket handles and state in memory. Our test used only client connections. It needed enough worker connection slots and a high enough process limit on open sockets and files.

6:56 We raised that process limit only for the test; it isn't production advice. Suppose an on-call engineer says, 'I'll raise the connection limit to finish more requests.' What does that actually buy? It can admit more connections if slots were the constraint. More slots add places to keep folders, not another clerk. Even with plenty of connection slots, one worker has only so much CPU time. Many ready connections still have to share it. Then the opening count makes sense. 3,000 connections kept their state while one worker handled ready work, including those 12 complete requests.

7:30 And one waiting client resumed when its missing bytes arrived, then reused the same socket. If we're watching open connections climb on a dashboard, we need to separate clients holding state from requests needing CPU time. That's how one worker can handle thousands of connections without doing thousands of CPU tasks at once. Thanks for listening to Learning Podcasts.