0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Foundations
Synchronization
Concurrency Patterns
Async Await Under the Hood
Async and await let programmers write code that looks sequential while running on an event loop. Behind the syntax is a transformation that turns a function into something that can pause and resume. This section traces the path from callbacks to coroutines, explains what a coroutine is, and shows what await actually does when it suspends a function.
The problem async solves
Consider a handler that loads a user, then loads their orders, then renders a page. With blocking calls, it is three lines. On an event loop, each load must return immediately and deliver its result later, so with callbacks the handler becomes three nested functions, each receiving the result of the previous step and starting the next. Error handling must be repeated at every level, loops that load items one by one need recursion, and early returns or try finally blocks no longer work across the nested functions. Promises flattened the nesting into chains of then calls and gave errors a single path, but still required the code to be split at every asynchronous step. Async and await go further: the handler is written as three ordinary lines, with an await before each load, and the compiler or runtime takes care of splitting it at the awaits and resuming it when each result arrives. Control flow constructs, loops, conditionals, try catch and finally, work exactly as they do in synchronous code.
What a coroutine is
A coroutine is a function that can suspend its execution at certain points and later resume from exactly where it stopped, with its local variables intact. Ordinary functions, called subroutines in this vocabulary, run from start to finish once called and return a single time. Coroutines generalize them by allowing many entries and exits. The idea dates to Melvin Conway in 1958, who used coroutines to structure a compiler as cooperating passes. A coroutine can be stackful, owning a full call stack so it can suspend from deep inside nested calls, like goroutines, Lua coroutines and Java virtual threads; or stackless, saving only its own frame, so it can suspend only at explicit points in its own body, like async functions in JavaScript, Python, C sharp, Rust and C plus plus. Async await in most languages is built on stackless coroutines, which is why await can appear only inside an async function: only that function frame is saved when it suspends, not the frames of its callers.
What await does
When an async function reaches an await on a value that is not yet ready, three things happen. First, the function saves its state: which await it is paused at and the values of its local variables. Second, it registers a continuation with the awaited object, a way to be resumed when the value is ready, for example by attaching a callback to a promise or future. Third, it returns control to its caller, which in the end is the event loop, so other work can run. When the awaited value becomes ready, the continuation is scheduled, the runtime resumes the function, restoring its state, and the await expression produces the value, or throws the error if the operation failed, and execution continues to the next line. If the awaited value is already ready, many runtimes still suspend briefly, as JavaScript does, while others, such as Rust and C sharp with completed tasks, continue synchronously without a round trip through the scheduler.
Calling an async function
Calling an async function does not run it to completion; it creates a coroutine object, and what happens next depends on the language. In JavaScript and C sharp, the function starts running immediately, synchronously, until its first await, and returns a promise or task representing its eventual result. In Python, calling an async function only creates a coroutine object and runs none of its body; it runs only when awaited or wrapped in a task with create_task, which is why forgetting the await produces a warning that a coroutine was never awaited and the code silently does nothing. In Rust, calling an async function creates a future that does nothing until polled by an executor. These differences, eager versus lazy, explain many bugs when moving between languages: in JavaScript, a forgotten await still runs the operation but loses its result and errors; in Python and Rust, a forgotten await means the operation never happens.
Await is not parallelism
Await makes a function wait without blocking the thread, but awaiting operations one after another still runs them in sequence. A handler that awaits a call to service A and then a call to service B, each taking 100 milliseconds, takes 200 milliseconds, exactly like blocking code, although the loop can serve other requests meanwhile. To overlap them, the handler must start both before awaiting either, by creating both promises or tasks first and then awaiting them together with Promise.all, asyncio.gather, Task.WhenAll or join in Rust, which takes 100 milliseconds. Async code makes concurrency possible, but the programmer still has to express which operations are independent. A common review finding in async codebases is a loop that awaits each item in turn when the items could be fetched concurrently with a bounded fan out.
Async across languages
The syntax is remarkably similar across languages, which hides real differences. C sharp introduced async and await in version 5 in 2012, building on its Task type, and the design spread quickly: Python added the keywords in 3.5 in 2015, JavaScript in ES2017, Kotlin offered suspend functions with coroutines in 2018, Rust stabilized async await in 1.39 in 2019, Swift added it in 5.5 in 2021 and C plus plus 20 added coroutines with co_await. Kotlin is notable for marking functions with suspend rather than returning a future type, and for structured concurrency through coroutine scopes built in from the start. Swift ties async functions to actors and tasks with compile time checks for data races. Go and Java took a different path entirely, keeping ordinary blocking syntax and making threads cheap instead. Knowing which family a language belongs to tells you whether a function call might suspend invisibly or only at explicit awaits.
When not to use async
Async is not always worth its cost. A batch script that processes files one after another, a CPU bound computation, or a service handling a handful of concurrent requests gains little from async and pays in coloured functions, harder debugging and library constraints. The benefit appears when a program has many concurrent waits, such as hundreds of network calls in flight, and grows with the ratio of waiting to computing.
An async function is a coroutine that saves its state at each await, registers a continuation and yields to the loop, resuming when the value is ready. Most languages use stackless coroutines, so await only works inside async functions. Calling an async function may run it eagerly or not at all until awaited, and sequential awaits still add up unless you start operations together.