№ 07
15 min read

Waiting is not work

Most of the backends I have built follow the same shape. A request arrives. Application code runs. The database answers. A response goes back.

The framework hides almost everything between those steps.

This weekend, I went underneath it. I wanted to understand one idea properly: how an event-driven server keeps thousands of connections open with only a few threads.

The phrase event-driven architecture also names something larger: services that publish events, consumers that react to them, and queues between them. This entry is not about that. It stays inside a single server, at the level of sockets, threads, and the event loop. Martin Fowler, What do you mean by “Event-Driven”?

The easiest way to explain it is the way it finally made sense to me. Not as a definition, but as a mechanism, built one layer at a time.

Count the right thing first

Event-driven servers are often explained through the C10K problem: handling roughly ten thousand simultaneous connections on one machine. Event-driven programming did not start there, but C10K is where its value for servers is easiest to see. Dan Kegel, The C10K problem

The important word is simultaneous.

Ten thousand visitors in a day is not ten thousand connections. If a site has ten thousand daily visitors and two hundred connections open at this moment, the server is handling two hundred simultaneous connections. A count over a day and a snapshot of one instant answer different questions.

Even at one instant, users and connections do not map one to one. A browser can open several connections, reuse one for many requests, or close it between them. HTTP/2 can carry many streams over a single TCP connection. And one request may run several SQL queries, or none at all.

Before asking how a server handles load, the first question is which of these you are counting.

The thread that waits

The traditional answer to many connections is many threads. Give each connection a thread. The thread reads the request, runs the code, waits for the database, and writes the response.

A thread is an execution context inside a process: a program counter, registers, and a stack. The CPU executes its instructions when the operating system schedules it. A thread is not a CPU. One core can run many threads by switching between them.

The trouble is not that threads are slow. It is what they do while a request waits.

When a thread makes a blocking database call, the call does not return until the result arrives or the call fails. The operating system suspends the thread, so it uses almost no CPU. But that thread cannot handle anything else in the meantime. If three worker threads are all waiting on PostgreSQL, a fourth request has to queue, find another free worker, or be rejected.

Now scale it. Thousands of open connections, most of them idle or waiting, each holding a thread with its own stack and scheduling cost.

The machine is not busy.

It is occupied.

Who is actually doing the work?

This is the distinction everything else rests on.

When PostgreSQL is executing a query, the work is happening somewhere else: in another process, often on another machine. The application thread has nothing to compute. It is only waiting, and that waiting time can be given to another request.

When the application thread is computing something itself, parsing a large payload or running a calculation, there is no waiting time to give away. The thread is the one doing the work.

An event-driven server is built for the first case: it stops waits from occupying threads. It cannot make the second case finish any sooner. A calculation still needs the CPU time it needs.

Three terms follow from this:

  • Blocking I/O: the call does not return until the operation completes, fails, or times out. The calling thread is held for the whole wait.
  • Non-blocking I/O: the call returns immediately. If the operation cannot proceed yet, it says so, and the program tries again later.
  • Asynchronous programming: the operation stays pending while the caller does something else. A callback, promise, future, or coroutine represents the result that will arrive later.

A short Python program shows the difference. asyncio.sleep stands in for a database wait, and TaskGroup needs Python 3.11 or later:

import asyncio
import time
 
 
async def query(name, seconds):
    print(name, "sent")
    await asyncio.sleep(seconds)  # an external wait
    print(name, "ready")
 
 
async def main():
    start = time.perf_counter()
    async with asyncio.TaskGroup() as group:
        group.create_task(query("A", 0.3))
        group.create_task(query("B", 0.1))
        group.create_task(query("C", 0.2))
    print(f"total: {time.perf_counter() - start:.1f}s")
 
 
asyncio.run(main())
A sent
B sent
C sent
B ready
C ready
A ready
total: 0.3s

Three waits, one thread, 0.3 seconds. B finishes first because its wait is the shortest, not because of the order it was sent in. Python task groups

Replace await asyncio.sleep(seconds) with time.sleep(seconds) and the same program takes 0.6 seconds. Each wait now holds the thread, so the waits happen one after another. Replace it with a long calculation and the result is the same: the thread is busy, and nothing else runs.

Writing async def around a blocking call does not make the call non-blocking.

Follow one request

To see where the waiting actually happens, follow a single request.

Browser → application       HTTP, over the client connection
Application → PostgreSQL    SQL, over a separate database connection

