how-one-server-handles-thousands-of-connections.md

← Writing Desktop 17 min read

How one server handles thousands of connections

A server that talks to one client at a time is easy to write. Here is why it breaks, the two usual fixes, and what each one costs, measured with 5,000 connections.

Created
Nov 30, 2026
Reading
17 min
Labels
networkingbackend

In the last post we wrote a small server and talked to it with nc. It worked, but it had a quiet limit: it could only deal with one client at a time.

A real server has thousands of people connected at once. Most of them are doing nothing at any given moment, a few are sending a request, and every one of them expects an answer right away. This post is about how a server copes with that.

I’ll start with the simple server and show where it fails. Then there are two ways to fix it, and I measured both with 5,000 connections. You do not need to know anything about threads or operating systems first. I’ll explain each term when it comes up, and every demo ran in a Debian container so you can repeat it.

The problem: one client at a time

Here is a server that shouts back whatever you send it. It turns the text to upper case and returns it:

import socket

srv = socket.socket()
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 9000))
srv.listen(1000)

while True:
    conn, addr = srv.accept()          # waits here for a client
    while data := conn.recv(1024):     # waits here for that client to speak
        conn.sendall(data.upper())
    conn.close()

Two lines in that loop wait. accept() waits until a new client connects. recv() waits until the client sends something. The word for this is blocking: the program stops at that line and does nothing else until the thing it is waiting for happens.

That is fine with one client. With two, it is a problem. Let’s start the server, connect a client that says nothing, and then try a second client:

$ python3 blocking.py &
$ python3 holder.py &          # connects, then sits there silent for 8 seconds
$ python3 client.py hello      # sends "hello" and waits for the answer
no reply after 5 seconds

The second client never got an answer. The server was stuck in recv(), waiting for the first client to speak, and it had no way to look at anyone else.

client A connected, says nothing client B sends "hello", waits for a reply server blocked in recv(), waiting for client A time →
The server can only wait on one socket at a time, so client B sits in line behind a client that is doing nothing.

One more detail. Client B’s connect() did succeed. The operating system accepts new connections into a waiting queue on its own, even when your program is not calling accept(). So the client thinks it is connected, and the silence only shows up when it asks for something.

Fix one: a thread for every client

The first fix is the one most people think of. Give each client its own worker, so a worker that is stuck waiting only blocks itself.

A thread is one of those workers. It is a separate line of execution inside the same program. Several threads can run at the same time, and each one can be stuck in its own recv() without affecting the others.

import socket
import threading

def handle(conn):
    while data := conn.recv(1024):
        conn.sendall(data.upper())
    conn.close()

srv = socket.socket()
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 9000))
srv.listen(1000)

while True:
    conn, addr = srv.accept()
    threading.Thread(target=handle, args=(conn,), daemon=True).start()

The only change is the last line. Instead of handling the client itself, the main loop starts a new thread for it and goes straight back to accept(). Same test as before:

$ python3 threaded.py &
$ python3 holder.py &
$ python3 client.py hello
reply: b'HELLO\n' after 0.00 s

The second client gets its answer immediately. For a lot of programs this is a perfectly good place to stop.

What threads cost

Each thread needs memory for its own stack and its own bookkeeping, and the operating system has to switch between them. With ten clients you will never notice. With thousands, you might.

I wrote a small script that opens a lot of connections, keeps them all open, and then reads the server’s thread count and memory from /proc:

import socket, sys, time
n, pid = int(sys.argv[1]), sys.argv[2]
t = time.time()
socks = [socket.create_connection(("127.0.0.1", 9000)) for _ in range(n)]
print("opened %d connections in %.2f s" % (n, time.time() - t))
time.sleep(1)
st = dict(l.split(":", 1) for l in open("/proc/%s/status" % pid) if l.split(":")[0] in ("Threads", "VmRSS"))
print("server:", "threads =", st["Threads"].strip(), "| memory (RSS) =", st["VmRSS"].strip())
t = time.time()
for s in socks: s.sendall(b"hi\n")
ok = sum(1 for s in socks if s.recv(10) == b"HI\n")
print("%d of %d answered, %.2f s for the whole round" % (ok, n, time.time() - t))

