Sync vs async: who waits, and on what

Most of a web request is waiting: for a database, another service, a disk. Serve the same requests with a thread each, a small pool and an event loop, and watch where the waiting goes.

Level: IntermediateWatch: 13 steps · ~80 secondsThree ways, three loadsRecall: 3 questions · 8 cardsCompare 3 waysPython · TypeScript · Go

What you'll take away

  • Explain what blocking means: a thread asleep, doing nothing, through every wait
  • Work out why a pool of 4 threads leaves the 16th request waiting over a second
  • Know why async doesn't make a request faster, only lets one thread hold many waits
  • Keep heavy work off an event loop by moving it to a worker thread or another process

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
A thread per request8 requests, 60 ms apart · blocking calls: the thread sleeps until the answer
1 thread
in line · nobody
database · answers in 300 ms
clients
#1
#1 comes in → …
Step 1 / 13 · step by step
0 msModel time
1Threads used
0Threads asleep
0In line for a thread
0 / 8Answered

The picture: the server's hall. Each desk is a thread: lit while it computes, dashed with a "z" while it sleeps through a blocking call, faded once the thread is gone. The event loop is one desk, and the waits it hands off sit in the kernel's box. Requests are lights: on the bench while they wait their turn, across the street at the database while they wait on it, back in the square once answered. Model milliseconds (300 ms on the database), not a measurement.

Step 4 · Every option at once, on one clock

Compare them all: Sync vs async

The same request, 10 ms of work, 300 ms waiting on the database, 10 ms more, sent to three servers: steady, a burst, and one heavy CPU job. Each bar is the slowest request; the number is the threads it took.

1/3 · 8 requests, 60 ms apart
A thread per requestblocking calls: the thread sleeps until the answerslowest …

Use it when The easiest code to read, line after line. With cheap threads (Java 21's virtual threads, Go's goroutines) it goes a long way

Skip it when Thousands of OS threads: each has its own stack (1 MB reserved by default for Java on Linux x64), and the OS switches between them

A model: a machine with four cores, and the model's milliseconds, not a measurement. The code below really runs all three. Press any tile to see it large above, with when it fits.

Three ways to serve requests that wait

WayWhile a request waitsSuitsGoes wrong when
a thread per requestits thread sleepscode read line by line; cheap threads (goroutines, Java 21 virtual threads)thousands of OS threads, each with its own stack
a fixed poola pool thread sleeps; the rest queuebounding resources, like database connectionsmore waiting work than threads
an event loopthe wait is parked with the kernel; the thread runs otherswork that mostly waits on the networkheavy computing on the loop

Waiting vs computing

Async helps only with waiting. A thread that computes is busy whatever you call it, so heavy work on an event loop holds back every answer that arrives meanwhile. Move it to a worker thread or another process, and keep the loop for waiting.

The threads Node really uses