The browser does not talk to the database. It sends an HTTP request to the application. Application code decides whether SQL is needed and, if so, sends it over a different connection to PostgreSQL. Two connections, two protocols, two lifetimes. Closing one does not close the other.

Each of those connections sits on a socket. When a database library connects, it asks the operating system to create a socket. On Linux, it receives a file descriptor: a small integer referring to an object the kernel manages. The library uses that handle to send, receive, and eventually close.

A socket is not yet a database session. The session begins after the connection is established: a database is selected, the user is authenticated, and TLS may be negotiated. The driver’s connection object carries that protocol and transaction state on top of the socket.

One port does not mean one connection either. PostgreSQL usually listens on port 5432. An application can open ten connections to that same port. Each has its own socket, told apart by the address and port on the application’s side.

ConnectionApplication sidePostgreSQL side
110.0.1.10:5100110.0.2.20:5432
210.0.1.10:5100210.0.2.20:5432
310.0.1.10:5100310.0.2.20:5432

A query sent on connection 2 receives its response on connection 2.

A pool decides who waits

Database connections are expensive to open and limited in number. PostgreSQL’s default max_connections is typically 100, though the value on a running server depends on how it was configured. Every session consumes server resources. PostgreSQL max_connections

So applications usually keep a connection pool: a bounded set of open connections that are lent out and returned. A request borrows one, runs its queries, and gives it back once it is safe to reuse. The next borrower may get a different connection.

This breaks another assumption. Threads, requests, and connections do not have to match:

  • 100 blocking threads can share 10 database connections. The threads queue for a connection.
  • One event-loop thread can coordinate 6 database connections.
  • 10,000 open HTTP connections can sit in front of 6 database connections, because most of those clients are not running a query at any given moment.

A connection is not free just because a query returned. A transaction may still be open. A result may still be streaming. An error may need a rollback. Release it too early and the next borrower inherits someone else’s state. Hold it too long and the pool runs dry.

When every connection is in use, the next request waits, times out, or is rejected. A pool does not create database capacity. It only decides who waits for it. Psycopg connection pools

How the server learns something is ready

This is where event-driven architecture gets its name.

When PostgreSQL finishes a query, it sends response bytes back over the connection. The operating system receives them and holds them in that socket’s receive buffer. Nothing in the application has run yet.

The application needs a way to ask the kernel which of its many sockets have something to read, without checking each one in turn. On Linux, that mechanism is epoll. macOS and the BSDs use kqueue. Linux epoll(7)

It comes down to three calls:

CallWhat it doesWhat it does not do
epoll_create1()Creates an epoll instanceOpen a database session
epoll_ctl()Adds, changes, or removes a descriptor to watchChoose a connection for a request
epoll_wait()Returns ready descriptors, or sleeps until one isRead the result or run your code

The application registers its interest explicitly. Sending SQL does not create a watch by itself. And epoll knows nothing about SQL, requests, or users. It reports that a descriptor is readable or writable, along with a value the application attached when it registered. The application uses that value to find its own connection object, and that object knows which request is waiting.

PostgreSQL sends bytes
→ Linux holds them in the socket's buffer
→ epoll reports the socket as readable
→ the driver reads and parses the bytes
→ the application resumes the waiting request

PostgreSQL never talks to epoll. It writes to a connection. The kernel notices the bytes. epoll tells whoever asked.

The older calls, select() and poll(), answer the same question, but the program hands over its full list of descriptors on every call. epoll keeps the list inside the kernel and returns only the ready ones. That difference matters when most of ten thousand sockets are idle.

Not every asynchronous operation is a socket waiting on epoll. libuv, the library underneath Node.js, runs file system operations and some DNS lookups on a small pool of helper threads, then reports the result back to the loop. Python’s asyncio can do the same with asyncio.to_thread. Something still waits on a thread. It is just not the event-loop thread. libuv design overview

Readiness is not completion

A readable socket means there are bytes to read. It does not mean the query has finished. The bytes may be part of one message, several messages, an error, or the other side closing the connection. The driver still has to read what is available, assemble complete protocol messages, and decide whether the operation a request is waiting for is done.

Data that has not been read does not disappear. It stays in the kernel’s buffer or the driver’s. Those buffers are finite. If the application stops reading, TCP slows the sender down, and a very large result can leave PostgreSQL waiting to send.

The event loop is not another worker

The piece that ties this together is the event loop. It is easy to picture it as a separate thing working alongside the thread.

