53 points · by adunk · 2y ago · 92 comments
There are serious drawbacks to async/await, and the red/blue blog post manages to list none of them.
I've wrote a blog in response to OP containing a more detailed version of the above:
https://wpbindt.github.io/async/opinions/programming/2024/01...
My reading of the article is very different. I think the main thrust is function color is infectious, and that's an issue because adding "async" to a single function can have cascading effects through your codebase, which makes refactoring difficult and slows down development speed. This is true even if "async" conveys important information.
My response to this would be that this infectiousness is not a feature of async/await but an intrinsic property of the function. A function calling an expensive function is itself expensive. This is not a bug, it's just reality, and async forces you to be upfront with that.
Another part of my response would be that it doesn't need to infect your entire code base, and that it actually pushes you in the direction of keeping your business logic (which can be sync) separated from your infra logic (which is almost guaranteed to be async). This too I see as a good thing, mixing business logic with infra logic tends to push you in the direction of death by a thousand cuts bad performance. You can achieve this separation as follows:
async def your_endpoint():
business_object = await db.get()
business_object.do_business()
await db.save(business_object)
The blog post I linked to goes into more detail.You're right, the async keyword describes a reality about a function, and any attempt to syntax sugar your way out of that reality will leave you with a leaky abstraction. Async is async whether you have colored functions or colorless functions.
On the other hand, should changing a single function from synchronous to async require you to touch up your code in 30 different places across 10 different files? If you know what you're doing and you're okay with the async call, why do you have redeclare your intentions over and over again like you're punching in nuclear launch codes?
It's an opinionated question. You can see a similar design tradeoff in Zig's approach to generics (implicit type constraints) versus Rust's approach to generics (explicit type constraints) Rust's explicitness removes potential footguns, but it's also an absolute PITA to refactor your type system when you have to.
As an example, a project I work on provides functionality implementing arbitrary computation graphs, with an explicit guarantee that all computations are synchronous, consistent and complete on return from every state change call. This guarantee is a conscious design decision that characterizes both the project itself (and its API boundaries) as well as many of its internals predicated on the same principles. It does explicitly account for asynchronous behavior at the entry point, and at very specific exit points. But introducing async anywhere else in between would mean building a fundamentally different project, and probably revisiting business goals in the process.
The function color problem isn’t just annoying or tedious, it can be fundamental to whether certain projects are even viable.
Being real vague here, in order to support a new capability, we need to insert an asynchronous operation in the middle of what has been a synchronous operation. The synchronous operations is done implicitly and explicitly in many, many places in the app (yes I know this sucks, big old codebases are what they are, and you can only refactor so much at one time while continuing to deliver new features).
We have a hard ordering requirement where the new async behavior must be completed before the work can continue.
And it's killing us. What would be a simple case of "call this new function" is spiraling into weeks of work and thrown our planning into question.
Most of the time it's pretty easy to accommodate the contagion. It's a little more work than is ideal, but it is fine in practice because you hit a natural boundary that stops the spread.
But in this case, due partly to tech debt and partly due to deep architectural decisions, it's blocking our ability to move forward in a reasonable amount of time.
We will certainly find a solution, but it's going to be much more expensive to get there than it needs to be.
The main issue here is that whether or not a function is expensive is known upfront. In practice, this bites you when (a) you refactor (the impl changes), and (b) when you’re writing interfaces (the impl is unknown). This causes cumbersome cascading refactors and even complete loss of interop (in case where a 3p interface is sync and your impl is not).
In order to argue against that point, you have to argue that async is upfront-predictable and obviously part of the interface. And that it should be considered a breaking change - or semantically different if you will.
Regular functions always return (or crash the program).
Regular functions run to completion before returning control to the caller.
These are two key properties async functions lack, so the caller has to care. It's analogous to the notion that checked exceptions are challenging because they also become part of the interface and so the caller is impacted by implementation details.
(This does raise the question of whether there's a form of async hiding just out of sight of current language designs that's analogous to "unchecked exceptions": can one construct a model of function calling that makes one not have to care about async vs. sync functions at the cost of something else? I suspect, without exploring too deeply, that Orc (https://orc.csres.utexas.edu/) has gone that road).
No, you can't say that; claiming they do is equivalent to claiming the halting problem is trivially solvable since any program it applies to will definitively halt.
Trivial counterexample:
def forever():
while True:
pass
> Regular functions run to completion before returning control to the caller.This is true, but it need not be an inherent distinction of the function, but could be one made between the function, caller, and context: that is, the function can have points at which it can yield control, if it is called in the context of an event loop, it will yield at those points, and the caller can choose either to directly call the function and get sync behavior relative to itself or call it in the context of the same event loop as the caller is running, getting async behavior if the function yields early and the call returning an awaitable value (whether or not there is an early yield.)
For the way many “scripting” languages are implemented, where there is already a kind of yield to the runtime at IO, this would be a pretty natural implementation and lets a caller treat any function as async or not without caring if it was specifically implemented as async or not, though you’ll grt no real concurrency in a single-threaded runtime without the function having yield points. (This is, AIUI, basically what the async implementation in Ruby does, which is why while there are libraries specifically designed for async use, existing Ruby async-unaware code that does IO can be called as async and works concurrently out of the box.)
If I understand it correctly this is technologically possible in Python and there are two main tradeoffs depending on how the event loop is modified. given the following:
x = 0
y = 0
async def set_x():
global x
x = await request_x() # returns 5
async def set_y()
global y
y = await request_y() # returns 10
def business_logic():
if x == 0:
set_y() # magic synchronous call to async func
print(x + y)
async def do_business():
business_logic()
async def main():
await asyncio.gather(
set_x(),
do_business())
What is the value that's printed? If all coroutines share the same event loop then we don't know because set_y() could yield execution and give it to set_x(). The author of business_logic() may not even know they are writing async code because it just works, and the author of main() assumes that do_business() is concurrency safe because it's async.The alternative is nested event loops, so everything in business_logic() gets its own event loop that must fully complete before anything else in the parent event loop can run. This solves the concurrency bug but we've introduced blocking into code that was obviously intended to be async. This approach works (see nest-asyncio package) but the core devs have opted against it because they feel it makes it too easy to break the value of async on accident or out of laziness.
IMO something that could work is a `sync def` declaration where the function is written in async style but gets its own event loop and can be called synchronously. It solves the tainting issue while still being explicit, easy to convert to full async, and easy to lint for in projects where it would be a net negative.
Absolutely. Async is sugar for state machines. There is nothing wrong with that per se.
> Regular functions run to completion before returning control to the caller.
Yep. However it's important to note that it’s very possible to cancel regular functions IO from a language perspective, using a cooperative signal. (I always squirm a little every time someone says cancelation is easier in async - you shouldn’t imo cancel by dropping a state machine on the floor).
The best example of this is context.Context in Golang. But even Tokio has CancellationToken.
That said, the real benefit of the state machine is known size. This is the main (and I would say only) meaningful advantage compared to a regular stack. In Golang, you have dynamic per-goroutine (green thread) stack, which is wasting memory compared to rust async.
My issue is that in some contexts the cost of the function is effectively meaningless. A lot of python scripting falls into this category, where performance is not a concern or there is nothing useful to accomplish in the process while waiting for I/O. At that point any async up the stack is just forcing the user to deal with implementation details they shouldn't need to care about.
I can appreciate that it enforces good design decisions in some contexts, but marking that up as a pro feels like tasking the interpreter with doing the job of a linter.
If I could design a language from scratch, I'd argue for async/await OOTB. For example, the Microsoft Midori team did "async everything" in their C# derivative.[0]
[0]: https://joeduffyblog.com/2015/11/19/asynchronous-everything/
I found your post helpful and well written, but in the end I still find myself supporting Bob's blue/red delineation as a helpful articulation of the key limitations with async/await. Why?
Because the only thing that the async keyword objectively says is "someone, somewhere down the call stack, decided to make their function async". You mention I/O in your post and it might indeed be because of that. You also mention cheap vs expensive and, again, it could be that. But those are heuristics: not objective or definitive. The cheap vs expensive point is particularly problematic (a) because there's no delineation between the two, and (b) because it's different for different use cases.
Is reading a file expensive? It might be. If I need to read a 1GB file just to pick out 10 characters, then the read is expensive. But if I'm reading that same file to run a stochastic simulation, then the time to read the file might well be insignificant in comparison to the computation. And, besides, I can't run the computation until I've read the input data anyway - so it's not helpful to me that someone else decided that reading files is "expensive".
The other argument I've seen for marking IO as async is partial failure: IO can fail in ways that local computation doesn't (modulo hardware failures - which can occur, though are much less common). That would be legitimate - except, per above, "async" doesn't definitely mean "does I/O". It only means someone, somewhere in the chain, decided to make their function async. And now I'm constrained to make my functions async too because of its transitive nature.
I'm not against cooperative multi-tasking per se. I do prefer the developer experience of runtime-supported fine threading such as Erlang processes or goroutines. That's a preference though, and others will feel differently - ref comment on static vs dynamic typing.
Well it specifically means that a function can yield its execution context. That property is taken on when one function calls an async function.
It has clear implications for very common threading patterns, I think it's right to argue that using blue/red obfuscates that.
Some type systems allow for validated vs. unvalidated data. And then all of a sudden you have a creeping concern that half your functions talk about char* and half your functions talk about String (or, perhaps, a heterogeneous collection of strings: userid and telephone number and the like). Suddenly the code on the outside of the validation boundary can't use the code on the inside without addressing the question of whether their data is valid.
- The annotation doesn't guarantee any particularly useful property: in many languages async functions can still block or take arbitrary time, while on the other hand non-async functions can still lead to reentrancy issues.
- Most languages do not allow abstracting over async functions: you end up having to write the same higher order function twice even if it would be agnostic over the effectfulness of its parameter.
Some languages, for example some of those with first class effects and no implicit side effects, you can both enforce the property and abstract over the effectfulness.
But for most languages the real reason the async annotations exists is because it is a way to syntactically enforce that only a single stack frame can be suspended as opposed to a whole stack, which is tradeoff between usability, and performance and space usage. The supposed benefit is a post-hoc rationalization.
The peer replies here are dinging you on the vagueness of "expensive" but it's not really about that. The explicit information given by async is whether a function will yield its execution context or retain control of it.
If you're leveraging "has control of the thread" as a form of concurrency (eg the UI thread) then knowing a function is sync or async is extremely important.
The “coloring problem” has nothing to do with async at all, it's just about making effects explicit or implicit in the code.
In Go or Rust, returning an error is also a “color” that spreads out to the top of the call stack. Same for checked exception in Java. Unchecked exceptions are like blocking functions, it's invisible so you don't have to manually annotate your functions but as a result any function can now fail without the programmer knowing it.
JavaScript having async/await but unchecked exception may sound bit paradoxical in that regard, but every language has a combinations of both explicit and implicit effects: Rust has both async/await and explicit errors, but it also has panics (implicit errors) and implicit allocation for instance.
I personally live explicit effects, but at the same time when you have too many of them (for example I'd like to have effects like “pure”, “allocating” and “panics”) they start to cause combinatorial explosion of cases in libraries accepting closures as parameter.
Algebraic effects supposedly solve this particular problem but I'm not sure the additional conceptual learning effort is sustainable for a mainstream language, so in the meantime I think every language must keep its amount of explicit effects under a certain threshold.
As another example to your point, whether a function returns a list of foo's or a single foo is a also a color. You have to do completely different things when calling a function that returns a list compared to one that just returns a single value. And that's not just empty pedantry. Haskell let's you treat "list" as an effect (since it is a monad). Array languages like APL, J or R are colorblind with respect to "a list"/"not a list" as the difference is erased (to a large extend). So there really is a whole rainbow of function colors (basically types).
On the other hand, this point of view doesn't really invalidate the original coloring argument at all. The effect encapsulated by "async" really is one that can be annoying and one that can actually be made implicit with a result that many would prefer.
Combinatorial explosions are wrapped up in the Ts themselves. Sure, you might sometimes get a Stream<Array<Stream<T>>>, but if that's simply the appropriate type to describe what your function does, then who's complaining? As long as you have various ways to manipulate those types, like "Combine" (Array<Stream<T>> -> Stream<Array<T>>) and "Flatten" (Stream<Stream<T>> -> Stream<T>) then you can handle everything. And you'll find that getting your types correct increasingly implies that your entire code is correct, so the compiler is helping you out a lot.
Not unless you're doing it wrong. Errors need to be handled. That may, in some cases, mean handling it with another error, but that isn't adding any "color". The new error is independent of any previous error state.
Sure sometimes you can avoid propagating the error upward, but that's not the most common case and it also happens with async/await (if you don't need the result of the promise in the caller function you don't need to await and to make it a async function).
In Rust the similarity is very flagrant because there are one postfix operators for both (? and .await).
Why call it at all, then? In Rust, futures don't run unless you poll them, so just calling an async function without polling it doesn't do anything.
In contrast, for error returns it's very common to log an error but continue with some default value, or just skip processing one item and continue with the rest. There are a lot of cases where errors can be handled immediately, rather than always blindly bubbled up the call stack
I might buy into your idea the "?" operator colors functions. But that's something else entirely and obviously isn't what you were talking about originally as it isn't found in all of the languages originally mentioned.
That's wrong... Suppose A calls B and B returns a Result<T> (so it's colored as you say). A can match both the Some() and the Err() variants of B and return something other than the error in the latter case. So A can shed the color. There is no way to "shed" async-ness like that in javascript.
In rust you can simply call `block_on` and call it a day. In JS there isn't such a construct by default because the blocking the thread would freeze the app, but it exists in every other language with async/await that I'm aware of.
Once you're in an async function the rules then fundamentally change for how everything operates; it's almost like programming within a dialect of the same language. In particular, I'm referring to everything from function calling, managing concurrency, waiting on results, sleeping threads.
Comparatively, when you're in a go-block in go, you're still writing within the same dialect as outside of it.
The JVM's virtual threads approach is the right way. The runtime should be able to do everything needed to deal with async, and I, the developer, can write simple blocking-style code. Currently there are still issues around pinning when using the older concurrency APIs, but I'm hopeful they can push through them.
But, eventually I realized the difference in pre-emption between languages -- Go can (now) preempt your code in many places, so locks and thread-safety are very important.
The javascript runtime only preempts at certain places, `await` being one. This means I can know no other code can be running without explicit locks around all critical sections.
Finally understanding the trade-offs, I no longer am as frustrated when recoloring a bunch of functions. Instead, I can appreciate the areas where I'm not required to lock certain operations that I would in other languages.
[1]https://en.wikipedia.org/wiki/Cooperative_multitasking#:~:te....
on click
fetch /whatever as json
put the result's data into #some-div
wait 2s
put '' into #some-div
You don't have to mark the script as sync or async, and the runtime will resolve everything for you, making everything feel like synchronous scripting.This obviously has limitations and foot guns, but it works reasonably well for light scripting. More info here:
https://hyperscript.org/docs/#async
And the implementation of it in the runtime here:
https://github.com/bigskysoftware/_hyperscript/blob/c81b07ce...
https://github.com/bigskysoftware/_hyperscript/blob/c81b07ce...
--
[1] - https://htmx.org/essays/hypermedia-friendly-scripting/
const promise1 = job1();
const promise2 = job2();
const [result1, result2] = Promise.all(promise1, promise2); set result to [job1(), job2()]
set result1 to the first result
set result2 to the last result
The array expression will wait until all promise values resolve.This isn't really what hyperscript is designed for, however: its async behavior is designed instead to take the async/sync distinction (and callback hell) out of "normal" DOM scripting. If you have sophisticated async needs then JavaScript is probably a better option. The good news is that hyperscript can call JavaScript functionality in the normal way, so that is an easy option if hyperscripts behavior isn't sufficient for your needs.
const result = Promise.race(job1(), job2()); const promise1 = async job1();
const promise2 = async job2();
const [result1, result2] = Promise.all(promise1, promise2);This means I can write my tech stack to run in either mode, then swap out async/sync functions in the application. This is exactly what I do in https://Lua.civboot.org#Package_lap
- They're sometimes much too explicit. When writing a complicated generator, I don't necessarily want to annotate every call to a sub-generator with `yield*`, especially if I need to drill that annotation through wrapper functions which aren't really generators themselves.
- Colours show up everywhere. If you have several functions with a `context: GodObject` parameter, then that's a function colour. Most third-party code will be unable to forward a `context` argument to a callback, so you'll have to manually smuggle it in using closures instead.
- Different "colour channels" don't compose nicely with one another. Even though JavaScript ES2017 provided both async functions and generators, ES2018 had to add multiple new pieces of syntax to permit async generators.
- It's normally impossible to write code which is generic over a function's colours. For example, if you have `function callTwice(f)` in JavaScript, you'd need a separate `async function callTwiceAsync(f)`, and a `function* iterateTwice(iterable)`, and an `async function* iterateTwiceAsync(iterable)`, despite the fact that all of those functions are doing the same thing.
Several small languages are experimenting with algebraic effect systems [1], which would make all functions colourless. If JavaScript had this feature, the syntax for defining and calling functions would be the same, no matter whether you're dealing with a normal function, a generator, or an async function. No more `async`, `await`, `function*`, `yield`, `yield*`, `for-of`, `for await`...
This can make everything too implicit and vague. The state of the art is for algebraic effect systems to be implemented in a statically-typed language, which then uses type inference to quietly tag all function types with their colours. This means that the compiler can enforce requirements like "you can only call generators within a scope which is prepared to collect their results", but that rule wouldn't prevent you from wrapping a generator in `callTwice`.
[1]: https://github.com/ocaml-multicore/ocaml-effects-tutorial
Having a context argument which is passed to the callback has been par for the course in all cases I've seen, but I've mostly been in C land and related areas.
Though, if you have closures, should you still prefer a context param?
> If JavaScript had this feature, the syntax for defining and calling functions would be the same, no matter whether you're dealing with a normal function, a generator, or an async function.
How would one reason about performance and possibly concurrency in such languages?
It's ambient state, just like a `catch` block, and so you can make it ambiently available to a whole tree of function calls. The outcome is the same as passing around a context argument by hand, and it can have equally strong type-checking, but the compiler handles all of the boilerplate for you.
To answer your second question: I agree that, in a dynamic language like JavaScript, making all of these language features implicit could be too costly. I'm more optimistic about effect systems in statically-typed languages.
So a "localized global variable" of sorts? Sounds interesting, got any links to examples I could look at?
Does anyone understand why asyncio-style approach to async won over gevent-style in Python? Why was the former approach accepted into to stdlib, got special syntax and is preferred by the community while the latter is a fringe niche thing?
Another comment: Python's async/await is precisely syntactic sugar for generators. It just changes the keywords and checks that you only use await in a function labeled async.
Edit: my rate limit appears to have been increased.
I may have a sync program running a main loop and I want to have a subset of that program using something like the reactor pattern. In any multithreading aware programming language I can do that by just sticking that in another thread and syncing however I want, even using coroutines I can do that, it doesn't need to follow the reactor pattern.
However libraries (tokio) and languages (js) don't make that the obvious default. In something like JS it isn't even possible, the entire language is built on top of coroutines. For tokio the default is "put tokio main here and voila async" and you need to actually understand what it's doing under the hood to know that that isn't the behaviour you want in all cases.
This is more bottom-up vs top-down learning. Most people learn and teach top-down because it gets you to productive really quickly. Bottom-up is much harder and has the chance of getting lost in the weeds but makes what is happening very obvious.
Does tokio use reactor or coroutines? It depends...
[0] I say was because I don't know the current status of async in zig or if it will come back in the future. [1] https://kristoff.it/blog/zig-colorblind-async-await/
The biggest issue the article describes — inability for sync code to wait for an async result — is limited mostly to JavaScript, and doesn't exist in most other languages that have async and a blocking wait (they can call red functions from blue functions).
If this architectural hurdle is meant to be the color, then lots of languages with async functions don't have it. This reduces the coloring problem down to a minor issue of whether async needs to be used with a special syntax or not, and that's not such a big deal, and some may prefer async to be explicit anyway.
This is for the most part an intentional design decision to "make sure that when the user is already in async code they don't call the sync form out of laziness." [1]
[1] https://github.com/python/cpython/issues/66435#issuecomment-...
Ruby methods are colorless - https://news.ycombinator.com/item?id=41001951 - July 2024 (235 comments)
On 'function coloring' (2018) - https://news.ycombinator.com/item?id=36199499 - June 2023 (21 comments)
I Believe Zig Has Function Colors - https://news.ycombinator.com/item?id=30965805 - April 2022 (158 comments)
In Defense of Async: Function Colors Are Rusty - https://news.ycombinator.com/item?id=29793428 - Jan 2022 (101 comments)
The Function Colour Myth, Or: async/await is not what you think it is - https://news.ycombinator.com/item?id=28904863 - Oct 2021 (7 comments)
What color is your function? (2015) - https://news.ycombinator.com/item?id=28657358 - Sept 2021 (58 comments)
What Color Is Your Function? (2015) - https://news.ycombinator.com/item?id=23218782 - May 2020 (85 comments)
What Color is Your Function? (2015) - https://news.ycombinator.com/item?id=16732948 - April 2018 (45 comments)
The Function Colour Myth (or async/await is not what you think it is) - https://news.ycombinator.com/item?id=12300441 - Aug 2016 (4 comments)
What Color Is Your Function? - https://news.ycombinator.com/item?id=8984648 - Feb 2015 (146 comments)
No one would want that though right? Like in what context would you even have a consequenceless block? A CLI maybe?
Yes, mitigating the color issue in JavaScript is as "trivial" as allowing the `await` keyword inside non-`async` functions. And what that would mean more-or-less makes sense: the runtime sleeps the active execution thread and resumes it if and when something else in the runtime satisfies the await.
But then you can't know, as the caller, whether any function has "sometimes this function just never returns" semantics without inspecting the whole call chain of every function you call (an arguably impossible task), and that's worse. Especially because the dominant use-case for JavaScript is browsers, where just blocking the UI thread forever is extremely bad.
The fact `await` can only show up in a function declared `async` is a feature, not a bug---it saves the developer from a type of hell where they can't know, in the general case, if a function never returns.
You have exactly as much guarantee of this with async functions as with sync ones, though, but if there is a reason to worry about an async function where it is being called from a sync function and you need to provide a better guarantee, Promise.race() it with a timeout and...problem solved.
Colorless green functions async/await furiously.
And IT MATTERS. That's why you have structured concurrency hot on the heels of Loom. And once you are using structured concurrency constructs... Ehh, it's not the magic "solution" we were sold anymore is it?
The naive solution doesn't work because it turns out the difference between functions that return a value and functions that return a promise matters..
The other approaches destroy ergonomics.
template<effect T> T_function List filter(List list, T_function pred)
(element type committed for brevity) and then filter is async if the predicate is async, etc - it's pure if the predicate is, nonblocking if the predicate is. If you continue in this direction, your language gets more complex than C++. The other options are to just accept that you need a separate filter function for async and non async predicates, or to do away with function flags (doesn't work for CPS style async of course).