Run against the threaded server with 5,000 clients:

$ python3 load.py 5000 $SERVER_PID
opened 5000 connections in 4.34 s
server: threads = 5001 | memory (RSS) = 166496 kB
5000 of 5000 answered, 0.10 s for the whole round

It worked. All 5,000 clients got an answer. But the server now has 5,001 threads and about 163 MB of memory, and most of that is just waiting. (RSS is the memory the process is actually using right now.)

Nothing here is broken, and for a few hundred connections it would not matter. The point is the shape of the cost: it grows with every connection, even the ones that do nothing.

Fix two: one thread, many sockets

The other approach starts from a different question. Why does the server need a worker per client, when most clients are silent most of the time?

Imagine a waiter in a restaurant. One way is to assign a waiter to each table, who stands there until the table orders. Another is a single waiter who walks the room and only goes to the tables where someone has raised a hand. The second waiter can look after far more tables.

a thread per client A B C thread 1 thread 2 thread 3 each one waits on its own socket an event loop A B C one threadasks the OS:"who is ready?" one thread watches every socket
Same clients, two designs. The event loop only does work for the sockets that have something to say.

For a server, “raising a hand” means a socket has data waiting. You ask the operating system, “here is my list of sockets, tell me when any of them is ready”, and the program sleeps until the answer comes. This design is called an event loop, and the Linux feature behind it is called epoll. Python hides the details behind a module called selectors:

import selectors
import socket

sel = selectors.DefaultSelector()

srv = socket.socket()
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 9000))
srv.listen(1000)
srv.setblocking(False)
sel.register(srv, selectors.EVENT_READ)

while True:
    for key, _ in sel.select():            # sleeps until some socket is ready
        sock = key.fileobj
        if sock is srv:
            conn, addr = srv.accept()      # a new client: will not block
            conn.setblocking(False)
            sel.register(conn, selectors.EVENT_READ)
        else:
            data = sock.recv(1024)         # data is already waiting: will not block
            if data:
                sock.sendall(data.upper())
            else:
                sel.unregister(sock)
                sock.close()

This is longer than the other two. We tell the selector which sockets we care about (register). Then sel.select() sleeps until at least one of them is ready and returns only the ready ones. For each one, we do the work. If it is the listening socket, a new client is waiting, so we accept it and add it to the list. If it is a client socket, there is data waiting, so we read it and reply.

Because we only touch sockets the operating system says are ready, accept() and recv() never have to wait. That is what the setblocking(False) lines are about.

The same test gives the same result as the threaded server:

$ python3 evented.py &
$ python3 holder.py &
$ python3 client.py hello
reply: b'HELLO\n' after 0.00 s

Watching epoll with strace

If you read my strace post, you can look at what this server asks the operating system. This is one client connecting, sending hi, getting HI back, and leaving:

$ strace -f -e trace=epoll_ctl,epoll_pwait,accept4,recvfrom,sendto python3 evented.py
epoll_ctl(3, EPOLL_CTL_ADD, 4, {events=EPOLLIN, data=0xffff00000004}) = 0
epoll_pwait(3, [{events=EPOLLIN, data=0xffff00000004}], 1, -1, NULL, 8) = 1
accept4(4, {sa_family=AF_INET, sin_port=htons(60000), sin_addr=inet_addr("127.0.0.1")}, [16], SOCK_CLOEXEC) = 5
epoll_ctl(3, EPOLL_CTL_ADD, 5, {events=EPOLLIN, data=0x5}) = 0
epoll_pwait(3, [{events=EPOLLIN, data=0x5}], 2, -1, NULL, 8) = 1
recvfrom(5, "hi\n", 1024, 0, NULL, NULL) = 3
sendto(5, "HI\n", 3, 0, NULL, 0)  = 3
epoll_pwait(3, [{events=EPOLLIN, data=0x5}], 2, -1, NULL, 8) = 1
recvfrom(5, "", 1024, 0, NULL, NULL) = 0
epoll_ctl(3, EPOLL_CTL_DEL, 5, 0xffffe9d56210) = 0

