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

AI was used to assist with organizing and editing this post, and was especially helpful at criticizing me whenever I contradicted myself.

My team is building a multi-threaded Rust service on Tokio. Our serialization and deserialization were many times slower in production than in any benchmark I could run locally, and it was jeopardizing the entire project,1 but it turned out that the serialization library was only a minor part of the problem. Once we figured out that we were seeing symptoms of contention for the global allocator, one of the most impactful fixes ended up being very simple.

#[global_allocator]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

With a two-line change to use tikv-jemallocator as the global allocator, we were able to cut serialization and deserialization time by more than half at the median and by about 40% at p99.

Hourly p50, p90, and p99 server-side latency for the identity operation from September 9 to 18. At the point marked switch to jemalloc, p50 drops from about 20 ms to 9 ms, p90 from about 30 ms to 15 ms, and p99 from about 49 ms to 28 ms, and all three stay flat afterward.

Hourly server-side latency percentiles for the identity operation, which is almost entirely serialization and deserialization. Switching the global allocator to `jemalloc` cut latency by more than half at the median and by about 40% at p99, and it stayed there.

If you have a concurrent Rust application and allocator frames are noticeable in your flame graph, one of the first steps you should consider is changing the global allocator. Though it was not the only fix we needed, it was a simple change with a high payoff.

The problem

We're building a service in Rust that runs pluggable business logic against structured data, at high request rates and with tight latency targets. Clients send requests to it as Amazon Ion, which we chose for its rich types, self-describing nature, and efficient binary format. Every request takes the same path through the service. A Tokio worker reads the HTTP payload, deserializes it into our domain model using ion-rs, and dispatches the work to a separate worker pool (the business logic can't share threads with the async runtime). The worker pool runs the business logic and hands back a response, which a Tokio worker serializes and sends back to the client.

Sequence diagram with three participants: client, Tokio server worker, and business logic worker pool. The client sends an Ion request to the Tokio server worker, which deserializes it and allocates the domain model. The worker dispatches the work to the business logic worker pool, which runs the business logic, drops the request, and allocates the response. The pool returns the response to the Tokio server worker, which serializes it, drops the response, and sends the Ion response to the client.

We knew that ion-rs was not as fast as the more mature ion-java. On single-threaded tests, ion-rs 1.0.1 read our payloads at a little less than half the throughput of ion-java. However, it came as a surprise when some of our initial CPU profiles suggested that more than 40% of the total CPU work done in production was related to serialization and deserialization, so we started to dig deeper.

Replicating the problem in production

To 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.)

The identity operation confirmed the problem. Our server-side p50 latency was more than 9× the client-side p50 latency of the equivalent identity operation on the Java system the service is replacing. Comparing our server-side latency to their client-side latency understates the gap, so the real number is worse.2 However, a parser that is ~2.3× slower doesn't explain a 9× gap, and local benchmarks only confounded the problem. When I benchmarked the same payloads single-threaded on a development server with an older CPU (Graviton2 rather than the Graviton4 we run in production, but the same vCPU count and memory), the results were still much faster than in production.

Normalizing by the amount of work

It is hard to compare a benchmark with production using elapsed time alone. Real payloads vary in size and shape, so they don't all do the same amount of work. To get a slightly more stable point of comparison, I divided the request size by the deserialization time to get a throughput in MB/s.3

WorkloadBinary Ion deserialization throughput
Identity operation in production (Graviton4)12 MB/s
Real traffic, where application code dominates (Graviton4)28 MB/s
Same payloads, single-threaded benchmark (Graviton2)38 MB/s

The same deserialization code was more than twice as fast on real traffic as on the identity operation. In other words, serde got cheaper in absolute terms when the requests also had real work to do. This suggested that the parser was not the (primary) bottleneck, and I began to suspect that some resource had contention that was specific to the serde portion of the code. At first, I suspected thread oversubscription, with threads waiting for a free CPU core.

What dial9 showed

We run dial9 (introduced here) on some of our production servers. Having it enabled meant that we didn't have to guess what was going on because we had profiles of the service under real load. (dial9 also had corresponding Tokio stats and CPU usage for the same time frame.) The first thing we were able to rule out was scheduling delay for Tokio tasks. CPU utilization was also too low for threads to be waiting on a free core, so the slowness had to be the result of waiting rather than computing. Surprisingly, it was a CPU flame graph that gave the first concrete evidence of the problem.

CPU flame graph of the identity operation. Wide towers of clone, drop, malloc, and free frames sit under the Ion deserialization and serialization code, while the Ion reader itself is a much smaller part of the graph.

An early CPU flame graph of the identity operation, with service-specific names replaced by placeholders. The preview shows the bottom of the graph; open it for the full, interactive version, where you can zoom in and search for frames.

Most of the samples under ion_rs frames weren't parsing Ion at all. In an early profile,4 ~63% of samples had a clone or drop frame on the stack, and ~60% had malloc, free, or realloc on the stack. Only ~22% were in the reader itself. (These categories overlap, because the allocator is called from inside the clones and drops.) Seeing drop_in_place, malloc, and free this prominently in a profile is always a red flag.

You can check this yourself on this flame graph or on your own application's profile by finding the inclusive time5 for ^(malloc|free|realloc|calloc)$6.

