Principles for Fast Tokio Applications

(dial9-rs.github.io)

213 points | by carllerche 18 hours ago

8 comments

  • saghm 13 hours ago

    "Be careful with mutexes" is good advice, but I'm surprised it doesn't explicitly call out the various channels that tokio provides as alternatives (detailed here: https://docs.rs/tokio/latest/tokio/sync/index.html). There are a variety of options that fit different use cases, and you don't even need to enable the runtime feature to use them (e.g. if you want to do a single check for completion rather than await). I'd estimate that at least half of the bottlenecks I've seen with mutexes when using tokio could have been avoided by not even using a mutex at all and instead passing the data that's truly needed across different tasks with some type of channel.

    The other trick I've used a few times that's a bit hacky but can get the job done is when reading a snapshot of the data under a mutex is enough without needing to prevent other changes; if that's the case, you can just clone the data and drop the mutex to allow other uses move forward at the cost of the data potentially being stale.

    • CoolestBeans 10 hours ago

      Tasks and channels is the way. You can get something that feels like programming a real preemptive concurrency model like BEAM languages or golang but with minimal overhead.

      • eru 3 hours ago

        When you send a message in Erlang, nothing the recipient does with the message impacts anything on the sender side. That's good!

        In principle, they could have used something like copy-on-write for this, but in practice they really just make a copy of the bytes.

        Alas in Go, when you mutate what you received on a channel, you mutate the object the sender might still be holding. That's pretty annoying. It gets worse, because Golang has no way to declare something as `const` (like in C) nor that you are holding an immutable borrow (like in Rust). So you need to rely on conventions and perhaps a linter.

        Slighty less of a tangent: task and channels and software transactional memory (STM) are all great. I see mutexes as more of an implementation detail that you can use to implement these higher level abstractions (but they aren't the only way).

        • SwtCyber 2 hours ago

          Give a task ownership of some state, communicate through channels and suddenly a lot of locking just disappears from the design

        • SwtCyber 2 hours ago

          I think channels deserve more emphasis here too, especially because they change the architecture rather than just swapping synchronization primitives

          • rusbus 11 hours ago

            (I am OP) Both good call outs. Will update the article to include them

            • saghm 10 hours ago

              Awesome! I was pretty confident you already were aware of both of those based on the level of knowledge needed for everything else in there, so I mostly was mentioning them here in case some people here might find them useful. Adding them in for others is even better though!

            • jimbob45 7 hours ago

              Why use mutexes (mutices?) over semaphores?

              • LoganDark 7 hours ago

                Aren't semaphores a more fundamental primitive that is trickier to get right? Otherwise, the mutex guards in Rust are very ergonomic.

                • lkirkwood 6 hours ago

                  Semaphores are more general for sure. The common semaphore is just a counter, when you lock it you decrement the counter by one atomically. Therefore a mutex is just a semaphore with a limit of 1. I wouldn't say they're much trickier to get right, maybe just less frequently applicable in e.g. general web io tasks.

            • SwtCyber 2 hours ago

              One thing I appreciate here is treating scheduler fairness as something you spend, not something you get for free

              • dist1ll 15 hours ago

                When you're at a point of tuning Tokio, consider taking a look at ef_vi/DPDK + SPDK

                • kev009 12 hours ago

                  I don't think there is a ton of overlap. tokio is appropriate for general userspace apps, ranging anywhere from a CLI, GUI, API or web app. DPDK and SPDK are specialized fast paths for building network data paths and storage solutions that come with tradeoffs: DPDK uses poll mode drivers, outside of the operating system, which have various implications including busy waiting and taking over the interface. That is why DPDK is fast, no kernel/userspace context switching and copies, and the drivers are tuned for the polling model. But it's not a general purpose building block.

                  • dist1ll 11 hours ago

                    Fwiw with ef_vi you have full control over the event queue - you don't need to busy-spin it, you can choose whatever strategy you prefer.

                    > tokio is appropriate for general userspace apps

                    Yep, and for those I wouldn't recommend it. But tokio is also widely used in performance-critical infrastructure and web services. For those I'd say it can definitely be worth taking a second look at kernel bypass.

                  • rusbus 13 hours ago

                    Do you have any resources worth referencing on this? I assume this isn't something that works with tokio more of a replace tokio?

                  • 5ersi 13 hours ago

                    For a true high performance you should use thread busy-spinning, CPU pinning and SPSC/MPSC ring buffers.

                    • VorpalWay 13 hours ago

                      It all depends on what you are doing. I do embedded with strict realtime requirements. CPU pinning would not be an option. I have also done software that should use as little resources as possible (but still be quick) to coexist with other software on the same hardware.

                      All of these are different, valid, meanings of high performance. You need context. An interactive IDE is yet another thing that needs to be high performance in yet another way.

                      • mahboi 10 hours ago

                        Also, using 100% CPU without a good reason can cause thermal throttling that makes it slower for the sections that actually need 100% CPU

                      • HackerThemAll 37 minutes ago

                        Spinning is covered in the article.

                      • Tsarp 17 hours ago

                        One great use of agentic coding is being able to add and very granular tracing instrumentation to help with these sort of optimizations.

                        • jeffbee 17 hours ago

                          Also a great way to make sure that your app spends most of its time in observability overhead. For example even the latency histogram that the OP mentions is wildly expensive.

                          • Veserv 16 hours ago

                            That just sounds like bad tracing implementations. A good tracing implementation should be able to drive gigabytes per second of trace logs to memory. If you are generating it slow enough to allow actual offload then you should be in the 1—10% range even if you are saturating your offload.

                            You should, of course, upper bound this overhead by switching to a full time travel debugging solution, thus tracing everything, when you get to the 10-30% range.

                            The only way you get to “majority” is if your trace implementation is slower than time travel debugging and provides less information, but then why choose something worse in every dimension.

                            • jeffbee 15 hours ago

                              I'm just reporting from the trenches here. I think you are suggesting that everyone is aware of and capable of using state-of-the-art (from 20 years ago) tracing schemes like XRay[1], when in reality they are not. Most projects would be well-served by any basic profiler but even profiling is apparently for wizards, because I've seen a lot of projects that will resort to manually annotating functions with OTel trace spans, which are ~millions of times more expensive than function calls. Even eBPF uprobe/uretprobe is 100x more expensive than XRay, at a minimum. HotSpot's JFR is like a miracle compared to what people suffer through to diagnose Rust+Tokio.

                              1: https://llvm.org/docs/XRay.html ... is there even a Rust analog to this?

                              • RealityVoid 13 hours ago

                                Huh, it seems xray puts blank trampolines all over your binary? That sounds pretty nifty but I would expect it to be pretty language agnostic, ish? Adding support should be doable for Rust as well, right? Anyways, pretty nifty.

                                I am by no means an expert, but I've recently improved performance for some code and used tracy. They have rust bindings as well. It's pretty cool and it seems to be low overhead. Wonder if I can couple it with something like xray? Tracy is more the tracing library + tracing interpretations/aquisition tool.

                                Edit: apparently rust already supports xray natively on the nightly.

                                • duped 15 hours ago

                                  Not even an analog: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/...

                                  It's worth pointing out though that just tracing function calls isn't good enough for the kinds of stackless coroutines that run in async Rust tasks. You need a way of mapping between the async tasks and the compiler emitted traces.

                                  afaik, C/C++ have the same problem.

                                  • jeffbee 13 hours ago

                                    The difference is nobody in the C++ community believes that a dominant asynchronous executor library exists, and there is not a pervasive belief that it would be helpful.

                                    • duped 12 hours ago

                                      The "C++ community", if it even exists, barely believes in sharing code let alone any library being "dominant." They'd have to agree on a build system first, after all.

                                      But honestly that's a mischaracterization of the situation in Rust. Tokio is popular for networked service backends. If that's the wheelhouse you're in then yea it might look "dominant."

                                      • ablob 11 hours ago

                                        You don't need a build system to share code.

                                        You can share with header files and respective (shared) object files regardless of the build system you're using. Likewise you could just share the source. None of this needs a build system.

                                        • duped 10 hours ago

                                          I was just being a bit sardonic because the C++ ecosystem is so fragmented that something like tokio couldn't really exist. It would be one of three executors in boost, abseil, or folly, and you would never see the kind of downstream ecosystem build on top of them because C++ shops are allergic to external dependencies.

                              • nicoburns 17 hours ago

                                One legitimately great thing about LLMs is that it makes it feasible to add these kind of tracing instrumentations temporarily for profiling and then throw them away so they never reach source control let alone production.

                                • shim__ 1 hour ago

                                  Reaching source control is fine as long as there is a compile time flag to disable the whole thing, which tokio-tracing does

                                  • jeffbee 17 hours ago

                                    I can get an LLM to trace my incomprehensible Tokio application which was also written by an LLM, which is why I don't understand its behavior. Truly the future we were promised.

                                • rusbus 13 hours ago

                                  Was this in a specific application? I wouldn't necessarily expect that histogram to be particularly bad for most applications.

                                  • jeffbee 13 hours ago

                                    Reading the clock every time you jump into a closure is in fact incredibly wasteful, and is exacerbated by chopping work up into tiny chunks for questionable reasons.

                                  • foota 16 hours ago

                                    Just curious, why? Is this true even if you did something like a per-CPU histogram that uses atomic ops to increment?

                                    • jeffbee 13 hours ago

                                      If you have a per-cpu metric there would not be a reason to use atomic instructions to mutate it.

                                      • loeg 9 hours ago

                                        In general your unpinned userspace threads will hit the same CPU 99.99% of the time, but not 100%.

                                        • jeffbee 7 hours ago

                                          Sure. You get the pointer, you lock the mutex, 99.99% of the time that is uncontended, then you set all the metrics and release it.

                                          • loeg 4 hours ago

                                            Taking the mutex uses (uncontended) atomic ops.

                                    • MomsAVoxell 17 hours ago

                                      If you’re not using eBPF to trace your app you’re doing it wrong.

                                      • MobiusHorizons 11 hours ago

                                        Doesn’t that only work on Linux? And then only for things that make syscalls? Presumably people have to trace other slow paths sometime.

                                        • jeffbee 17 hours ago

                                          The low cost of eBPF tracing is another myth.

                                          • MomsAVoxell 15 hours ago

                                            1) Its no myth, but you can definitely foot-bullet into doing it wrong, and 2) it's a far better path to take than in-app telemetry.

                                    • jeffbee 17 hours ago

                                      All of the significant server applications I have encountered in the industry have suffered from the same problem, which surprised their authors but seemed obvious to me: the application was spending the majority of its CPU time doing meta-work like entering and leaving epoll, stealing work from itself, etc. There are principles for writing Tokio servers and these are good points in the OP but I think they are little-known and too easy to violate.

                                      • cube00 17 hours ago

                                        I can't say I'm surprised when I see the 100+ function stack traces that Axum built on Tokio produces.

                                        Before you say Axum is "holding it wrong" the project lives under the tokio-rs GitHub org.

                                        • rusbus 15 hours ago

                                          Note that most of those end up getting inlined in practice

                                        • prydt 11 hours ago

                                          Do you have any references for these principles for writing Tokio servers? Or just a high level summary of what best practices look like?

                                        • iberator 11 hours ago

                                          What the hell is Tokio? Articles mentions it like once I was expecting some programing principles from Japan

                                        • denizay 9 hours ago

                                          Fast Tokioo, drift, drift, drift!