It is not. The event loop is code running on the thread. The thread is what the operating system schedules. The event loop is the routine that thread repeats. Conceptually, it looks like this:

  1. Run the application work that is ready, until it finishes or suspends at an await.
  2. Perform whatever non-blocking reads and writes are possible, and update connection state.
  3. Let the driver mark finished operations, so the tasks waiting on them become ready.
  4. Run timers that are due.
  5. If nothing is ready, sleep in epoll_wait() until something is, or until the next timer.
  6. Repeat.

That is a model of the responsibilities, not the literal order. Node.js, through libuv, runs timers, I/O callbacks, and other work in fixed phases. Python’s asyncio arranges them its own way. What every loop shares is the shape: find ready work, run a bounded piece of it, remember what is still pending, and wait when there is nothing to do. libuv: the I/O loop

Step 5 matters. An idle event loop does not spin through every connection looking for results. It sleeps in the kernel and is woken when there is something to do. Blocking there is fine, because nothing else was ready. Blocking on one particular request while other work is ready is the mistake.

A callback, a handler attached to a promise, or the code after an await is the continuation: what should run once the result is available. epoll does not call it. The driver and the runtime arrange for it to run on the same thread when its turn comes.

Order is not guaranteed

Queries sent as A, B, and C over independent connections do not have to finish as A, B, and C. B may run a smaller query, avoid a lock, or hit cached data. The loop handles B as soon as B is ready, without waiting for A, unless the application itself makes B depend on A.

When several results are ready together, they are still handled one at a time. One thread runs one piece of code at a time. That is concurrency, many things in progress over the same period. It is not parallelism, many things executing at the same instant.

A burst, with numbers

The model is only useful if it survives a burst. Fix the assumptions:

  • 100 requests arrive, each needing one query.
  • One event-loop thread.
  • A pool of 6 database connections, each carrying one query at a time.

The first 6 requests get connections and send their queries. The other 94 wait for a connection. They have not reached PostgreSQL, and PostgreSQL cannot start work it has not received. Their state still costs memory, and their deadlines are still running.

If each query holds its connection for exactly one second, with no contention:

Rounds of queries:   ceil(100 / 6) = 17   → about 17 seconds
Throughput ceiling:  6 connections / 1 s  = 6 queries per second

Real queries vary, so connections free up at different times and new queries start between results rather than in neat rounds. The ceiling is the honest part: pool size divided by how long each request holds a connection.

Now change the design slightly. Suppose the application handles each result in two stages. When a query finishes, the loop reads the result, keeps it in memory, and returns the connection to the pool straight away. The CPU work on that result is queued for later.

Under that design, completed results can pile up beyond six. Six limits the queries running at once, not the results held in memory. Say 50 are waiting, and each needs 2 ms of CPU:

50 × 2 ms = 100 ms

The last one starts about 98 ms after the first. That is the cost of one thread handling ready work in sequence, and it is small.

Make each one need 5 seconds of CPU instead:

50 × 5 s = 250 s

Async does not shorten this. The waiting has already been shared. What is left is computation, and one thread computes one thing at a time.

Where that computation runs matters too. If each request does its CPU work the moment its query returns, a 5-second handler holds the loop for 5 seconds. During that time the loop cannot read the other results or return their connections to the pool. The connections stay held while the queue behind them grows.

There are two ways out, and they solve different problems. Breaking the work into chunks and yielding between them keeps the loop responsive, but the same thread still needs the full 250 seconds. Moving the work off the loop, to worker threads, a separate process, or a job queue, frees the loop and, where the runtime allows it, uses other cores. Node.js: Don’t block the event loop

What changed, and what did not

Thread per connectionEvent-driven
A worker is held for the whole I/O waitA task waits; the thread moves on to ready work
Many idle connections tie up many threadsMany idle sockets share a few threads
Worker count limits requests in flightCPU time, pool size, and queue limits still do
Other threads keep serving if one blocksOne blocking call or long handler stalls the loop

The last row is the trade. An event-driven server is very good at waiting, and fragile when something on the loop refuses to let go.

In under a minute

C10K is the problem of handling many simultaneous connections efficiently. A thread per connection wastes resources when most clients are waiting. An event-driven server uses non-blocking I/O and operating-system readiness notification, epoll on Linux, so a few threads spend their time only on work that is ready. Each thread still runs code one piece at a time. Database access needs an async path and a bounded pool. CPU-heavy work needs a separate strategy.

The result is efficient waiting, not unlimited parallel work.

Most of this stays hidden behind the framework, and it should. But the next time a server is slow while its CPU is almost idle, I know the first question to ask.

Is it waiting, or is it working?

A thread can give away its waiting.

It cannot give away its work.


— H.