← Building blocks

Do not block on I/O

Latency & performancesenior

A server thread sits idle waiting on the network while other requests queue.

Say it like this

A connection server holds 250,000 mostly idle WebSockets, so I run it on an event loop with non-blocking I/O: one process waits on all sockets at once and only spends CPU when bytes actually arrive.

Basic solution

Use non-blocking I/O or an event loop so one process handles many concurrent connections.

Node.jsNettyGo goroutinesTokioasyncio

One loop, many idle sockets

The loop blocks in epoll until sockets are ready, runs short handlers for each, and offloads slow or CPU-heavy work. Nothing on the loop ever waits on the network.

How it works

  1. Register every socket with the kernel's readiness mechanism (epoll on Linux, kqueue on BSD, or io_uring for completion-based I/O) instead of giving each connection its own thread. The kernel now tracks which sockets have data waiting.
  2. The event loop makes one system call that blocks until some sockets are readable or writable, and returns with the list of the ones that are ready. One call covers all 240,000 sockets.
  3. For each ready socket the loop runs a short handler: read the frame from the socket buffer, decode it, enqueue whatever work it implies, and write a response if one is ready. Handlers never wait on anything; a slow operation such as a database write is started asynchronously and the loop moves to the next socket.
  4. When that asynchronous operation completes, the kernel or the client library queues its callback back onto the loop, which runs it on a later iteration, for example to send the acknowledgement to the client.
  5. CPU-heavy work (encoding a large JSON payload, compression, a TLS handshake) is handed to a separate worker thread pool so the loop stays free to service sockets; the loop is for coordinating I/O, not for computation.
  6. Run one loop per CPU core (separate processes in cluster mode, or a runtime scheduler such as Go's) and let them share the listening socket so every core accepts connections.

What this replaces

  • Thread per connection: 250,000 threads at 1 MB of stack each would reserve 250 GB of stack address space (only touched pages are backed by RAM, but that alone runs to gigabytes), and the scheduler would spend its time switching between threads that are mostly waiting. The event loop keeps a few KB of state per connection and switches nothing.

Worked example

Connection servers for the chat app

  • 50 million concurrent users across the fleet; each connection sends or receives a frame every few seconds on average, so a connection is idle more than 99 percent of the time.
  • Thread per connection: at 10,000 connections per server with 512 KB stacks, 5 GB of stack and roughly 10,000 context switches per second just to poll. 5,000 servers for the fleet.
  • Event loop: one process per core, 8 cores, each loop handling 30,000 connections at about 10 KB of buffers and state each, 300 MB per loop, 2.4 GB per server, 240,000 connections per server. About 210 servers for the fleet, a 24x reduction.
  • CPU per message: a loop iteration for one frame (read, decode, route lookup, write) is about 20 microseconds. 240,000 connections at one frame every 3 s is 80,000 frames per second per server, 1.6 CPU-seconds per second, so 8 cores run at about 20 percent and have headroom for a reconnect storm.
  • The database call to persist a message is issued asynchronously; the loop continues serving other sockets during the 5 ms it takes, and the ack is sent when the completion arrives.
  • Reconnect storm: a network blip reconnects 240,000 clients to one server within 10 s; TLS handshakes are CPU-bound, so they run in the worker pool and the loop keeps existing sockets alive.

Variants and when each wins

Single-threaded event loop (Node.js, Python asyncio)

  • One loop per process, scaled by running more processes. It wins for a simple mental model with no shared-memory races; any blocking call stalls every connection on that loop.

Multi-threaded event loops (Netty, Tokio)

  • Several loops in one process share the listening socket, and Tokio moves work between them (work-stealing). It wins for throughput per process, and it needs care around state shared between loops.

Green threads and goroutines (Go, Java virtual threads)

  • You write ordinary blocking-style code and the runtime multiplexes thousands of lightweight threads onto a few OS threads, parking each one while it waits on I/O. It wins for readability with a small per-connection cost, at the price of less control over scheduling.

Completion-based I/O (io_uring, IOCP)

  • You submit operations into a ring buffer shared with the kernel and receive completions in another, with far fewer system calls than readiness polling. It wins on raw throughput, and it is newer and less portable.

Recommendation: goroutines or virtual threads for most services because the code stays readable; a dedicated event-loop framework (Netty, Tokio) for connection servers and proxies where per-connection overhead and tail latency matter most.

Failure modes

Blocking call on the loop

  • You notice every connection on a server stalls for hundreds of milliseconds at once. It happens because a synchronous file read, a DNS lookup or a CPU-heavy JSON parse ran on the loop thread, and nothing else could run until it finished. Fix it by auditing for blocking calls, moving CPU work to a worker pool, and alerting on event-loop lag (how late the loop is to its next iteration).

Unbounded buffering of slow clients

  • You notice memory climbs until the process dies. It happens because the server keeps writing to a socket whose client is not reading, so the outbound buffer for that connection grows without limit. Fix it by checking that a socket is writable before writing, capping the buffer per connection, and disconnecting clients that fall too far behind.

One core busy, seven idle

  • You notice CPU at 12 percent overall yet latency rising. It happens because a single loop process is running on an eight-core machine and only one core does any work. Fix it by running one loop per core with a shared listening socket (SO_REUSEPORT or cluster mode).

Connection storms exhaust file descriptors

  • You notice accept() failing with EMFILE. It happens because each socket consumes a file descriptor and the process limit is still the default of 1,024 or 65,536. Fix it by raising the limit, and setting a maximum connection count per process that rejects new connections gracefully above it.

Callback or promise leaks

  • You notice memory growing slowly over days. It happens because handlers are registered per request and never released, or promises are created that never settle and are never collected. Fix it with a timeout on every asynchronous operation, and heap snapshots in staging under load to find what is retained.

Interviewer follow-ups

Answer out loud before you open each one.

What is the difference between non-blocking I/O and multithreading?

Multithreading gives each waiting operation its own thread, so waiting costs stack memory and context switches. Non-blocking I/O lets one thread wait on many operations at once through the kernel and only runs code when something is ready. The first scales with threads, the second with sockets, which is why connection servers use the second.

How do you handle CPU-heavy work in an event-loop server?

Hand it to a worker pool sized to the core count and treat the result as another async completion. The loop must never run anything that takes more than a few hundred microseconds, otherwise every other connection waits behind it. Event loop lag is the metric that catches violations.

How many connections can one server hold, and what limits it?

Memory per connection and file descriptor limits, not CPU, for mostly idle sockets. At 10 KB of buffers and state per connection, a 32 GB server could in principle hold millions; in practice 200,000 to 500,000 per server is typical once TLS state, kernel buffers and headroom for a reconnect storm are counted.

Why do goroutines make this easier than callbacks?

The code reads as sequential blocking calls while the runtime parks the goroutine on I/O and runs others. You get the memory profile of an event loop without inverting control flow into callbacks or futures. The cost is less visibility into scheduling and the same rule that a truly blocking system call still stalls an OS thread.

Connections

Pairs with
Push to the browser in real time · Find which server holds a user · Slow the producer when the consumer is behind · Pool database connections · Never wait forever
Used in
Chat App (WhatsApp / Messenger)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon KeyspacesMessage storeBigtableManaged Instance for Apache CassandraApache Cassandra, ScyllaDB