Skip to content

Commit 0e2561e

Browse files
authored
Merge pull request #144 from guswynn/patch-2
Barbara compares some cpp code (and has a performance problem)
2 parents 6c5b671 + 34d0c75 commit 0e2561e

File tree

1 file changed

+137
-0
lines changed

1 file changed

+137
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
# 😱 Status quo stories: Barbara compares some code (and has a performance problem)
2+
3+
## 🚧 Warning: Draft status 🚧
4+
5+
This is a draft "status quo" story submitted as part of the brainstorming period. It is derived from real-life experiences of actual Rust users and is meant to reflect some of the challenges that Async Rust programmers face today.
6+
7+
If you would like to expand on this story, or adjust the answers to the FAQ, feel free to open a PR making edits (but keep in mind that, as they reflect peoples' experiences, status quo stories [cannot be wrong], only inaccurate). Alternatively, you may wish to [add your own status quo story][htvsq]!
8+
9+
## The story
10+
11+
Barbara is recreating some code that has been written in other languages they have some familiarity with. These include C++, but
12+
also GC'd languages like Python.
13+
14+
This code collates a large number of requests to network services, with each response containing a large amount of data.
15+
To speed this up, Barbara uses `buffer_unordered`, and writes code like this:
16+
17+
```rust
18+
let mut queries = futures::stream::iter(...)
19+
.map(|query| async move {
20+
let d: Data = self.client.request(&query).await?;
21+
d
22+
})
23+
.buffer_unordered(32);
24+
25+
use futures::stream::StreamExt;
26+
let results = queries.collect::<Vec<Data>>().await;
27+
```
28+
29+
Barbara thinks this is similar in function to things she has seen using
30+
Python's [asyncio.wait](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait),
31+
as well as some code her coworkers have written using c++20's `coroutines`,
32+
using [this](https://github.com/facebook/folly/blob/master/folly/experimental/coro/Collect.h#L321):
33+
34+
```C++
35+
std::vector<folly::coro::Task<Data>> tasks;
36+
for (const auto& query : queries) {
37+
tasks.push_back(
38+
folly::coro::co_invoke([this, &query]() -> folly::coro::Task<Data> {
39+
co_return co_await client_->co_request(query);
40+
}
41+
)
42+
}
43+
auto results = co_await folly:coro::collectAllWindowed(
44+
move(tasks), 32);
45+
```
46+
47+
However, *the Rust code performs quite poorly compared to the other impls,
48+
appearing to effectively complete the requests serially, despite on the surface
49+
looking like effectively identical code.*
50+
51+
While investigating, Barbara looks at `top`, and realises that her coworker's C++20 code sometimes results in her 16 core laptop using 1600% CPU; her Rust async code never exceeds 100% CPU usage. She spends time investigating her runtime setup, but Tokio is configured to use enough worker threads to keep all her CPU cores busy. This feels to her like a bug in `buffer_unordered ` or `tokio`, needing more time to investigate.
52+
53+
Barbara goes deep into investigating this, spends time reading how `buffer_unordered` is
54+
implemented, how its underlying `FuturesUnordered` is implemented, and even thinks about
55+
how polling and the `tokio` runtime she is using works. She evens tries to figure out if the
56+
upstream service is doing some sort of queueing.
57+
58+
Eventually Barbara starts reading more about c++20 coroutines, looking closer at the folly
59+
implementation used above, noticing that is works primarily with *tasks*, which are not exactly
60+
equivalent to rust `Future`'s.
61+
62+
Then it strikes her! `request` is implemented something like this:
63+
64+
```rust
65+
impl Client {
66+
async fn request(&self) -> Result<Data> {
67+
let bytes = self.inner.network_request().await?
68+
Ok(serialization_libary::from_bytes(&bytes)?)
69+
}
70+
}
71+
```
72+
73+
The results from the network service are sometimes (but not always) VERY large, and the `BufferedUnordered` stream is contained within 1 tokio task.
74+
**The request future does non-trivial cpu work to deserialize the data.
75+
This causes significant slowdowns in wall-time as the the process CAN BE bounded by the time it takes
76+
the single thread running the tokio-task to deserialize all the data.**
77+
This problem hadn't shown up in test cases, where the results from the mocked network service are always small; many common uses of the network service only ever have small results, so it takes a specific production load to trigger this issue, or a large scale test.
78+
79+
The solution is to spawn tasks (note this requires `'static` futures):
80+
81+
```rust
82+
let mut queries = futures::stream::iter(...)
83+
.map(|query| async move {
84+
let d: Data = tokio::spawn(
85+
self.client.request(&query)).await??;
86+
d
87+
})
88+
.buffer_unordered(32);
89+
90+
use futures::stream::StreamExt;
91+
let results = queries.collect::<Vec<Data>>().await;
92+
```
93+
94+
Barbara was able to figure this out by reading enough and trying things out, but had that not worked, it
95+
would have probably required figuring out how to use `perf` or some similar tool.
96+
97+
Later on, Barbara gets surprised by this code again. It's now being used as part of a system that handles a very high number of requests per second, but sometimes the system stalls under load. She enlists Grace to help debug, and the two of them identify via `perf` that all the CPU cores are busy running `serialization_libary::from_bytes`. Barbara revisits this solution, and discovers `tokio::task::block_in_place` which she uses to wrap the calls to `serialization_libary::from_bytes`:
98+
```rust
99+
impl Client {
100+
async fn request(&self) -> Result<Data> {
101+
let bytes = self.inner.network_request().await?
102+
Ok(tokio::task::block_in_place(move || serialization_libary::from_bytes(&bytes))?)
103+
}
104+
}
105+
```
106+
107+
This resolves the problem as seen in production, but leads to Niklaus's code review suggesting the use of `tokio::task::spawn_blocking` inside `request`, instead of `spawn` inside `buffer_unordered`. This discussion is challenging, because the tradeoffs between `spawn` on a `Future` including `block_in_place` and `spawn_blocking` and then not spawning the containing `Future` are subtle and tricky to explain. Also, either `block_in_place` and `spawn_blocking` are heavyweight and Barbara would prefer to avoid them when the cost of serialization is low, which is usually a runtime-property of the system.
108+
109+
110+
## 🤔 Frequently Asked Questions
111+
112+
### **Are any of these actually the correct solution?**
113+
* Only in part. It may cause other kinds of contention or blocking on the runtime. As mentioned above, the deserialization work probably needs to be wrapped in something like [`block_in_place`](https://docs.rs/tokio/1/tokio/task/fn.block_in_place.html), so that other tasks are not starved on the runtime, or might want to use [`spawn_blocking`](https://docs.rs/tokio/1/tokio/task/fn.spawn_blocking.html). There are some important caveats/details that matter:
114+
* This is dependent on how the runtime works.
115+
* `block_in_place` + `tokio::spawn` might be better if the caller wants to control concurrency, as spawning is heavyweight when the deserialization work happens to be small. However, as mentioned above, this can be complex to reason about, and in some cases, may be as heavyweight as `spawn_blocking`
116+
* `spawn_blocking`, at least in some executors, cannot be cancelled, a departure from the prototypical cancellation story in async Rust.
117+
* "Dependently blocking work" in the context of async programming is a hard problem to solve generally. https://github.com/async-rs/async-std/pull/631 was an attempt but the details are making runtime's agnostic blocking are extremely complex.
118+
* The way this problem manifests may be subtle, and it may be specific production load that triggers it.
119+
* The outlined solutions have tradeoffs that each only make sense for certain kind of workloads. It may be better to expose the io aspect of the request and the deserialization aspect as separate APIs, but that complicates the library's usage, lays the burden of choosing the tradeoff on the callee (which may not be generally possible).
120+
### **What are the morals of the story?**
121+
* Producing concurrent, performant code in Rust async is not always trivial. Debugging performance
122+
issues can be difficult.
123+
* Rust's async model, particularly the blocking nature of `polling`, can be complex to reason about,
124+
and in some cases is different from other languages choices in meaningful ways.
125+
* CPU-bound code can be easily hidden.
126+
127+
### **What are the sources for this story?**
128+
* This is a issue I personally hit while writing code required for production.
129+
130+
### **Why did you choose *Barbara* to tell this story?**
131+
That's probably the person in the cast that I am most similar to, but Alan
132+
and to some extent Grace make sense for the story as well.
133+
134+
### **How would this story have played out differently for the other characters?**
135+
* Alan: May have taken longer to figure out.
136+
* Grace: Likely would have been as interested in the details of how polling works.
137+
* Niklaus: Depends on their experience.

0 commit comments

Comments
 (0)