← Lessons

quiz vs the machine

Gold1330

Concurrency

The Run Loop

The single thread loop that pulls events and runs callbacks forever.

4 min read · core · beat Gold to climb

The Run Loop

A run loop, also called an event loop, is the engine behind single threaded async runtimes. It is a loop that repeatedly waits for events, then dispatches the callbacks those events trigger, then loops again.

Each turn of the loop is a tick. On a tick the loop checks queues of ready work, such as completed timers, finished IO, and resolved promises. It runs each ready callback to completion, one at a time, then asks the operating system to block until the next event is ready.

  • One callback at a time so no two callbacks run concurrently, which removes data races within the loop.
  • Run to completion Each callback finishes before the next begins, so a slow callback delays everything behind it.
  • Blocks only when idle The loop sleeps in a single efficient syscall when no work is ready, waking on the next event.

This design is why a single thread can serve thousands of connections. The thread is almost never busy, it spends most of its time parked waiting for the next event, and springs to life only to run short callbacks.

Key idea

A run loop waits for events and dispatches their callbacks one at a time to completion, letting a single thread serve many connections without data races.

Check yourself

Answer to earn rating on the learn ladder.

1. How many callbacks does a run loop execute at once?

2. What happens behind a slow callback in a run loop?