Your JavaScript runs on one thread. Network sockets are watched by the kernel (epoll, kqueue), and libuv runs the file system, dns.lookup, some crypto (pbkdf2, scrypt) and zlib on a pool of 4 threads, changed with UV_THREADPOOL_SIZE (libuv: thread pool, Node.js: don't block the event loop).

Cheap threads

An OS thread reserves its own stack: by default 1 MB for Java on Linux x64 (java -Xss). Goroutines and Java 21's virtual threads (JEP 444) are cheap threads the runtime parks while they wait, so blocking-style code can serve many at once.

In real code

four_ways.py
# The same I/O job four ways: 8 queries to a "database" that answers after 300 ms (a real TCP server on 127.0.0.1).
# Blocking calls on one thread, a pool of 4 threads, a thread per query, and asyncio (one thread, non-blocking
# sockets). Then a 0.8 s CPU job on the asyncio loop, and the same job moved off it to another process
# (a thread would still share Python's GIL with the loop).
# Run: python3 four_ways.py
import asyncio
import socket
import socketserver
import threading
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

N, DB_WAIT = 8, 0.3


class SlowDB(socketserver.BaseRequestHandler):
    def handle(self) -> None:
        self.request.recv(64)
        time.sleep(DB_WAIT)  # the database thinks for 300 ms
        self.request.sendall(b"row\n")


def query(port: int) -> bytes:
    """A blocking call: the thread stops here until the answer arrives."""
    with socket.create_connection(("127.0.0.1", port)) as s:
        s.sendall(b"SELECT 1\n")
        return s.recv(64)


async def aquery(port: int) -> bytes:
    """A non-blocking call: while it waits, the loop runs other coroutines."""
    reader, writer = await asyncio.open_connection("127.0.0.1", port)
    writer.write(b"SELECT 1\n")
    row = await reader.readline()
    writer.close()
    await writer.wait_closed()
    return row


def timed(fn) -> float:
    t0 = time.perf_counter()
    fn()
    return time.perf_counter() - t0


def crunch(seconds: float) -> None:
    """Pure CPU work (resizing an image, hashing): nothing to wait for."""
    t0 = time.perf_counter()
    while time.perf_counter() - t0 < seconds:
        pass


async def with_heavy(port: int, cpus: ProcessPoolExecutor | None) -> float:
    t0 = time.perf_counter()
    async def one() -> float:
        await aquery(port)
        return time.perf_counter() - t0
    tasks = [asyncio.create_task(one()) for _ in range(N)]
    await asyncio.sleep(0.01)  # the queries are on their way
    if cpus:
        await asyncio.get_running_loop().run_in_executor(cpus, crunch, 0.8)  # another process computes; the loop stays free
    else:
        crunch(0.8)  # the loop itself computes: answers that arrive meanwhile wait
    return max(await asyncio.gather(*tasks))


def main() -> None:
    socketserver.ThreadingTCPServer.allow_reuse_address = True
    socketserver.ThreadingTCPServer.request_queue_size = 64  # the default backlog of 5 refuses 8 at once
    with socketserver.ThreadingTCPServer(("127.0.0.1", 0), SlowDB) as db:
        threading.Thread(target=db.serve_forever, daemon=True).start()
        port = db.server_address[1]

        one = timed(lambda: [query(port) for _ in range(N)])
        with ThreadPoolExecutor(max_workers=4) as pool:
            pooled = timed(lambda: list(pool.map(lambda _: query(port), range(N))))

        def each() -> None:
            ts = [threading.Thread(target=query, args=(port,)) for _ in range(N)]
            for t in ts:
                t.start()
            for t in ts:
                t.join()
        per_thread = timed(each)

        async def all_async() -> None:
            await asyncio.gather(*(aquery(port) for _ in range(N)))
        on_loop = timed(lambda: asyncio.run(all_async()))
        blocked = asyncio.run(with_heavy(port, None))
        with ProcessPoolExecutor(max_workers=1) as cpus:
            cpus.submit(int).result()  # the process is up before the clock starts
            freed = asyncio.run(with_heavy(port, cpus))
        db.shutdown()

    assert 2.3 < one < 3.0, one  # 8 × 300 ms, one after another
    assert 0.55 < pooled < 0.9, pooled  # two rounds of 4
    assert 0.28 < per_thread < 0.5 and 0.28 < on_loop < 0.5, (per_thread, on_loop)
    assert blocked > 0.75 and freed < 0.5, (blocked, freed)
    print(f"8 queries of 300 ms: blocking on one thread {one:.1f} s · pool of 4 {pooled:.1f} s · a thread each {per_thread:.1f} s"
          f" · asyncio on one thread {on_loop:.1f} s · a 0.8 s CPU job on the loop: queries take {blocked:.1f} s, in another process {freed:.1f} s")


if __name__ == "__main__":
    main()
Run: python3 four_ways.pyIt printed: 8 queries of 300 ms: blocking on one thread 2.4 s · pool of 4 0.6 s · a thread each 0.3 s · asyncio on one thread 0.3 s · a 0.8 s CPU job on the loop: queries take 0.8 s, in another process 0.3 s

8 queries to a real TCP "database" that answers after 300 ms: blocking calls on one thread, a pool of 4, a thread each, and asyncio on one thread. Then 0.8 s of computing on the asyncio loop holds every query back; the same work in another process doesn't. Python's standard library, really run (times rounded to 0.1 s).

Common questions

What's the difference between sync and async?

Sync code waits for the result before the next line; async code starts the work and moves on, with the result coming later through a callback, a promise or await. What really changes is whether the thread sleeps through the wait (blocking) or is free for other work (non-blocking).

Does async make a request faster?

No. The database answers just as slowly and each request takes just as long. What you gain is serving many at once without a thread for every wait.

What's wrong with a thread per request?

The code is the easiest to read, but each OS thread has its own stack (Java reserves 1 MB on Linux x64) and the OS switches between them; ten thousand mostly sleeping threads weigh a lot. With cheap threads, like Java 21's virtual threads or Go's goroutines, this style goes a long way.

Doesn't a thread pool solve it?

A pool bounds the number of threads, but if each still sleeps through a blocking wait, work beyond the pool's size queues. A pool of 4 meeting 16 requests that wait 300 ms each leaves the last one waiting over a second.

How does one event loop thread wait on many things at once?

It doesn't do the waiting itself. Every socket is parked with the kernel (epoll on Linux, kqueue on macOS); the loop asks which are ready and carries each on in turn. While none is ready, the thread is free.

Why does heavy work in Node slow every request?

Node runs JavaScript on one thread, so a database answer that has arrived waits until the loop is free. A 400 ms computation on the loop makes everyone behind it late too. Move it to worker_threads or another process.

Read: waiting vs computing

Is Node really single-threaded?

Your JavaScript runs on one thread, but libuv keeps a thread pool, 4 by default, for work with no non-blocking form: the file system, dns.lookup, crypto.pbkdf2 and zlib. Network I/O goes to the kernel directly, not through the pool.

Which should I pick?

For work that mostly waits on the network (APIs, proxies, chat), an event loop or cheap threads. For heavy computing, threads or processes up to the number of cores. Real systems usually do both: a loop takes the requests and hands heavy work elsewhere.

Table: which way suits which work

Next lesson

Sizing a systemLevel: Intermediate

How many threads or connections you need is rate × wait; next, Little's law and the rough numbers that size a system before you build it.