Async/Await: a significantly compromised approach
Date: 2022-12-22
Summary: Async/await offers fine-grained concurrency but with very signififcant costs.
This post is quite long. If you want the TL;DR, jump to the conclusions.
Note: I'll use 'function' below to generically represent any activity that can be called. So it covers methods, lambdas, etc. as well as conventional functions.
In the beginning: sequence and structured programming
The origins of computer programming were sequential. Programs comprised ordered lists of instructions; the machine performed the instructions in the specified order. Programming languages evolved to support that paradigm. Even today, virtually every mainstream language is founded on sequential execution (C, C++, Java, C#, Python, Rust, Ruby, Javascript, ...). We write code as text: it has a linear order down the page that mirrors the execution flow. Control flow - looping and branching - uses indentation, e.g.
def countdown(start: int):
if start < 0:
print("Start must be greater than 0")
return
else:
count = start
while count >= 0:
print(count)
count -=1
return
Listing 1: Looping and Branching
This idea - structured programming - seeks to address a usability question that Edgar Dijkstra neatly articulated in his famous paper Go To Statement Considered Harmful:
[..] our intellectual powers are rather geared to master static relations and that our powers to visualise processes evolving in time are relatively poorly developed. For that reason we should do (as wise programmers aware of our limitations) our utmost to shorten the conceptual gap between the static program and the dynamic process, to make the correspondence between the program (spread out in text space) and the process (spread out in time) as trivial as possible.
Dijkstra's observation was that goto - a dominant construct at the time - created dissonance between the textual structure of a program and its runtime behaviour. He argued that if-then-else style formatting provided a better match between text stucture and program execution. Contrast listing 2 below with Listing 1 above. Both implement the same logic, but Listing 1 is clearly easier to read.
from goto import with_goto
@with_goto
def countdown(start: int):
if start <0: goto .fail
count=start
label .loop
if count == 0: goto .end
print(count)
count -=1
goto .loop
label .fail
print("Start must be greater than 0")
label .end
return
Listing 2 - countdown using goto
What's that got to do with async/await?
To begin with, we should pause to consider the problem async/await seeks to address. Microsoft, from whence the async/await design originated, has an example that illustrates the problem:
- Pour a cup of coffee.
- Heat a pan, then fry two eggs.
- Fry three slices of bacon.
- Toast two pieces of bread.
- Add butter and jam to the toast.
- Pour a glass of orange juice.
The essential argument is as follows. These steps are listed sequentially, but they don't have to be executed sequentially. For example: there's no need to wait for the bacon to finish frying before toasting the bread. Some of the steps are necessarily sequenced though: we can't butter the bread before it's finished toasting. It takes a bit of reading to figure out the dependencies in the list. It's a lot easier to see on a diagram - see Figure 1.

Figure 1 - Breakfast Dependencies
Maybe that's triggered something from Dijkstra's quote above: the textual layout of the procedure doesn't reflect the control flow. It's a different scenario though. Dijkstra was talking about branching and looping: decision points where, in the next step, we do either one thing or another. They're mutually exclusive. In Listing 1, for example, the function would never print the error and the countdown sequence in a single invocation.
We want something different for the breakfast example. Here, we do want everything to happen: we just don't want it to be purely sequential. The textual procedure is over-constrained. That gives us a problem: programs are inherently sequential. Our control flow statements (if-then-else, while) don't let us say anything about things running concurrently. We need something else.
Processes and Threads
This isn't a new problem of course. Running multiple things concurrently, on a single computer, has been possible since at least the 1960s. Operating systems have offered processes and threads for decades. Both enable independent sequences of instructions to run concurrently. They differ in some important ways, but those are less relevant here. The key point is: processes and threads allow independent execution of concurrent instruction sequences.
So why do we need async/await?
The primary argument is scale. Operating system processes and threads are heavyweight abstractions. We can't start too many in parallel, because the machine will run out of resources. Take a web server. Conceptually, the easiest approach would be for each incoming user session to be handled by its own process/thread. A typical mid-range server might support a couple of thousand concurrent threads. That's not really very high for something like a web server though. Ideally, we'd like something finer-grained than that. That's what async/await attempts to address.
Stepping back: what's the problem again?
Before we get lost in the weeds of processes, threads and async/await, let's go back to the problem in the example. What is it we're trying to express? Why is there a direct path from start -> pour_coffee -> eat_breakfast, but not from start -> fry_eggs -> eat_breakfast? The answer probably seems obvious when you look at the diagram: we need to heat the pan before frying the eggs. We can't fry the eggs in a cold pan, but we don't need a pan (hot or cold) to pour coffee. There's a dependency between heating the pan and frying the eggs, but the coffee is independent of either. Equally, all of the concurrent sequences need to complete before we can eat breakfast. That's fundamentally the problem we're trying to solve. We can generalise the objective and express it as follows:
Prevent undesirable interference among independent activities.
That might seem a bit of a jump from frying eggs, so let's test it.
- Pouring coffee is independent of heating the pan. So any interference between them would be undesirable.
- Frying the eggs is dependent on the pan being heated, but independent of pouring the coffee.
The picture in the example is a dependency graph. It illustrates which activities depend on others, and which are independent.
What we want in code is the ability to express a dependency graph that doesn't have any unnecessary dependencies among activities.
That's the problem Async/Await aims to address. And it, does, but at a cost. Let's look at the async code given in the example:
Coffee cup = PourCoffee();
Console.WriteLine("Coffee is ready");
Task<Egg> eggsTask = FryEggsAsync(2);
Task<Bacon> baconTask = FryBaconAsync(3);
Task<Toast> toastTask = ToastBreadAsync(2);
Toast toast = await toastTask;
ApplyButter(toast);
ApplyJam(toast);
Console.WriteLine("Toast is ready");
Juice oj = PourOJ();
Console.WriteLine("Oj is ready");
Egg eggs = await eggsTask;
Console.WriteLine("Eggs are ready");
Bacon bacon = await baconTask;
Console.WriteLine("Bacon is ready");
Console.WriteLine("Breakfast is ready!");
Listing 3 - preparing breakfast with async/await
The first thing to note is that it still includes some unwanted dependencies: for example, pouring the orange juice has to wait until the toast has been prepared. The change is how the eggs and bacon are handled. Each has two relevant statements:
Task<Egg> eggsTask = FryEggsAsync(2);
Task<Bacon> baconTask = FryBaconAsync(3);
//...other activities
Egg eggs = await eggsTask;
Bacon bacon = await baconTask;
FryEggsAsync() and FryBaconAsync() are defined as async functions. When the code executes the Task<Egg> eggsTask = FryEggsAsync(2); statement, it doesn't call into the FryEggsAsync() function. It starts it as a concurrent activity, which, avoiding implementation details, means the following happens:
FryEggsAsync(2)is startedFryBaconAsync(3)is started immediately, i.e. it doesn't wait forFryEggsAsync()to finish.
So what's wrong with that?
Problem #1: Syntax overhead
First off, there's extra syntax to deal with. Task<Egg> eggsTask = FryEggsAsync(2); is a bit more complex to mentally parse than eggs = FryEggs(). And we also need to remember to call Egg eggs = await eggsTask; to actually get the result.
Problem #2: Failing Dijkstra's recommendation
Quoting Dijkstra again:
make the correspondence between the program (spread out in text space) and the process (spread out in time) as trivial as possible.
Whilst frying the eggs and bacon are started concurrently, the link between each and their corresponding await instructions isn't reflected in the syntactic structure. In fact, it's more like looking at Listing 2 than Listing 1. The syntactic structure doesn't reflect the runtime dependencies. On reading the Task<Egg> eggsTask = FryEggsAsync(2); line, we have to scan down the page to find the corresponding Egg eggs = await eggsTask;. It's analogous to encountering the goto .fail in Listing 2 and scanning down to find the label .fail statement.
The code is still written linearly. There's no structure to aid the developer in visualising the intended runtime behaviour.
Problem #3: Coloured Functions
Bob Nystrom wrote the definitive post on coloured functions, and it's well worth a read. In summary though, the crux is this:
You can't call an async function from a sync function
Bob illustrates this with colour: async functions are red, sync functions are blue. Continuing our example, the following is legal:
private static async Task<Egg> FryEggsAsync(int howMany)
{
pan = GetPan(); //where GetPan() is a conventional synchronous function
}
But we can't do this:
static void PrepareBreakfast()
{
Task<Egg> eggsTask = FryEggsAsync(2);
Egg eggs = await eggsTask;
}
That limitation is transitive. If there's one async function, anywhere in your program's call stack, every single direct or indirect caller has to be async.
Think about that for a minute. Say you're writing a web app. Almost no-one writes something like that from sratch. There'll be a stack of abstractions like libraries handling IP, TCP, HTTP, SSL and what not. If any one of the functions that your app handler function calls is async - whether directly or indirectly - every other one needs to be async too.
Just imagine what happens if one of those functions changes from sync to async in a library update. Every single app using that function needs re-written. If the function was in the language runtime, that's every app in the world that directly or indirectly calls the function in question.
That's.... significant. It's generally accepted that design decisions should, as far as possible, be localised so as to have minimal interference on other parts of a program or library. Coloured functions are the opposite of localised.
Problem #4: The Sync/Async Decision Point
The transitive ramifications of async put a significant responsibility on deciding whether any given function should be sync or async. It's a choice that has to be made for every single function you write. Who owns the decision? The answer is: the developer who defines and/or implements the function. Maybe that seems reasonable, obvious even: if functions have to be either sync or async, then of course the implementer decides. But again, think through the implications. Think about the library implementer deciding whether to make a function sync or async. How do they decide?
- If they make it sync, it will pause execution during long-running actions such as network input/output. That's bad: we don't want unnecessary interference among independent activities
- If they make it async, every direct or indirect calling function needs to be async too.
Talk about being stuck between a rock and a hard place. How is our beleaguered developer to choose? Microsoft provides some guidance:
If you have any I/O-bound needs (such as requesting data from a network, accessing a database, or reading and writing to a file system), you'll want to utilize asynchronous programming. You could also have CPU-bound code, such as performing an expensive calculation, which is also a good scenario for writing async code.
Reading that, our diligent library designer will reasonably decide "OK, this needs to be async". But she has just made a decision that impacts every direct and indirect user of her library. The reality is she can't know the right answer - because there isn't one. It's simply not feasible that every single user of her function has the same efficiency/simplicity tradeoffs.
Problem #5: Debugging
Behind the scenes, language runtimes schedule async functions onto different execution threads (that's how they enable the functions to run concurrently). Unfortunately, that can make debugging difficult: there are multiple call stacks. Add in exception handling and the picture gets even more complicated. Microsoft even has a video series entitled Why is Async code hard to debug?
Consequences
Coloured functions and the async decision point are mutually reinforcing - in a bad way. The transitive nature of async means all descendent users are impacted; and the decision point is in the wrong place. Meaning (a) implementers have to decide without knowledge of use, and (b) callers have to live with the implementer's decision.
In practice this causes 2 chronic problems:
- async proliferation. Async spreads like a codebase virus. Whilst the guidelines on when to use it are reasonable, in reality most functions become async for one of two reasons:
- the developer of a library made their function async, therefore forcing the consuming developer to follow suit;
- Developers take a simplified view that "async is good" and code all of their functions that way - irrespective of whether they need to or whether it's appropriate.
- Dual implementations. Diligent library implementers provide both sync and async variants. See, for example, the Python FastAPI library. Kudos to them for doing so, but why should they be saddled with that burden?
Conclusions
There's no doubt that concurrency is a real and increasingly pervasive requirement. OS level processes and threads are powerful but have scaling limitations. There is a clear need for constructs that enable finer-grained concurrency. But all design choices have trade-offs: the goal is to maximise benefits whilst minimising the costs. Async/await offers finer-grained concurrency, but has several notable costs:
- Syntax overhead
- Lack of syntax-directed flow
- Coloured functions
- Wrong decision point
- Difficult debugging
These are significant, and mean async/await is a highly compromised solution to providing fine-grained concurrency.
Given these serious flaws, it's reasonable to ask why the async/await pattern has been adopted by several high-profile languages including C#, Python, Rust and Javascript. A key attraction is speed. Async/await is essentially cooperative multi-tasking. That means every developer has to decide when and where it's OK for their code to pause and allow other independent sequences to get compute time. The advantage is low overhead and so the potential for good performance: there's little or no runtime overhead in the operating system or language runtime. The overhead instead is with the developer. So - used well - cooperative multitasking can bring meaningful performance improvements. The key clause in that statement, however, is used well. Given the very significant flaws highlighted above, using it well is fraught with problems.
Are there better options? I believe so, and will cover in a later post. For now, I'll reference this post for a good description of the problem and, in my view, a good conceptual basis for providing a better approach.