Async and Event-Driven Programming
Handling many slow operations at once by reacting to events instead of blocking while you wait.
What is it?
Most programs spend a lot of time waiting: for a network response, a disk read, a database query, a user click. With blocking I/O, the thread that asked simply stops until the answer arrives. To serve 10,000 clients that way, you need 10,000 threads.
Non-blocking I/O starts the operation and returns immediately. The program gets notified later when the result is ready. An event loop sits at the centre: it waits for any of many events (data arrived, timer fired, connection opened), then runs the code registered for that event, then waits again. One thread can juggle thousands of connections this way.
The way programmers write this code has evolved:
1. Callbacks: pass a function to call when the operation completes. Simple, but nesting gets deep and error handling scatters. 2. Promises / futures: an object representing a result that will arrive later, which you can chain and combine. 3. async/await: syntax that lets you write promise-based code top to bottom, as if it were blocking, while the function actually suspends at each await and frees the thread.
Under async/await sit coroutines: functions that can pause partway through and resume later with their local state intact.
Async helps with I/O-bound work (lots of waiting). It does nothing for CPU-bound work; a long computation still occupies the thread and blocks every other task on the loop.
Explain like I'm 10
A blocking waiter takes one table's order, walks to the kitchen and stands there until the food is ready. An event-driven waiter hands the order to the kitchen, serves other tables, and goes back when the kitchen rings the bell. One waiter can handle a whole restaurant, unless one table asks them to personally cook a five-course meal.
Examples
Callbacks to promises to async/await (JavaScript)
// 1. Callbacks: nesting grows with each step
readFile("user.json", (error, userText) => {
if (error) return handle(error);
fetchOrders(JSON.parse(userText).id, (error, orders) => {
if (error) return handle(error);
render(orders);
});
});
// 2. Promises: a flat chain with one error handler
readFileAsync("user.json")
.then((userText) => fetchOrdersAsync(JSON.parse(userText).id))
.then(render)
.catch(handle);
// 3. async/await: reads like sequential code
async function showOrders() {
try {
const userText = await readFileAsync("user.json");
const orders = await fetchOrdersAsync(JSON.parse(userText).id);
render(orders);
} catch (error) {
handle(error);
}
}Concurrency on one thread: 3 requests in ~1 second, not 3 (Python)
import asyncio
import time
async def fetch(name):
await asyncio.sleep(1) # stands in for a network call
return name
async def main():
started = time.perf_counter()
results = await asyncio.gather(fetch("a"), fetch("b"), fetch("c"))
print(results, round(time.perf_counter() - started, 1)) # ['a', 'b', 'c'] 1.0
asyncio.run(main())All three coroutines wait at the same time. Replace await asyncio.sleep(1) with time.sleep(1) (a blocking call) and the total becomes 3 seconds, because the loop can't run anything else while blocked.
How it works
The OS side. Non-blocking sockets plus a readiness API (epoll on Linux, kqueue on BSD/macOS, IOCP on Windows, io_uring for newer Linux) let one thread ask "tell me which of these 10,000 sockets has data". The event loop calls that API, gets a list of ready events, and dispatches each to its handler.
The loop. Roughly: 1. Run any ready callbacks or resumable tasks. 2. Ask the OS which I/O is ready (waiting until something is, or until the next timer is due). 3. Queue the handlers for ready I/O and expired timers, and repeat.
Node.js uses libuv for this, with a thread pool for operations the OS can't do asynchronously (some file system calls, DNS lookups, crypto).
Coroutines. An async function compiles to a state machine (or a suspendable frame). Each await is a point where it saves its locals and returns control to the loop. When the awaited future completes, the loop resumes the coroutine from that point. This is cooperative scheduling: a task only gives up the thread at an await.
Why CPU-bound work hurts. Nothing preempts a running callback. A 2-second JSON parse or image resize stalls every other request on that loop for 2 seconds. Move such work to a worker thread, process pool, or separate service.
Function colouring. In most languages, async functions can only be awaited from other async functions, so async tends to spread up the call stack. Go and Java's virtual threads take a different route: blocking-style code on cheap threads, with the runtime doing the non-blocking I/O underneath.
Blocking (thread per request): Event loop (one thread):
T1: [work][ wait.......][work] loop: [A work][B work][C work] -> poll
T2: [work][ wait.......][work] ...I/O for A,B,C in flight...
T3: [work][ wait.......][work] loop: [A resume][C resume][B resume]
+------------------------------------+
| Event loop |
| run ready tasks -> poll OS for |
| ready I/O + timers -> queue their |
| handlers -> repeat |
+------------------------------------+
^ |
I/O done | | start non-blocking I/O
| v
[ epoll / kqueue / IOCP / thread pool ]Why does it exist?
Thread-per-connection servers ran into the "C10K problem": each OS thread costs memory and scheduling overhead, so tens of thousands of mostly idle connections became expensive. Event-driven designs (nginx, Node.js, Redis) showed that one thread can serve huge numbers of connections when it never blocks. Callbacks made that possible; promises and async/await made it readable. UIs have the same need: the UI thread must never block, or the app freezes.
When to use it
- Servers and clients with many concurrent, mostly idle connections: web servers, proxies, chat, websockets. - Code that fans out to several I/O calls and can run them concurrently (several API calls at once instead of one after another). - UI programming (browsers, mobile, desktop), where the main thread must stay responsive. - Pipelines driven by external events: message consumers, file watchers, timers.
When not to use it
- CPU-bound work (number crunching, image processing, compression): use threads, processes or Web Workers for real parallelism. - Simple scripts or low-concurrency services, where blocking code is easier to write, read and debug. - When a library you depend on only offers blocking calls; wrapping them in async without a thread pool still blocks the loop. - In Go or Java 21+, plain blocking code on goroutines or virtual threads often gives the same scalability without async syntax.
Common mistakes
Calling a blocking function (
time.sleep, synchronous file or HTTP calls, heavy loops) inside async code and freezing the whole event loop.Awaiting independent operations one after another instead of starting them together with
Promise.all/asyncio.gather.Forgetting to
awaita promise or coroutine, so errors vanish and code continues before the work finishes.Assuming async code is free of races because it's single-threaded. State can change at every
await.Starting unbounded numbers of concurrent requests (thousands of
fetchcalls at once) and overwhelming the downstream service; limit concurrency with a semaphore or pool.
Practice exercises
- Easy:
Write a function that fetches 5 URLs (or simulated delays) sequentially with await, then rewrite it to run them concurrently. Measure and compare the total time.
- Medium:
Take a callback-based function such as Node's
fs.readFileor asetTimeoutdelay and wrap it in a promise yourself, then use it with async/await, including error handling. - Hard:
Build a tiny event loop in Python using generators: tasks
yielda sleep duration, and the loop keeps a priority queue of (wake_time, task), always resuming the earliest. Run three tasks that print interleaved output.
Interview questions
What is the difference between blocking and non-blocking I/O?
Blocking I/O suspends the calling thread until the operation completes. Non-blocking I/O returns immediately, either with data if ready or an indication that it isn't, and the program is notified later through readiness or completion events. Non-blocking lets one thread manage many operations.
What is an event loop?
A loop that repeatedly waits for events (I/O readiness, timers, messages) and dispatches the callback or resumes the task associated with each one. It provides concurrency on a single thread, as long as no handler blocks or runs long.
How does async/await relate to promises and coroutines?
async/await is syntax over promises (JS) or futures/awaitables (Python, C#, Rust). An async function is a coroutine compiled into a state machine; each await suspends it until the awaited future completes, then the event loop resumes it. It's the same model as promise chains, written sequentially.
When does async improve performance, and when doesn't it?
It improves throughput for I/O-bound work, where tasks mostly wait, by overlapping the waits without many threads. It doesn't help CPU-bound work, because computation still occupies the thread and blocks the loop; use parallel threads or processes for that.
What happens if you call a blocking function inside an async handler?
The event loop thread is blocked for the duration, so no other tasks, timers or I/O handlers run. Latency rises for every request sharing that loop. Run blocking code in a thread pool (run_in_executor, worker_threads) or use an async-native library.
What is callback hell, and how do promises fix it?
Deeply nested callbacks where each async step's continuation is passed into the previous one, with error handling repeated at every level. Promises flatten the nesting into chains, propagate errors to a single handler, and let you compose operations (all, race, any).
What is the difference between concurrency with async and parallelism with threads?
Async interleaves many tasks on one thread, switching only at await points (cooperative). Threads can run simultaneously on multiple cores and are preempted by the OS. Async gives concurrency for waiting; threads or processes give parallelism for computing.
What is 'function colouring'?
In languages with async/await, async functions can only be awaited from other async functions, so the code splits into two colours and making one deep function async forces changes all the way up. Go and Java virtual threads avoid it by letting ordinary blocking code run on cheap threads.
How do you limit concurrency in async code?
Use a semaphore (asyncio.Semaphore, a p-limit style helper) around the operation, a fixed-size worker pool reading from a queue, or batching. This protects downstream services and avoids exhausting sockets or memory.
How does Node.js handle file I/O if the OS doesn't support truly async file operations?
libuv runs those operations on a small internal thread pool (4 threads by default, configurable via UV_THREADPOOL_SIZE) and posts the completion back to the event loop. Network I/O uses the OS readiness APIs (epoll, kqueue, IOCP) directly.