I trimmed the start-up lines and shortened some. In that trace:

  • epoll_ctl(... ADD, 4 ...) registers socket 4, the listening one. This is sel.register(srv, ...).
  • epoll_pwait is the program sleeping. It comes back when socket 4 has a visitor, and accept4 then returns the new client as socket 5.
  • Socket 5 gets registered the same way. The next epoll_pwait returns when it has data, then recvfrom reads hi and sendto writes HI.
  • The last recvfrom returns 0, which means the client hung up, so socket 5 is removed with EPOLL_CTL_DEL.

The -1 in epoll_pwait means “wait as long as it takes”. The name might be epoll_wait on some systems, since it depends on the kernel and architecture. This one ran on arm64.

The code was selectors.DefaultSelector, and I did not pick epoll myself. On Linux, Python chose it for me (the class was EpollSelector). On macOS it uses a different mechanism called kqueue, with the same idea.

The same 5,000 connections

Now the same load script against the event-loop server:

$ python3 load.py 5000 $SERVER_PID
opened 5000 connections in 0.07 s
server: threads = 1 | memory (RSS) = 11232 kB
5000 of 5000 answered, 0.04 s for the whole round
5,000 connections thread per client event loop
Threads in the server 5,001 1
Memory about 163 MB about 11 MB
Time to open them all 4.34 s 0.07 s
Time to answer all of them 0.10 s 0.04 s

An idle event-loop server with no clients used about 9.7 MB. Counting from that, the threaded server spent roughly 30 KB per connection and the event loop a bit under 0.3 KB.

Take these numbers as a rough picture, not a benchmark. The client and server shared one machine and talked over the loopback address, so there was no real network. It was Python 3.13 in a Debian container, and your machine will give different figures. The ratio between the two is the interesting part. There was another limit I had to raise: every open connection uses a file descriptor, and each process is allowed only so many (ulimit -n). I set it to 65,536 for this test.

The catch: one slow handler

The event loop is not free. It works because every handler is quick. There is only one thread, so if one handler takes a long time, everything else waits for it.

I changed the event-loop server so that a message starting with slow makes the handler sleep for 3 seconds, as if it were doing heavy work. Then I sent one slow request and, half a second later, a normal hi:

$ python3 client.py slow &
$ python3 client.py hi
reply: b'SLOW\n' after 3.01 s
reply: b'HI\n' after 2.50 s

The hi was a fast request, but it took 2.5 seconds because it had to wait behind the slow one. This is the same symptom as the very first demo, in a smaller form.

server A B C: slow work, 3 seconds D client D arrives, but has to wait time →
With one thread, the handlers run one after another. A single slow handler holds up everyone behind it.

This is the rule behind a piece of advice you will hear a lot in Node.js and Python’s asyncio: do not block the event loop. If a handler has to do something slow, hand it to another thread or process, or split it into small steps.

That also means threads are still the right tool in some places. If each request does a lot of work on the CPU, or you only have a few clients, a thread per client is simpler to write and to reason about.

Where you have already met this

The event loop is not a trick for one server. It is how much of the software you use is built:

  • Node.js runs your JavaScript on a single thread with an event loop underneath (a library called libuv, which uses epoll on Linux).
  • nginx handles many connections per worker process with the same idea.
  • Redis runs its commands on one event-loop thread.
  • Python’s asyncio is built on the same selectors module we just used.
  • Go does it differently. Your code looks like a thread per client, but the runtime multiplexes goroutines on top of epoll for you.

The problem has a name too. In 1999 Dan Kegel wrote an article called “The C10K problem”, which asked how a single server could handle ten thousand clients at once. That was hard at the time. The event-loop server above handled half of that in well under a second.

Try it yourself

Everything above is about 100 lines of Python in total. To get a feel for it:

  1. Start threaded.py, then run the load script with 500 clients and watch the thread count with ps -o nlwp -p <pid>.
  2. Run the same test against evented.py and compare.
  3. In evented.py, add time.sleep(3) to the handler and see how a second nc session freezes.

If you want to go one level further down, run strace -c on both servers while the load runs and compare the system calls each one makes.

The numbers and output above came from Python 3.13.5 on Debian, in an arm64 container with the open-file limit raised to 65,536.

← All writing Share on LinkedIn RSS