Async and Non-Blocking I/O
Picture a chat server. Each user keeps a connection open all day, but sends a message only now and then. With 10,000 users online, the server holds 10,000 connections, and at any given moment maybe 50 of them have something to say. The other 9,950 are just waiting.
The simplest design gives every connection its own thread. It is easy to write and easy to read, and it works well
for a few hundred clients. At ten thousand, the machine spends its memory on thread stacks and its time switching
between threads that have nothing to do. Non-blocking I/O fixes this by letting one thread watch all the
connections at once and only touch the ones that are ready. That idea, wrapped in an event loop, is what runs
Node.js, Netty, nginx, Redis and Python's asyncio.
This post builds it from the bottom: what a socket call actually waits for, why thread-per-connection hits a wall,
how a selector lets one thread wait on many sockets, and how callbacks, futures and async/await make that style
pleasant to write.
💡 Why this matters in an interview: you won't write an event loop from scratch. You will be asked "how would this server handle 100,000 open connections?" or "why is Node single-threaded and still fast?" The answer is always the same mechanism, and you should be able to explain it in two minutes.
Sockets in Five Minutes
A socket is one end of a network connection. Your program gets a handle to it (on Unix, a small integer called a file descriptor) and reads and writes bytes through it, much like a file. A TCP server uses a few calls:
listenon a port, so the operating system starts accepting connections for you.accepta new connection. This returns a fresh socket for that one client.recv(read) bytes the client sent, andsend(write) bytes back.closethe socket when done.
The key detail is what happens when there is nothing to do yet. By default, sockets are blocking:
acceptwaits until a client connects.recvwaits until at least one byte arrives. If the client is idle for an hour, the call waits an hour.sendcopies your bytes into the kernel's send buffer and returns. If that buffer is full because the client reads slowly,sendwaits until there is room.
While a thread is blocked in one of these calls, it can do nothing else. It is parked by the operating system and costs no CPU, but it still exists, with its own stack, waiting for one socket.
Two more details matter later. First, TCP is a byte stream, not a message stream: one recv can return half
of what the client sent, or two messages glued together. Real servers keep a buffer per connection and split it
into messages themselves. Second, a recv that returns zero bytes means the client closed the connection.