<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shekhar M Bhosale on Medium]]></title>
        <description><![CDATA[Stories by Shekhar M Bhosale on Medium]]></description>
        <link>https://medium.com/@shekhar.m.bhosale?source=rss-6f4747793332------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bF2OyRI_0oJCU3HG</url>
            <title>Stories by Shekhar M Bhosale on Medium</title>
            <link>https://medium.com/@shekhar.m.bhosale?source=rss-6f4747793332------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:44:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shekhar.m.bhosale/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Concurrency in Rust: Tokio, Rayon, and Why It Matters at Planet Scale]]></title>
            <link>https://medium.com/@shekhar.m.bhosale/concurrency-in-rust-tokio-rayon-and-why-it-matters-at-planet-scale-228b5dc2fde3?source=rss-6f4747793332------2</link>
            <guid isPermaLink="false">https://medium.com/p/228b5dc2fde3</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[large-scale-system]]></category>
            <category><![CDATA[rust-programming]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Shekhar M Bhosale]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 09:24:16 GMT</pubDate>
            <atom:updated>2026-08-30T09:24:16.125Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to how Rust actually runs work in parallel, and why that model holds up where others strain.</em></p><h3>Why concurrency in Rust feels different</h3><p>If you’re coming from Java, Go, or Python, the first thing you notice about Rust concurrency is that the language ships with almost nothing and yet gives you more safety than any of them. There’s no built-in thread pool, no bundled async runtime, no ExecutorService. What Rust gives you instead is a compiler that makes entire categories of concurrency bugs (data races, use-after-free across threads, sending a non-thread-safe value where it doesn&#39;t belong) simply <em>fail to compile</em>.</p><p>That compile-time guarantee comes from two marker traits, Send and Sync, woven into the type system:</p><ul><li>Send means a value can be <em>moved</em> to another thread.</li><li>Sync means a value can be <em>shared</em> (by reference) across threads.</li></ul><p>You never implement these by hand for normal code; the compiler derives them. But the moment you try to share something that isn’t safe to share (say, an Rc instead of an Arc), the borrow checker stops you before the program ever runs. In Java, the equivalent mistake, unsynchronized access to shared mutable state, compiles cleanly and blows up as a heisenbug in production at 3 a.m. In Rust, it&#39;s a red squiggle in your editor.</p><p>So the mental model is: <strong>Rust makes concurrency safe by default and leaves the <em>runtime</em> to the ecosystem.</strong> And the ecosystem has produced two dominant, very different tools: <strong>Tokio</strong> and <strong>Rayon</strong>. Understanding when to reach for each is the single most useful thing you can learn about Rust concurrency.</p><h3>The core distinction: concurrency vs. parallelism</h3><p>These words get used interchangeably, but the difference is the whole ballgame:</p><ul><li><strong>Concurrency</strong> is about <em>dealing with many things at once</em>, most of which spend their time <strong>waiting</strong> (for a network response, a disk read, a timer). You want to overlap all that waiting so one CPU can juggle thousands of in-flight operations.</li><li><strong>Parallelism</strong> is about <em>doing many things at once</em>: splitting a <strong>computation</strong> across CPU cores so it finishes faster. Nothing is waiting; every core is pegged.</li></ul><p>Rust has a specialized tool for each:</p><ul><li><strong>Tokio → concurrency</strong> (I/O-bound work)</li><li><strong>Rayon → parallelism</strong> (CPU-bound work)</li></ul><p>Get this mapping right and everything else follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rjuu5fw8ECDTBGzQM90s5Q.png" /></figure><h3>Tokio: concurrency for I/O-bound work</h3><p>Tokio is an <strong>async runtime</strong>. Its job is to let a small number of OS threads drive a huge number of tasks that are mostly waiting on the outside world.</p><p>Here’s the key idea. A Tokio task is not an OS thread; it’s a Future, a lightweight state machine that costs a few hundred bytes. You can have <strong>millions</strong> of them multiplexed onto a worker pool that defaults to one thread per CPU core. Tokio&#39;s scheduler uses <strong>work-stealing</strong>: idle worker threads pull tasks from busy ones&#39; queues, keeping every core productive.</p><pre>// Fetch 10,000 URLs concurrently on a handful of worker threads.<br>use futures::future::join_all;<br>async fn fetch_all(urls: Vec&lt;String&gt;) -&gt; Vec&lt;Result&lt;String, reqwest::Error&gt;&gt; {<br>    let client = reqwest::Client::new();<br>    let requests = urls.iter().map(|url| {<br>        let client = &amp;client;<br>        async move { client.get(url).send().await?.text().await }<br>    });<br>    join_all(requests).await<br>}</pre><p><strong>Tokio is the right tool when:</strong></p><ul><li>You’re building network servers or clients.</li><li>You’re calling many services, databases, or object stores concurrently.</li><li>You have sockets, timers, or high connection counts.</li><li>Your bottleneck is <em>waiting</em>, not computing.</li></ul><p><strong>The rules of the road:</strong></p><ul><li>It’s async/.await all the way down. Async functions can only be .awaited from other async contexts (the famous &quot;function coloring&quot; problem).</li><li>Your I/O must go through async APIs (tokio::fs, reqwest, async storage clients), not their blocking equivalents.</li></ul><h3>The one mistake that wrecks a Tokio app</h3><p>Tokio tasks are <strong>cooperatively scheduled</strong>. A worker thread only switches to another task when the current one hits an .await that isn&#39;t ready. That means if a task <strong>blocks</strong> (a synchronous syscall) or <strong>grinds</strong> (a long CPU loop with no .await), it holds its worker thread hostage, and every other task queued on that thread is frozen behind it. With 8 workers, one blocking call takes out 1/8 of your entire runtime&#39;s capacity.</p><p>The fix is to move that work off the worker threads:</p><pre>// Blocking syscall or blocking library -&gt; spawn_blocking (a separate, growable pool).<br>let contents = tokio::task::spawn_blocking(|| {<br>    std::fs::read_to_string(&quot;huge_file.txt&quot;) // synchronous, blocking<br>}).await??;</pre><p>For <em>heavy CPU computation</em>, spawn_blocking isn&#39;t enough; you want real parallelism. That&#39;s where Rayon comes in.</p><h3>Rayon: parallelism for CPU-bound work</h3><p>Rayon is a <strong>data-parallelism</strong> library. Where Tokio helps you wait efficiently, Rayon helps you <em>compute</em> efficiently by spreading a workload across all your cores with almost no code change.</p><p>The signature move is turning a sequential iterator into a parallel one by changing one word:</p><pre>use rayon::prelude::*;<br>// Sequential<br>let total: u64 = data.iter().map(|x| expensive_transform(x)).sum();<br><br>// Parallel across all cores. That&#39;s the entire change.<br>let total: u64 = data.par_iter().map(|x| expensive_transform(x)).sum();</pre><p>Under the hood, Rayon runs its own work-stealing thread pool sized to your CPU count and splits the work recursively (a technique called <em>fork-join</em>). You don’t manage threads, chunk sizes, or joins; you declare “this is parallelizable” and Rayon handles the rest.</p><p><strong>Rayon is the right tool when:</strong></p><ul><li>You’re transforming or aggregating large collections.</li><li>You’re doing number crunching, parsing, compression, hashing, or image/segment processing.</li><li>The work is CPU-bound and embarrassingly parallel.</li><li>Nothing is waiting; the cores are the bottleneck.</li></ul><p><strong>The one rule:</strong> don’t do blocking I/O or .await inside a Rayon closure. Rayon has no async runtime to drive futures; it&#39;s for pure computation.</p><h3>Tokio vs. Rayon at a glance</h3><p>Each bullet is one dimension, <strong>Tokio</strong> first, then <strong>Rayon</strong>:</p><ul><li><strong>Problem it solves.</strong> Tokio: concurrency (I/O-bound). Rayon: parallelism (CPU-bound).</li><li><strong>Unit of work.</strong> Tokio: a Future/task, hundreds of bytes. Rayon: a slice of a computation.</li><li><strong>Scale.</strong> Tokio: millions of concurrent tasks. Rayon: roughly one task per core.</li><li><strong>Scheduling.</strong> Tokio: cooperative, yields at .await. Rayon: fork-join, work-stealing.</li><li><strong>Best at.</strong> Tokio: waiting on many things. Rayon: computing one thing fast.</li><li><strong>What kills performance.</strong> Tokio: blocking or grinding on a worker thread. Rayon: doing async I/O inside it.</li><li><strong>Canonical use.</strong> Tokio: web servers, service calls, object-storage reads. Rayon: data crunching, parsing, hashing.</li></ul><h3>The combined model: Tokio and Rayon together</h3><p>Real systems rarely fit neatly into one box. A common and healthy architecture is a <strong>Tokio front, Rayon back</strong>: an async service that accepts requests and does I/O with Tokio, but hands CPU-heavy work to a Rayon pool and bridges the result back over a channel so it never stalls a Tokio worker.</p><pre>use tokio::sync::oneshot;<br>async fn handle_request(payload: Vec&lt;u8&gt;) -&gt; Result&lt;Summary, Error&gt; {<br>    let (tx, rx) = oneshot::channel();<br><br>// Offload the CPU-heavy work to Rayon; don&#39;t block the Tokio worker.<br>    rayon::spawn(move || {<br>        let result = heavy_parallel_analysis(&amp;payload); // uses par_iter internally<br>        let _ = tx.send(result);<br>    });<br><br>// The Tokio task yields here and the worker is free to serve other requests.<br>    let summary = rx.await?;<br>    Ok(summary)<br>}</pre><p>This is exactly the shape a <strong>distributed query engine</strong> wants, and it’s worth slowing down here, because it’s the example that made the Tokio-vs-Rayon distinction click for me.</p><h3>First, what is a query engine?</h3><p>A query engine is the system that answers questions like “count the errors from service X in the last hour” over enormous amounts of data. Modern analytical engines store data in a <strong>columnar</strong> format: instead of keeping each record’s fields together, they store each column separately (all the timestamps in one place, all the service names in another, all the message bodies in another). Columns compress well and let a query read only the fields it needs. A <strong>distributed</strong> query engine spreads that data across many files in object storage and across many machines, so a single query fans out, reads lots of files in parallel, scans and filters and aggregates them, and combines the results.</p><p>If you look at where a query engine actually spends its time, it splits cleanly into two very different kinds of work:</p><ul><li><strong>Waiting on data to arrive:</strong> fetching hundreds or thousands of column files from object storage, reading metadata, talking to a catalog. This is I/O-bound, mostly waiting on the network. That’s <strong>Tokio’s job.</strong></li><li><strong>Chewing through the data once it’s in memory:</strong> decompressing, decoding columns, filtering rows, aggregating, sorting, building index structures. This pegs the CPU. That’s <strong>Rayon’s job.</strong></li></ul><p>So a well-built query engine is almost the textbook “Tokio front, Rayon back”: stream the files in concurrently with Tokio, hand each chunk to Rayon to scan and compute, collect results back over a channel.</p><h3>A scenario that teaches the lesson</h3><p>Here’s a common trap that shows what happens when you get this split wrong. Imagine an indexing job that builds small per-column index structures: bloom filters and cardinality sketches, the little summaries a query engine uses to skip files that can’t possibly match a query. The job runs on an async, Tokio-based service, streaming the columnar data in chunk by chunk with .await, which is exactly right for the I/O part.</p><p>The trap is in the <em>computation</em>. Suppose that, for each chunk, the code walks every column one at a time, on a single core, folding values into that column’s sketch and inserting them into that column’s bloom filter. For a narrow dataset that’s fine. But for a very “wide” dataset (one with hundreds or thousands of columns) that serial, single-core work grows and grows until the job blows past its hard timeout and fails. All the heavy lifting is crammed onto one thread while the machine’s other cores sit idle. This is the CPU-bound version of thread starvation: the async runtime is perfectly healthy, but the compute is bottlenecked on a single core it never should have been on.</p><p>The fix is almost embarrassingly small, and it’s the whole point of this article. Each column’s sketch and filter is completely independent of the others (no shared state), so the per-column work is embarrassingly parallel. Hand it to Rayon:</p><pre>use rayon::prelude::*;<br>// Before: every column folded serially on one core.<br>for estimator in &amp;mut estimators {<br>    fold_column(&amp;chunk, estimator);<br>}<br><br>// After: fan the independent per-column work across every core, lock-free.<br>estimators<br>    .par_iter_mut()<br>    .for_each(|estimator| fold_column(&amp;chunk, estimator));</pre><p>That one change, from iter_mut() to par_iter_mut(), spreads the work across every available core. Because the columns are independent, the fills need no locking, and the output is byte-for-byte identical to the serial version; only the wall-clock time changes. The job that used to time out now finishes comfortably, because the wide datasets that were the <em>worst</em> case for serial code are the <em>best</em> case for parallelism: lots of independent columns to spread across cores.</p><h3>The takeaway from that story</h3><p>Tokio was never the problem; it was doing its job (streaming data in) perfectly. The mistake was running heavy, parallelizable CPU work <em>inline</em>, on a single thread, instead of handing it to a tool built for parallelism. <strong>Let Rayon own the compute, let Tokio own the waiting, and connect them with a channel.</strong> Reaching for Tokio alone on a CPU-heavy query workload just starves a worker the moment a scan or aggregation gets big; reaching for Rayon alone leaves you without a clean way to do the concurrent object-storage I/O that feeds it. A serious query engine needs both: Tokio at the I/O edge, Rayon at the compute core.</p><p>For completeness, there’s a third option: <strong>raw </strong>std::thread. Use it for a small, fixed number of long-lived, independent workers (a background log flusher, a single consumer loop, a CLI that runs two things at once) where pulling in a whole runtime is overkill. It&#39;s the wrong tool for either thousands of I/O tasks (use Tokio) or fine-grained parallel compute (use Rayon).</p><h3>How Java does it differently, and why Rust wins at planet scale</h3><p>Java has excellent, mature concurrency. But it makes fundamentally different tradeoffs, and those tradeoffs matter enormously once you’re running fleets of services handling billions of requests.</p><h3>1. Safety: compile-time vs. runtime</h3><p>Java’s concurrency correctness rests on <em>discipline</em>: synchronized, volatile, java.util.concurrent, and the Java Memory Model&#39;s happens-before rules. Nothing stops you from sharing mutable state across threads without synchronization; it compiles fine and corrupts data intermittently under load. Rust makes that same mistake a <strong>compile error</strong> via Send/Sync and ownership. At planet scale, where a one-in-a-billion race <em>will</em> happen many times a day, moving that entire bug class from &quot;runtime incident&quot; to &quot;won&#39;t compile&quot; is a categorical reliability win.</p><h3>2. The threading model: OS threads, virtual threads, and async</h3><p>Historically, a Java thread mapped 1:1 to an OS thread: expensive (~1MB of stack), context-switch-heavy, and capped at thousands. That ceiling is precisely why async runtimes like Tokio exist, to serve hundreds of thousands of connections on a handful of threads.</p><p>Java 21’s <strong>virtual threads</strong> (Project Loom) close much of this gap: millions of cheap green threads multiplexed onto a few carrier OS threads, with the JVM transparently unmounting a virtual thread when it blocks. It’s genuinely great, and it’s more ergonomic than Rust’s async; you write ordinary blocking-style code and it just works, with no function coloring.</p><p>But two structural differences remain at scale:</p><ul><li><strong>No garbage collector.</strong> Rust has no GC pauses. Java’s GC has improved dramatically (ZGC, Shenandoah bring pauses to sub-millisecond), but a GC still consumes CPU and memory headroom, and tail-latency behavior under memory pressure is something you must constantly tune. For latency-sensitive, high-throughput services, Rust’s deterministic, zero-GC memory model means <strong>predictable tail latencies</strong> (the p99.9 that actually defines user experience at scale) without a tuning treadmill.</li><li><strong>Lower, more predictable resource footprint.</strong> Rust’s futures compile to compact state machines with no runtime overhead (“zero-cost abstractions”), and there’s no JVM warmup, no JIT ramp, no per-instance heap to size. In a fleet of thousands of hosts, a service that uses a fraction of the memory and starts instantly translates directly into fewer machines, lower cost, and faster autoscaling and failover.</li></ul><h3>3. Explicit vs. transparent, and why explicit scales</h3><p>Loom hides the yield points inside the runtime; Rust makes them explicit with async/.await. Explicit is less ergonomic, but it means the cost of every suspension point is visible in the code and paid for at compile time, with no managed runtime deciding your scheduling behavior for you. When you&#39;re reasoning about the performance of a system spread across regions and datacenters, <em>predictability</em> beats <em>convenience</em>. There&#39;s no hidden scheduler, no GC, no JIT: what you write is what runs.</p><h3>The honest summary</h3><p>This isn’t “Rust good, Java bad.” Java is more ergonomic, has a deeper standard library, a larger talent pool, and a longer battle-tested track record. If your team knows the JVM and your latency budget is generous, Java 21 with virtual threads is a fantastic, productive choice.</p><p>But for <strong>planet-scale distributed systems</strong>, where tail latency, resource efficiency, and the <em>absence</em> of whole bug classes compound across thousands of hosts and billions of requests, Rust’s model has a real edge. Point by point, <strong>Java</strong> first, then <strong>Rust</strong>:</p><ul><li><strong>Data-race safety.</strong> Java: runtime discipline. Rust: compile-time guarantee.</li><li><strong>GC pauses.</strong> Java: yes (tunable, small). Rust: none.</li><li><strong>Memory footprint.</strong> Java: higher (JVM heap). Rust: low and predictable.</li><li><strong>Startup.</strong> Java: JVM warmup + JIT ramp. Rust: instant, native.</li><li><strong>Massive I/O concurrency.</strong> Java: virtual threads (transparent). Rust: Tokio tasks (explicit).</li><li><strong>CPU parallelism.</strong> Java: ForkJoinPool / parallel streams. Rust: Rayon.</li><li><strong>Ergonomics.</strong> Java: higher. Rust: lower (explicit async).</li><li><strong>Tail-latency predictability.</strong> Java: good, but requires tuning. Rust: excellent, by construction.</li></ul><h3>Takeaways</h3><ol><li><strong>Concurrency is not parallelism.</strong> Tokio for I/O-bound waiting; Rayon for CPU-bound computing.</li><li><strong>Tokio tasks are cheap but cooperative:</strong> never block or grind on a worker thread. Offload blocking work with spawn_blocking and CPU work to Rayon.</li><li><strong>Rayon parallelizes computation</strong> with a one-word change (iter becomes par_iter) and its own work-stealing pool.</li><li><strong>Combine them:</strong> Tokio for the I/O edge, Rayon for the compute core, a channel in between. For a query engine, let Rayon lead the scan/aggregate work and Tokio feed it from object storage.</li><li><strong>Rust’s safety is compile-time</strong>, and its zero-GC, low-footprint, predictable model is what makes it shine at planet scale, where Java, for all its strengths, pays in GC, warmup, and runtime-discovered races.</li></ol><p>Rust asks more of you up front: explicit async, a strict borrow checker, a runtime you assemble yourself. In return, it hands you concurrency that’s safe by construction and performance that stays predictable no matter how many machines you spread it across. At planet scale, that trade is often exactly the one worth making.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=228b5dc2fde3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>