It is worth noting that those frames sit under ion_rs because of the design of ion_rs::Element, which makes at least one allocation per node in the tree. Charging that cost to ion_rs is fair, even though the parser isn't where the time goes.

I suspected allocator contention (not just excessive memory use), but I didn't yet know how to prove it or have a complete explanation for how it would be happening. I was discussing the problem with a colleague and shared some of our dial9 data, and he pointed out that the time spent in malloc on a CPU profile understates the wall-clock cost. If a thread sleeps on a contended allocator lock, it's de-scheduled, and a CPU flame graph will not report that time.

Why freeing on another thread is expensive

Many 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.

Modern allocators typically use thread-local caches (and often a thread-local arena) so that they don't have to acquire a global lock for every malloc and free. Allocating and freeing on the same thread is fast because it rarely touches anything shared, but when you start freeing memory on a different thread, it gets more expensive. The allocator has to return the memory to the cache or arena that owns it, which requires synchronizing with the owning thread, either through a lock or through atomic operations on a shared list.

Sharing between threads also affects the L1 and L2 caches, which are usually private to each core.7 When one thread builds a tree of small nodes and another thread frees them, the cache lines holding those nodes have to move from one core to another, which typically takes tens of nanoseconds per line.8 A small allocation can share its cache line with other small allocations, and if neighboring allocations are being used by different threads, you can also get false sharing, where two cores repeatedly invalidate a cache line even though they aren't logically sharing any data.

You 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.

The 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.

Confirming the hypothesis

I ran a three-way comparison between mimalloc, jemalloc, and the default allocator (glibc). Because our existing benchmarks could not reproduce the problems we were seeing in production, I created a synthetic workload to more accurately reflect the behavior of our production code. It deserialized into the domain model in one thread, passed the value to another thread, and then dropped it there. I measured the number of requests per second with a fixed payload size, varying the thread topology and the allocator. (The configurations use different numbers of threads, so compare allocators within a row rather than across rows.)

Configurationglibcjemallocmimalloc
Same thread (16 threads)80 req/s95 req/s98 req/s
8 producer, 8 consumer threads32 req/s85 req/s81 req/s
16 producer, 16 consumer threads66 req/s163 req/s145 req/s

When the work stays on one thread, the three allocators are roughly comparable. (Although 15–20% slower might be reason enough to stop using glibc.) As soon as values are freed on a different thread, glibc is roughly 2.5× slower than either of the others.

Why is glibc so much worse than the others? My best explanation is that glibc's thread-local cache (tcache) is small (7 entries per size class by default), so steady, cross-thread traffic overflows the tcache on the freeing thread and completely drains the tcache on the allocating thread, so on both sides it falls through to the arena that owns the memory, and the allocating and freeing threads end up contending for that arena's lock. While holding that lock, glibc also takes time to consolidate adjacent free chunks. glibc can push small chunks to a "fastbin" with an atomic operation, but still needs to consolidate them later in malloc_consolidate (which accounted for ~8% of CPU time in our profile). At the time, many of our allocations were too large for fastbins. In ion-rs 1.0.1, an ion_rs::Element alone was 128 bytes, and our domain model carried Elements.

jemalloc and mimalloc serve small allocations from slabs of fixed-size slots, so there's nothing to coalesce.

The choice of jemalloc over mimalloc was arbitrary. Both represented a significant improvement over the current state, and at the time we were just looking for improvement rather than perfection. If switching allocators isn't an option, raising glibc's tcache size with GLIBC_TUNABLES=glibc.malloc.tcache_count=... might be worth an experiment. We didn't try it.

Other fixes

Switching the allocator doesn't fix all of the problems you might see in that flame graph. Other fixes include eliminating the intermediate ion_rs::Element between the serialized Ion and our domain model, deserializing request payloads into a request-scoped arena, moving some of the deserialization work onto the worker threads, and contributing performance improvements directly to ion-rs (for example, v1.1.0). Some of that work is still ongoing, and to discuss it all in detail would be too large for one blog post.

  1. I 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. ↩

  2. You 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 gave similar results. ↩

  3. Different 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. ↩

  4. Although 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. ↩

  5. In a flame graph generated by inferno, press Ctrl+F (or click "Search") and enter the pattern. The "Matched" percentage is the share of samples with a matching frame anywhere on the stack, with nested matches counted once. inferno omits frames narrower than its --minwidth setting, so generate the flame graph with --minwidth 0 if you want a complete count. ↩

  6. Note that the symbol names vary by platform and glibc version. On the server where this profile data was collected, perf resolved free to the versioned alias cfree@GLIBC_2.17. (The suffix is a symbol version, not the installed glibc, which was 2.26. You must include that alias if you want to replicate my figures for that flame graph.) If you have the wrong names, you will end up under-counting, so be sure to check the names in your own profile data before trusting any suspiciously small number. ↩

  7. When 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 while our flame graph doesn't have a "stalled_load" frame, it can hint at the stall as extra samples in the function where the stall occurs. This is probably why malloc, free, and drop_in_place were so prominent in our profiler data. ↩

  8. The nviennot/core-to-core-latency repo on GitHub has a tool for measuring core-to-core latency and published measurements for many architectures. ↩