by spinningslate · 7y ago · 0 comments
It’s proliferation puzzles me: c#, python, node, rust and no doubt others. Yet it seems like a poor abstraction.
1. The cognitive overhead. Whilst the example might be intended to show off power, that function signature is not at all easy to parse mentally. Even allowing for generics it’s still a lot more difficult to think of a function that returns a future that will return the result at some point (as opposed to a function that returns a result synchronously).
2. It’s declared at the call site - not by the caller. As the writer of a function, how am I supposed to know whether the majority of callers will get sufficient benefit to offset the increased cognitive overhead? It can also have viral tendencies: a function that calls an async function is async itself, and so on. (Not sure if that’s mandatory in all language implementations). I’ve seen more than one code base where async was like a virulent rash.
Personally I find Actor model concurrency so much easier to deal with (e.g. Erlang). The rules seem significantly more straightforward and easier to deal with mentally.
Data flow concurrency (e.g. FRP) also seems much easier to reason about.
Async/await by comparison seems like a poor substitute. So I’m puzzled but intrigued by its growing popularity.
I can imagine it’s easier to implement in the language (compiler/runtime), which might be key for rust. I can also see that it’s an incremental step for procedural languages. But then surely it’s a wise investment to build good abstractions in the language - even if it’s (a lot) harder - rather than burden the programmer with more complexity?
What am I missing?
I'll try to give you some answers from my perspective; I am not on the language team, nor have I done any of this work myself, but this is what I remember, and see from the outside.
The short answer is: it's the only way to accomplish the task that fits into Rust's requirements. The top relevant ones are speed, lack of required runtime for non-async code, and zero-cost C interoperability. It sounds to me like you're coming at this from a "what is the simplest thing for a programmer to use" angle. That's a totally valid angle, but Rust is focused on ease of use only within the context of other requirements. Notably, Erlang's model, while it has excellent properties, falls down on all three of these other requirements. That's totally okay in the context of Erlang, but is not acceptable in the context of Rust.
> Notably, Erlang's model, while it has excellent properties, falls down on all three of these other requirements.
Being nitpicky, but I'd argue Erlang only falls down on speed where it's computationally bound. Where it's IO bound (e.g. a prototypical chat server) Erlang has excellent speed characteristics - where speed is measured in concurrency and latency.
But I absolutely get that's not the interpretation of "speed" you meant.
Appreciate the explanation.
Phoenix, which is in Elixir, does 2.7% of the requests of the Rust frameworks. Chicago Boss, in Erlang, does 0.2%. Is this a realistic benchmark? I don't know; I can't say if the code for either of these implementation is good or not. But if it's a silly error, I think it would be good for Elixir/Erlang advocates to fix this. Early Rust implementations had extremely poor showings too.
I tend to think of Erlang as being extremely reliable, with acceptable performance, rather than being the fastest IO language in the West.
It is not really realistic at all no. But mostly because the benchmark is not realistic of a production load. That said we should do better.
The main reason it is not fixed is that the few members of the community that tried to fix it had a really bad experience interacting with the repo and getting feedback of impact and simply lost interest. And we have not have people motivated enough so far because they do not really care about the benchmark.
Ofc it matters to people that are not in the community but well...
That said, yes we would never be close to Rust anyway (probably) but we could probably have a far better standard deviation than Rust. Something that tend to matter in production a lot but people forget reading benchmark is the spread of the response time vs the average one.
We should also perform better in a noisy environment like the "cloud" one.
There are hopes that the recent EEF marketing group could help find volunteers or finance someone to fix it.
At the scale where asynchronous IO becomes interesting, speed is computationally bound. Think maintaining tens of thousands of TCP connections. You can either spawn a single OS thread for each connection, which gets prohibitively expensive with regards to memory consumption, or you can use asynchronous IO and have a couple of native worker threads, approx. 1 per CPU core.
If Erlang can handle, say, tens of thousands of TCP connections with one Erlang thread/actor per connection, then only because it is using an implementation of asynchronous IO in the background.
Yes, it can. That's one of the BEAM's key strengths (the Erlang VM). It presents a simple, uniform concurrency abstraction - the process - to developers. Note these are application-level processes, not OS level. They're very lightweight and it's possible to spin up tens of thousands on a single machine. The VM multiplexes user processes over the underlying hardware (threads/cores). More here [0].
[0] https://stackoverflow.com/questions/2708033/technically-why-...
My experience with JS async/await code in the wild is that developers promptly forget (or never learn) that it desugars to a promise, forget all the tools that can be used for managing complex asynchronous code with explicit promises, and then fail to properly account for the asynchronicity of their code.
I would hope that Rust, with a type system and a community focused on engineering skills, would be able to avoid some of these pitfalls, but I'm not so sure about that.
However, we have people using Rust today that need help. We could ignore these production users and say “sorry, it’s gonna be who knows when”, or we can ship something that solves their problems. Even shipping async/await itself took four years, even though it’s a technique that’s well known!
I've written and reviewed boatloads of promise-using JS code, a fair amount of promise-using C++ and task-using C#, and some future-using Rust. I've never seen a case where the value added by async/await exceeds the potential for issues.
The goal seems to be make asynchronous code look like synchronous code. In my experience, developers do in fact act like it's synchronous, forgetting the critical fact that it's not. The supposed feature is a massive bug in everyday usage.
EDIT: reading through the RFC and comments, I now realize that async fn is NOT actually being implemented as sugar on top of future-returning functions, but in fact is more like a Python or ES6 generator. There seems to be a disagreement as to whether an async fn is really just a future-returning function: I see the claim made both ways, and haven't found an authoritative source yet. Confusing!
EDIT2: > do notation in a language without a GC is an open research question. Some believe it’s impossible.
I don't understand how GC comes into play. Isn't the do notation simply syntactic sugar for bind sequencing?
It seems to me that you'll generally await futures in high-level code. Keeping values around as futures is the minority case. So instead of asking to await one could automatically insert awaiting code whenever a future needs to be converted to a real value. Instead of this:
async fn process() -> Image {
await process_image(await fetch("http://example.com/foo.jpg"))
}
...you could simply have this: async fn process() -> Image {
process_image(fetch("http://example.com/foo.jpg"))
}
...which would await both the inner and outer futures: process_image() expects an Image, and fetch() returns a Future<Image>, so it can be automatically awaited and coerced.Sometimes you do want a future when you don't want to wait right away, e.g. when storing a bunch of pending operations or something. For that, one could tell Rust not to automatically coerce futures:
let pending: HashMap<string, Future<Image>>
// ...
async fn process() {
pending[key] = defer process_image(fetch("http://example.com/foo.jpg"))
}
...although this, too, could presumably be done transparently for you, since Rust knows you're assigning to a future.I think part of it too was that this works better if your futures were to execute immediately like promises; this would make a lot of code serial by default.
Disagree, because it's all compositional, which is the essence of taming complexity. You can understand what a Future is and then, separately, understand the thing the function is doing. It's similar to working with a container: a function that returns a list of results is more complex than a function that returns a single result, but it's tractable because you can understand the two aspects separately.
> As the writer of a function, how am I supposed to know whether the majority of callers will get sufficient benefit to offset the increased cognitive overhead?
If your function would need to wait, or calls an async function, it should be async; otherwise it should be sync. You need to define your threshold for "would need to wait" in your codebase - popular answers are any I/O, any network access, or any non-local network access - but you can answer that once and then the decision for any given function is pretty mechanical.
Of course ideally you'd be able to write general-purpose functions generically such that the caller could use them as either sync or async; unfortunately Rust lacks higher-kinded types.
> Personally I find Actor model concurrency so much easier to deal with (e.g. Erlang). The rules seem significantly more straightforward and easier to deal with mentally.
Actors are far too unconstrained to be able to reason about a codebase that uses them. You send a message to an actor, and what does it do? Could be anything. Is it equivalent to this other message? Maybe! You didn't get a reply, has something gone wrong? Maybe!
> Data flow concurrency (e.g. FRP) also seems much easier to reason about.
What distinction are you drawing here? FRP seems like something you'd build on top of Futures as far as I can see?
1. If it's like Javascript, async and await basically boil down to converting to and from Promises. There's no reason to have to transitively perpetuate `async` annotations: you can just deal directly with a completely normal Promise object instead. (But you soon find you like `async` better :-))
2. The “caller decides” model is actually considered good practice in Go: expose synchronous primitives, and let callers compose them with Goroutines if they want to.
It is and it isn't. That is,
> async and await basically boil down to converting to and from Promises
In Rust, they basically boil down to converting to and from Futures. However, the major difference is that while in JavaScript, promises start running upon creation, in Rust, a Future doesn't start executing until you submit it to an executor. This has many implications...
> ...until you submit it to an executor
That's not much different. Don't call the function then which returns that promise :)
Or you can write:
sendRequest(thingThatReturnsPromise);I’m in the process of writing a blog post about this...
// eager
new Promise(resolve => resolve(foo))
// lazy
const bar = () => new Promise(resolve => resolve(foo))
An executor would be something that takes n functions that return Promises and calls them.
I’m not sure what benefit this would bring you in JS.
A Promise is in one of these states: pending, fulfilled, or rejected. When you create a promise, you set a callback function that is the "body" of the promise, and can transition it into the fulfilled or rejected state by calling either of two callbacks passed into it. When you create a Promise, it's in the pending state, but the runtime sets it up to be executed, and when a tick occurs, it will start executing automatically.
In Rust, a Future is something with a poll method that returns either Pending or the final value. If you want JavaScript's behavior around failure, you make the final value a Result, it's not built-in. In Rust, unlike in JavaScript, a Future is inherently inert. Nothing happens until you actively call the poll method of said future. This means that, unlike in JavaScript, you have to either call poll yourself (not recommended) or pass it to something that will. We colloquially call those things "executors." This can lead to surprising behavior if you're used to the JavaScript model; many JS programmers coming to Rust will create a future, and then be surprised when their code compiles but doesn't work. It's usually that they forgot to submit things to an executor.
In both cases, you can chain these things together, which is how they're usually used to produce some bigger computation.
Okay, so from an interface perspective, that's the difference. But the difference goes a bit deeper than that. For example, since Rust futures are nested when you chain them, and because the language is always AOT compiled, a chain of Futures compiles down to a state machine with a perfectly sized stack. Whereas a Promise has a separate object for each step in the chain, with all of the excess allocations and such that implies. I am not 100% sure what the state of the art is in optimizing promises, but in Rust, you always get the most optimized thing, since it builds off of everything else in the language.
Okay that's all I've got for now, this is already too long. This is a complex topic...
If you want the actor model, you can use it! There is nothing stopping you from going thread-per-connection in Rust. It's quite fast on Linux for all but the most demanding workloads. If I were writing an ordinary network service expecting moderate traffic, I'd probably go thread-per-connection.
With heavyweight computations, CPU usage will hit 100% with a small number of concurrent requests, so a thread per request will work fine. Your server will get overloaded before you have too many threads and that load needs to be shed somehow, maybe by putting more servers online.
Even if you're using async-await, using threads for heavyweight requests is recommended anyway. An async function isn't supposed to hog the CPU; instead you outsource to a thread pool.
Besides, Apache is fast enough for most use cases.
Why do you have to say this?
I tend to be a fairly sarcastic person so when I want to make sure it's unambiguous that I'm not, I prefix my questions.
Rust originally had a heavier runtime with a green thread implementation, and it was removed. I believe one of the major considerations at the time was bare metal programming on microcontrollers.
But a few days ago I was writing a small TCP app, and I could not find the timeout argument to Python’s asyncio open_connection.
Then I realised I didn’t need it: I could simply create more complex behaviour by combining async primitives. I don’t even want to imagine how much code I’d need to write in order to implement something like that thread-wise (given that a library simply forgot to add it).
I haven't used Erlang, but how does it deal with blocking calls? Say an actor decides to make a call to the DB. Will the runtime block the current thread the actor is running on?
The other alternative to explicit async/await, which permeates the entire call stack as you pointed out, is to have green threads, like Java's upcoming fibers (see project Loom). The runtime automatically swaps out the current fiber once it makes a blocking call and switches in another non-blocking fiber to continue making progress.
However, for functions that can block indefinitely on I/O, then such an approach would mean keeping an inefficiently-large stack around indefinitely.
Hence, the better solution is to put the data on the heap, ideally in a manually engineered structure (i.e. "manual implementation of futures"), or for more ergonomics in one efficiently designed by the compiler (i.e. async/await).
Seems like forced message passing would be out of place.
Rust was originally going to use fiber threading. The reasons they didn't are lost to me and probably everyone with the amount of bikeshedding async await has seen
Because it was found that you can just put this stuff in user-level libraries, it doesn't need to be part of the core language. This is what Tokio does, it provides a multi-threaded runtime that can be used together with Rust's async facilities. Romio is an experimental project which extends Tokio to work with the new async-await syntax and adds async-IO support, but this work will very likely be folded back into Tokio itself as soon as the underlying features reach stability.
The reason it's even possible to retrofit fibers into old Java code is because all the threading and async stuff is built into the language. Unless you're using native code enabling fibers will be as easy as switching out thread pools that your threads use.