{"slug": "if-you-use-tokio-you-should-override-the-default-allocator", "title": "If you use Tokio, you should override the default allocator", "summary": "Switching a multi-threaded Rust service on Tokio to tikv-jemallocator as the global allocator cut serialization and deserialization time by more than half at the median and about 40% at p99, according to a guest post by Matthew Pope. Pope's team traced production serde latency that was more than 9× the client-side p50 of the equivalent Java identity operation to contention for the default global allocator, after CPU profiles showed over 40% of production CPU work went to serialization and deserialization. The fix was a two-line change declaring tikv_jemallocator::Jemalloc as the #[global_allocator].", "body_md": "This is a guest post from Matthew Pope. I spend a lot of time telling folks to not use the default allocator, this post captures a lot of the \"why.\" — Russell\n\n*AI was used to assist with organizing and editing this post, and was\nespecially helpful at criticizing me whenever I contradicted myself.*\n\nMy team is building a multi-threaded Rust service on Tokio. Our serialization\nand deserialization were many times slower in production than in any benchmark I\ncould run locally, and it was jeopardizing the entire project,<sup>[1](#fn-caveat-footnote)</sup>\nbut it turned out that the serialization library was only a minor part of the\nproblem. Once we figured out that we were seeing symptoms of contention for the\nglobal allocator, one of the most impactful fixes ended up being very simple.\n\n```\n#[global_allocator]\nstatic GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;\n```\n\nWith a two-line change to use [`tikv-jemallocator`](https://crates.io/crates/tikv-jemallocator) as the\nglobal allocator, we were able to cut serialization and deserialization time by\nmore than half at the median and by about 40% at p99.\n\nIf you have a concurrent Rust application and allocator frames are noticeable in\nyour flame graph, one of the first steps you should consider is [changing the\nglobal allocator](https://nnethercote.github.io/perf-book/build-configuration.html#alternative-allocators). Though it was not the only fix we\nneeded, it was a simple change with a high payoff.\n\n## The problem\n\nWe're building a service in Rust that runs pluggable business logic against\nstructured data, at high request rates and with tight latency targets. Clients\nsend requests to it as [Amazon Ion](https://amazon-ion.github.io/ion-docs/), which we chose for its rich types,\nself-describing nature, and efficient binary format. Every request takes the\nsame path through the service. A Tokio worker reads the HTTP payload,\ndeserializes it into our domain model using [ion-rs](https://github.com/amazon-ion/ion-rust), and dispatches the\nwork to a separate worker pool (the business logic can't share threads with the\nasync runtime). The worker pool runs the business logic and hands back a\nresponse, which a Tokio worker serializes and sends back to the client.\n\nWe knew that `ion-rs` was not as fast as the more mature `ion-java`. On\nsingle-threaded tests, `ion-rs` 1.0.1 read our payloads at a little less than\nhalf the throughput of `ion-java`. However, it came as a surprise when some of\nour initial CPU profiles suggested that more than 40% of the total CPU work done\nin production was related to serialization and deserialization, so we started to\ndig deeper.\n\n### Replicating the problem in production\n\nTo measure serialization and deserialization (\"serde\") in isolation, we added an identity operation to the service. It deserializes an Ion request (ranging 40–400 kB in this case) into our domain model, performs trivial business logic (i.e., the identity function), and serializes it straight back. Nothing significant happens in the request, so changes to serde show up directly in latency (and we have specific serde metrics too), and we can profile serde under real load. We also have a traffic file that we captured from real-world traffic so that we know we have representative data. (The identity operation is also the worst case for serde. More on that later.)\n\nThe identity operation confirmed the problem. Our server-side p50 latency was\nmore than 9× the client-side p50 latency of the equivalent identity operation on\nthe Java system the service is replacing. Comparing our server-side latency to\ntheir client-side latency understates the gap, so the real number is\nworse.<sup>[2](#fn-server-side-footnote)</sup> However, a parser that is ~2.3× slower doesn't\nexplain a 9× gap, and local benchmarks only confounded the problem. When I\nbenchmarked the same payloads single-threaded on a development server with an\nolder CPU (Graviton2 rather than the Graviton4 we run in production, but the\nsame vCPU count and memory), the results were still much faster than in\nproduction.\n\n### Normalizing by the amount of work\n\nIt is hard to compare a benchmark with production using elapsed time alone. Real\npayloads vary in size and shape, so they don't all do the same amount of work.\nTo get a slightly more stable point of comparison, I divided the request size by\nthe deserialization time to get a throughput in MB/s.[3](#fn-throughput-footnote)\n\n| Workload | Binary Ion deserialization throughput | \n|---|---|\n| Identity operation in production (Graviton4) | 12 MB/s | \n| Real traffic, where application code dominates (Graviton4) | 28 MB/s | \n| Same payloads, single-threaded benchmark (Graviton2) | 38 MB/s | \n\nThe same deserialization code was more than twice as fast on real traffic as on\nthe identity operation. In other words, serde got cheaper in *absolute* terms\nwhen the requests also had real work to do. This suggested that the parser was\nnot the (primary) bottleneck, and I began to suspect that some resource had\ncontention that was specific to the serde portion of the code. At first, I\nsuspected thread oversubscription, with threads waiting for a free CPU core.\n\n### What dial9 showed\n\nWe run [dial9](https://github.com/dial9-rs/dial9) ([introduced here](https://dial9-rs.github.io/blog/dial9-a-flight-recorder-for-rust/)) on some of our production\nservers. Having it enabled meant that we didn't have to guess what was going on\nbecause we had profiles of the service under real load. (dial9 also had\ncorresponding Tokio stats and CPU usage for the same time frame.) The first\nthing we were able to rule out was scheduling delay for Tokio tasks. CPU\nutilization was also too low for threads to be waiting on a free core, so the\nslowness had to be the result of waiting rather than computing. Surprisingly, it\nwas a CPU flame graph that gave the first concrete evidence of the problem.\n\nMost of the samples under `ion_rs` frames weren't parsing Ion at all. In an\nearly profile,<sup>[4](#fn-flamegraph-footnote)</sup> ~63% of samples had a clone or drop frame\non the stack, and ~60% had `malloc`, `free`, or `realloc` on the stack. Only\n~22% were in the reader itself. (These categories overlap, because the\nallocator is called from inside the clones and drops.) Seeing `drop_in_place`,\n`malloc`, and `free` this prominently in a profile is always a red flag.\n\nYou can check this yourself on this flame graph or on your own application's\nprofile by finding the inclusive time<sup>[5](#fn-inclusive-footnote)</sup> for\n`^(malloc|free|realloc|calloc)$`<sup>[6](#fn-symbol-name-footnote)</sup>.\n\nIt is worth noting that those frames sit under `ion_rs` because of the design of\n`ion_rs::Element`, which makes at least one allocation per node in the tree.\nCharging that cost to `ion_rs` is fair, even though the parser isn't where the\ntime goes.\n\nI suspected allocator contention (not just excessive memory use), but I didn't\nyet know how to prove it or have a complete explanation for how it would be\nhappening. I was discussing the problem with a colleague and shared some of our\ndial9 data, and he pointed out that the time spent in `malloc` on a CPU profile\nunderstates the wall-clock cost. If a thread sleeps on a contended allocator\nlock, it's de-scheduled, and a CPU flame graph will not report that time.\n\n## Why freeing on another thread is expensive\n\nMany years ago, I had a computer science class where I had to build a simplified memory allocator. Real-world systems are much more sophisticated, and as I was trying to understand the observed behavior, I learned a lot about low-level system architecture and memory management. What follows is my current understanding of what was happening.\n\nModern allocators typically use thread-local caches (and often a thread-local\narena) so that they don't have to acquire a global lock for every `malloc` and\n`free`. Allocating and freeing on the same thread is fast because it rarely\ntouches anything shared, but when you start freeing memory on a different\nthread, it gets more expensive. The allocator has to return the memory to the\ncache or arena that owns it, which requires synchronizing with the owning\nthread, either through a lock or through atomic operations on a shared list.\n\nSharing between threads also affects the L1 and L2 caches, which are usually\nprivate to each core.<sup>[7](#fn-stalls-footnote)</sup> When one thread builds a tree of small\nnodes and another thread frees them, the cache lines holding those nodes have to\nmove from one core to another, which typically takes tens of nanoseconds per\nline.<sup>[8](#fn-core-to-core-footnote)</sup> A small allocation can share its cache line with\nother small allocations, and if neighboring allocations are being used by\ndifferent threads, you can also get [false sharing](https://en.wikipedia.org/wiki/False_sharing), where two\ncores repeatedly invalidate a cache line even though they aren't logically\nsharing any data.\n\nYou don't have to intentionally pass values between threads for all of this to happen because Tokio's work-stealing scheduler moves tasks between worker threads, and values that are handed from one task (or worker pool) to another get dropped wherever the last reference happens to end up.\n\nThe cross-thread allocation and freeing costs are why the identity operation was the worst case for serde, and why serde ran faster on real traffic (see the table above). With real traffic, the business logic spreads out the allocation-heavy work, whereas the identity operation is nothing but allocation-heavy work.\n\n## Confirming the hypothesis\n\nI ran a three-way comparison between `mimalloc`, `jemalloc`, and the default\nallocator (`glibc`). Because our existing benchmarks could not reproduce the\nproblems we were seeing in production, I created a synthetic workload to more\naccurately reflect the behavior of our production code. It deserialized into the\ndomain model in one thread, passed the value to another thread, and then dropped\nit there. I measured the number of requests per second with a fixed payload\nsize, varying the thread topology and the allocator. (The configurations use\ndifferent numbers of threads, so compare allocators within a row rather than\nacross rows.)\n\n| Configuration | glibc | jemalloc | mimalloc | \n|---|---|---|---|\n| Same thread (16 threads) | 80 req/s | 95 req/s | 98 req/s | \n| 8 producer, 8 consumer threads | 32 req/s | 85 req/s | 81 req/s | \n| 16 producer, 16 consumer threads | 66 req/s | 163 req/s | 145 req/s | \n\nWhen the work stays on one thread, the three allocators are roughly comparable.\n(Although 15–20% slower might be reason enough to stop using `glibc`.) As soon\nas values are freed on a different thread, `glibc` is roughly 2.5× slower than\neither of the others.\n\nWhy is `glibc` so much worse than the others? My best explanation is that\n`glibc`'s thread-local cache (` tcache`) is small (7 entries per size class by\ndefault), so steady, cross-thread traffic overflows the `tcache` on the freeing\nthread and completely drains the `tcache` on the allocating thread, so on both\nsides it falls through to the arena that owns the memory, and the allocating and\nfreeing threads end up contending for that arena's lock. While holding that\nlock, `glibc` also takes time to consolidate adjacent free chunks. `glibc` can\npush small chunks to a \"fastbin\" with an atomic operation, but still needs to\nconsolidate them later in `malloc_consolidate` (which accounted for ~8% of CPU\ntime in our profile). At the time, many of our allocations were too large for\nfastbins. In `ion-rs` 1.0.1, an `ion_rs::Element` alone was 128 bytes, and our\ndomain model carried `Element` s.\n\n`jemalloc` and `mimalloc` serve small allocations from slabs of fixed-size\nslots, so there's nothing to coalesce.\n\nThe choice of `jemalloc` over `mimalloc` was arbitrary. Both represented a\nsignificant improvement over the current state, and at the time we were just\nlooking for improvement rather than perfection. If switching allocators isn't an\noption, raising `glibc`'s tcache size with\n`GLIBC_TUNABLES=glibc.malloc.tcache_count=...` might be worth an experiment. We\ndidn't try it.\n\n## Other fixes\n\nSwitching the allocator doesn't fix all of the problems you might see in that\nflame graph. Other fixes include eliminating the intermediate `ion_rs::Element`\nbetween the serialized Ion and our domain model, deserializing request payloads\ninto a request-scoped arena, moving some of the deserialization work onto the\nworker threads, and contributing performance improvements directly to `ion-rs`\n(for example, [v1.1.0](https://github.com/amazon-ion/ion-rust/releases/tag/v1.1.0)). Some of that work is still ongoing, and\nto discuss it all in detail would be too large for one blog post.\n\n1. \nI wasn't setting out to write a blog post when this occurred. I was just trying to address a latency problem that was so bad it was making the project look infeasible, so I was favoring speed and directional accuracy over scientific rigor and precision. You'll see this show up in this blog post as approximations, inconsistent hardware, and source data for some claims that is missing because the source data was deleted by log retention policies. [↩](#fr-caveat-footnote-1)\n2. \nYou probably noticed that we tracked the server-side latency rather than the client-side latency, even though our goal is ultimately defined in terms of client-side latency. The service's network configuration changed several times during development, so client-side numbers weren't comparable over time. Also, we report p50 latency because it's easy to compare with local benchmarks (Criterion reports medians). [TM99](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Statistics-definitions.html#Percentile-versus-Trimmed-Mean) gave similar\nresults.[↩](#fr-server-side-footnote-1)\n3. \nDifferent shapes do actually require different amounts of work, so using throughput is still not a completely fair comparison, but it can still be helpful as long as you're aware of the limitations. [↩](#fr-throughput-footnote-1)\n4. \nAlthough we started using dial9 around this time, the flame graph I am sharing was not generated by dial9. I lost the dial9 flame graph from that time to an ever-so-punctual S3 lifecycle policy. [↩](#fr-flamegraph-footnote-1)\n5. \nIn a flame graph generated by [inferno](https://github.com/jonhoo/inferno) , press Ctrl+F (or click\n\"Search\") and enter the pattern. The \"Matched\" percentage is the share of\nsamples with a matching frame anywhere on the stack, with nested matches\ncounted once. inferno omits frames narrower than its`--minwidth` setting,\nso generate the flame graph with`--minwidth 0` if you want a complete\ncount.[↩](#fr-inclusive-footnote-1)\n6. \nNote that the symbol names vary by platform and `glibc` version. On the\nserver where this profile data was collected,`perf` resolved`free` to the\nversioned alias`cfree@GLIBC_2.17` . (The suffix is a symbol version, not the\ninstalled`glibc` , which was 2.26. You must include that alias if you want\nto replicate my figures for that flame graph.) If you have the wrong names,\nyou will end up under-counting, so be sure to check the names in your own\nprofile data before trusting any suspiciously small number.[↩](#fr-symbol-name-footnote-1)\n7. \nWhen a core needs a cache line that currently belongs to another core's cache, it has to wait for that line to arrive. This kind of cache miss is called a *coherence miss* . A stalled access keeps the thread scheduled, so\nwhile our flame graph doesn't have a \"stalled_load\" frame, it can hint at\nthe stall as extra samples in the function where the stall occurs. This is\nprobably why`malloc` ,`free` , and`drop_in_place` were so prominent in our\nprofiler data.[↩](#fr-stalls-footnote-1)\n8. \nThe [nviennot/core-to-core-latency](https://github.com/nviennot/core-to-core-latency) repo on GitHub has\na tool for measuring core-to-core latency and published measurements for\nmany architectures.[↩](#fr-core-to-core-footnote-1)", "url": "https://wpnews.pro/news/if-you-use-tokio-you-should-override-the-default-allocator", "canonical_source": "https://dial9-rs.github.io/blog/allocator-contention-in-a-tokio-service/", "published_at": "2026-12-04 16:02:11+00:00", "updated_at": "2026-12-04 16:18:13.670548+00:00", "lang": "en", "topics": ["developer-tools"], "entities": ["Tokio", "Rust", "Matthew Pope", "tikv-jemallocator", "Amazon Ion", "ion-rs", "ion-java", "Graviton4"], "also_reported_by": [], "takeaway": "Declaring tikv_jemallocator::Jemalloc as the global allocator in a concurrent Tokio service cut serde time by more than half at p50 and about 40% at p99 when allocator frames appear in the flame graph.", "recommendation": {"advice": "If allocator frames show up in your concurrent Rust service's flame graph, swap the default global allocator for tikv-jemallocator; the source measured over 50% lower serde latency at p50 and 40% at p99.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/if-you-use-tokio-you-should-override-the-default-allocator", "markdown": "https://wpnews.pro/news/if-you-use-tokio-you-should-override-the-default-allocator.md", "text": "https://wpnews.pro/news/if-you-use-tokio-you-should-override-the-default-allocator.txt", "jsonld": "https://wpnews.pro/news/if-you-use-tokio-you-should-override-the-default-allocator.jsonld"}}