by jeffbee · 2w ago · 0 comments
Rust's async situation is still a pain in many ways.
But throwing Rayon at something often results in very reasonable parallel performance gains without cluttering things much. It usually won't get you to an optimal solution, but it's good for 80% with 10% of the pain.
The performance oriented (data plane) work happens on dedicated, cpu-pinned threads and sockets outside the tokio runtime. The control plane work happens in tokio async. Interaction between the two is tricky. But decreased latency and increased throughput is valuable. And it's a complex server, so we can't really try too many approaches.
It certainly doesn't help that the data structures are, by necessity, a cephalopod that have to be used across threads.
Everything wants to push you down the path of using `ARC<Thing>` even when `Thing` is immutable or the lifetime can be mostly guaranteed.
Here's an example of that problem. Let's say I want to do 2 things concurrently against the same data set. I might want to write code that looks like this:
let v = vec![1, 2, 3];
let taskA = tokio::spawn(async {
println!("Here's a vec: {:?}", v);
});
let taskB = tokio::spawn(async {
println!("Here's a vec: {:?}", v);
});
tokio::join!(taskA, taskB);
But that immediately gets you in hot water because "async block may outlive the current function, but
it borrows `v`, which is owned by the current function"Now, you and I can clearly see that the async block does not, in fact, outlive the current function. However, AFAIK, there's no real way to convince rust that that is the case.
So now even though `v` is immutable, making this a thread safe operation, we need to introduce unnecessary concurrency constructs or break out unsafe in order to force the language to recognize that "Yes, you can trust me".
For rust to actually be fast with concurrent operations, it needs to be smarter about lifetimes in terms of async.
I thought we as an industry had hopefully moved past "async == magic code-go-fast sauce", but apparently we have not.
As much as Go annoys me, you're right there as well. I have to admit that Go did "solve" the make-concurrency-and-parallelism-accessible (and relatively safe) space in a way that very, very few other programming languages did (and none that people widely use).
Java already did, especially now with virtual threads. Now other JVM languages can also get this benefit.
Erlang, as the adjacent comment points, out, did solve that! But at such a significant runtime (performance/memory) and syntactic cost that it's very rarely used, even nowadays after the Elixir renaissance.
Loop-blocking-as-backpressure is sometimes the right move, but only rarely. If you can isolate event loops for specific workloads (e.g. some shameless self promotion, releasing in PyPi this week: https://github.com/zbentley/async-anywhere/blob/main/src/asy...) that becomes a more tractable approach.