Event Loop
| Concept | |
|---|---|
![]() Image placeholderPlace the file shown below in the assets/articles folder event-loop.webp | |
| Type | Concurrency pattern |
| Related | Reactor pattern, async/await |
| Used in | Browsers, Node.js, nginx, asyncio |
An event loop is a programming construct that waits for events or messages and dispatches each one to a handler, usually inside a single thread of control.[1] It repeatedly takes the next pending event from a queue and runs the code registered for it. This lets one thread coordinate many concurrent activities, such as open network connections or user interface input, without blocking on any single one of them.
Event loops sit underneath a large share of everyday software. Web browsers, Node.js, graphical toolkits, Python's asyncio and network servers such as nginx all rely on the pattern. It is closely related to the reactor pattern from object-oriented design and to the async/await syntax found in many modern languages.
Why it exists
Operations such as reading from a socket, waiting for a timer or querying a remote service can take an unpredictable amount of time. A simple program that waits for each of them in turn wastes the processor, and a program that dedicates one operating-system thread to every waiting operation consumes memory for each thread stack and pays scheduling overhead for switching between them. At the end of the 1990s this limitation became known as the C10K problem: how to serve ten thousand simultaneous connections on one machine.
An event loop answers that problem by replacing waiting threads with a queue of callbacks. Instead of sitting idle inside a blocking call, a handler starts an operation, registers what should happen when it finishes, and returns immediately. The loop then goes on to the next ready event.
How it works
At its core the loop is a short piece of code that never ends. It asks the operating system which resources are ready, converts each notification into an event, and calls the associated handler.
while (true) {
event = queue.next() // blocks until an event is ready
handler = lookup(event)
handler(event) // runs to completion
}
[ OS notifications ] -> [ event queue ] -> [ loop ] -> [ handler ]
^ |
+--- new callbacks registeredThe readiness notifications come from kernel facilities designed for the purpose: epoll on Linux, kqueue on BSD and macOS, and I/O completion ports (IOCP) on Windows. Libraries such as libuv hide these differences behind one interface.[2] Timers are usually kept in a sorted structure so that the loop can sleep until the earliest deadline.
Run to completion
Handlers run to completion, one at a time. While a handler executes, no other handler in the same loop can start. This rule removes most data races inside a single loop, because two callbacks never touch shared data at the same instant. It also means that the loop is only as responsive as its slowest handler.
Event loops in practice
Web browsers and JavaScript
Every browser window or worker has its own event loop, defined in the HTML Standard.[1] The loop distinguishes two kinds of queues. Tasks (sometimes called macrotasks) come from sources such as user input, timers and network responses. Microtasks, such as promise reactions and callbacks scheduled with queueMicrotask, are drained completely after each task finishes and before the browser renders the next frame. This ordering explains why a resolved promise callback runs before a setTimeout callback scheduled earlier with a zero delay.
Node.js
Node.js, created by Ryan Dahl and first released in 2009, builds its event loop on libuv. Each turn of the loop passes through named phases: timers, pending callbacks, polling for new I/O, setImmediate callbacks and close callbacks.[4] Disk and DNS work that has no portable non-blocking interface is handed to a pool of worker threads, and the result is delivered back to the loop as an event.
Python, GUI toolkits and servers
Python gained a standard event loop with the asyncio module in version 3.4, and the async and await keywords arrived in version 3.5.[3] Desktop toolkits have used event loops for decades: the application starts a main loop that receives mouse, keyboard and window events. Servers such as nginx run one single-threaded loop per worker process, which keeps memory use low even with many idle connections.
Trade-offs
An event loop is efficient for programs that spend most of their time waiting, but it carries costs.
- Blocking is contagious. A long computation or a blocking library call stalls every other handler. CPU-heavy work has to be moved to worker threads or separate processes.
- No parallelism by itself. One loop uses one core. Using several cores requires several loops, one per thread or process.
- Harder control flow. Logic is split across callbacks. Promises and
async/awaitmake this readable, but stack traces across asynchronous boundaries remain harder to follow than synchronous ones. - Fairness. A handler that never yields can starve timers and other events, so well-behaved code splits large jobs into smaller steps.
| Approach | Strength | Weakness |
|---|---|---|
| Thread per connection | Simple sequential code | High memory and scheduling cost at scale |
| Event loop | Very many idle connections on few threads | Blocking calls stall everything |
| Event loop plus worker pool | Mixes I/O concurrency with CPU parallelism | More moving parts to reason about |
Common misconceptions
An event loop does not make code run in parallel; it interleaves tasks on one thread. Asynchronous code is also not automatically fast: a blocking call inside a handler stalls the loop just as it would stall any other single-threaded program. Finally, async functions do not create threads. They are a syntax for writing callbacks as straight-line code, and the loop underneath still decides when each piece runs.
Understanding the loop explains many practical puzzles, such as why a UI freezes during a heavy calculation, why timers fire late under load, and why the output order of logging statements in asynchronous code can look surprising. It is also a central part of how React applications handle user input and rendering in the browser.
Editorial connections and engineering implications
Queues, fairness and blocking work
An event loop waits for work to become ready, places callbacks or tasks on a queue and runs them according to a scheduling policy. In a single-threaded loop, a callback generally runs until it returns or yields. This simplifies coordination but means that one long-running callback can delay unrelated work. Expensive parsing, image processing or synchronous file access can block the loop and increase latency for every task sharing it.
Different runtimes use different event-loop designs. Browsers coordinate tasks, microtasks, rendering and timers; Node.js has phases for timers and I/O callbacks; Python's asyncio provides tasks and futures through its own API. An event loop can coordinate many outstanding operations without executing them simultaneously on multiple CPU cores. This is concurrency, not necessarily parallelism. It works especially well for I/O-heavy tasks; CPU-bound work may need processes, worker threads or native extensions. This distinction connects to race conditions and Python's concurrency model.
See also
- Race Condition – A defect in which the outcome of a program depends on the unpredictable timing of concurrent operations.
- React – A JavaScript library for building user interfaces from composable components.
- Domain Name System (DNS) – The distributed naming system that translates human-readable domain names into records used to locate internet services.
- Big-O Notation – A notation describing how the resource use of an algorithm grows as the input size grows.
- CAP Theorem – A result stating that a distributed data store cannot simultaneously guarantee consistency, availability and partition tolerance.
- Garbage Collection – Automatic memory management in which a runtime reclaims memory that a program can no longer reach.
- HTML – The standard markup language used to structure documents and applications on the World Wide Web.
- JavaScript – The programming language that powers interactive web pages and a large ecosystem of browser, server and desktop software.
References
- ↑ HTML Standard: Event loops (html.spec.whatwg.org)
- ↑ libuv design overview (docs.libuv.org)
- ↑ Python documentation: asyncio event loop (docs.python.org)
- ↑ Node.js documentation: The Node.js event loop (nodejs.org)
