A Rust thumbnail handler keeps a `[u8; 65536]` buffer alive across an `.await`, and `size_of_val` reports a 65 KiB future; why, and how do you shrink it?
answer
- one variant per suspension point
- what must survive the .await
- callee futures are embedded inline
- heap, scope, or box the child
basics
~20 sAn async fn compiles to a state machine that stores every local whose scope spans an .await, so the 64 KiB array sits inside the future. Fix it with a heap buffer, a scope that ends before the .await, or a boxed child future.
solid answer
~50 srustc turns an `async fn` body into an anonymous state machine, roughly an enum with one variant per `.await`, each storing what is needed to resume. A `[u8; 65536]` whose scope spans `store(&buf).await` must survive the suspension, so it is stored inline: on rustc 1.99.1 for aarch64, `size_of_val` reports 65584 bytes, and any caller that awaits it embeds that whole future, so the cost compounds up the call chain. Fixes: hold the buffer in a `Vec<u8>` or `Box<[u8; 65536]>` (72 bytes measured), close its scope in an inner block before the `.await` (20 bytes), or `Box::pin` the big child future so its parent stores only a pointer (16 bytes). Dropping a buffer before the `.await` shrinks it on 1.99.1 only if nothing borrowed the buffer first; once it was read through a reference, the layout keeps its storage until the scope ends. Clippy's pedantic `large_futures` lint flags oversized futures.
code
rust · 32 linesuse std::future::ready;
async fn store(bytes: &[u8]) -> usize {
ready(()).await; // stands in for a real upload
bytes.len()
}
async fn thumbnail_stack() -> usize {
let buf = [0u8; 64 * 1024];
store(&buf).await // buf is alive across this .await
}
async fn thumbnail_heap() -> usize {
let buf = vec![0u8; 64 * 1024];
store(&buf).await // only the Vec's pointer, length and capacity are stored
}
async fn route() -> usize {
thumbnail_stack().await // the callee's future is embedded inline
}
async fn route_boxed() -> usize {
Box::pin(thumbnail_stack()).await // only a Box pointer is embedded
}
fn main() {
println!("thumbnail_stack {}", size_of_val(&thumbnail_stack()));
println!("thumbnail_heap {}", size_of_val(&thumbnail_heap()));
println!("route {}", size_of_val(&route()));
println!("route_boxed {}", size_of_val(&route_boxed()));
println!("stored {}", futures::executor::block_on(route_boxed()));
}go deeper
Recall that an async fn becomes a state machine value, and that what is alive across an .await is stored inside it.
Explain the enum-per-await-point model, why awaited child futures are embedded inline, and how to measure a future with size_of_val.
Diagnose a bloated future from a buffer held across an .await, and pick between heap buffers, inner scopes and Box::pin at a boundary by measuring.
Decide where a codebase pays one allocation to box a future so per-task memory and stack copies stay bounded, and enforce it with lints or size tests.
## What an async fn compiles into An `async fn` or `async` block compiles into an **anonymous type implementing `Future`**. The Reference says its data format is unspecified, and adds a note that the generated type is **roughly an enum with one variant per await point, where each variant stores the data needed to resume** from that point. Polling the future runs the body until the next `.await` that is not ready, then records which variant it is in and returns. So the size of the future is, roughly, the size of its **largest** suspended state plus a discriminant. Whatever has to be alive at a suspension point is part of that state. ## What lands inside the future At each `.await`, the state machine must keep: - the function's **parameters** (an `async fn` owns all of them until it completes); - every **local whose scope spans the `.await`**, because code after the suspension may use it; - the **child future being awaited**, stored inline, not behind a pointer; - references between those pieces, which is why such futures can point into themselves and need pinning (the lesson on Pin covers that). In the thumbnail handler, `let buf = [0u8; 64 * 1024];` followed by `store(&buf).await` means the array is alive across the suspension, so all 65,536 bytes are part of the future. ## Measuring it `std::mem::size_of_val` (in the prelude since Rust 1.80) works on a future without polling it. On rustc 1.99.1, aarch64-apple-darwin, debug and release alike: ```plaintext thumbnail_stack 65584 thumbnail_heap 72 route 65592 route_boxed 16 ``` `route` only does `thumbnail_stack().await`, yet it is 65592 bytes: the awaited future is **embedded inline**, so a large future makes every async caller above it large as well. ## Why a big future hurts - **Stack pressure.** A future is an ordinary value; it is built on the creator's stack and moved into wherever it ends up (a `Box`, a task, a parent future). Clippy describes the risk as "large future may lead to unexpected stack overflows". - **Copies.** Moving a 64 KiB value before it is pinned costs a 64 KiB `memcpy` each time. - **Memory per task.** Every in-flight request holds a whole future; a thousand concurrent handlers of this shape hold over 60 MiB just for buffers. - **Compounding.** Because callees are embedded, the cost shows up far from the code that caused it. ## Shrinking it | Change | What the future stores | Measured on 1.99.1 | |---|---|---| | keep `[u8; 65536]` across the `.await` | the whole array | 65584 bytes | | `vec![0u8; 64 * 1024]` across the `.await` | pointer, length, capacity | 72 bytes | | array inside an inner block that ends before the `.await` | only the computed result | 20 bytes | | sum a non-`Copy` buffer, `drop(px)`, then `.await` | still the whole buffer | 65556 bytes | | `drop(px)` on a non-`Copy` buffer never borrowed, then `.await` | nothing of the buffer | 20 bytes | | caller uses `Box::pin(child).await` | a `Box` pointer to the child | 16 bytes | Practical steps: 1. **Move large buffers to the heap** (`Vec<u8>`, `Box<[u8; N]>`) when they must live across a suspension. 2. **End the scope before awaiting**: compute what you need from the buffer in an inner `{ ... }` block and keep only the result. 3. **Box at a boundary**: `Box::pin(big_child()).await` costs one allocation but keeps the parent small; do it where a big future would otherwise be copied through many layers. 4. **Measure**: assert a size budget in a unit test with `size_of_val`, or enable `clippy::large_futures` (pedantic, allow by default). ## The drop caveat Calling `drop(px)` before the `.await` **did not** shrink the future on rustc 1.99.1 when the buffer had been summed first: `px.0.iter()` borrowed it, and once a local has been borrowed the compiler cannot prove no reference survives, so the layout keeps its storage until its scope ends. The same `drop` on a buffer nothing borrowed measured 20 bytes, and so did moving the buffer by value into a synchronous `checksum(px)` helper. (For a `Copy` array, `drop` only drops a copy, which is even less useful.) Because the layout is unspecified, treat the inner-block and heap fixes as the reliable ones and verify any other trick by measuring.
- Why is `route()`, which only awaits `thumbnail_stack()`, also about 65 KiB?While `route` is suspended inside that `.await`, its state must hold the child future, and an awaited future is stored inline, not behind a pointer. So the parent's size includes the child's 65584 bytes plus its own state. `Box::pin(thumbnail_stack()).await` replaces the inline child with a pointer; `route_boxed` measured 16 bytes on rustc 1.99.1.
- Why did `drop(px)` before the `.await` leave the future at 65556 bytes?Summing it called `px.0.iter()`, which borrowed `px`. Once a local has been borrowed, rustc 1.99.1 cannot prove no reference to it survives, so the layout keeps its storage until its scope ends, even though the value had been moved out; the same drop on a buffer nothing borrowed measured 20 bytes. The layout is unspecified, so the dependable fixes are scoping the buffer in an inner block that closes before the `.await`, or keeping it on the heap. Measure with `size_of_val` rather than assuming.
- How would you keep oversized futures out of a large async codebase?Enable `clippy::large_futures` (pedantic, allow by default) in CI, add unit tests asserting `size_of_val` budgets for hot handlers, and adopt two habits: big buffers live in `Vec` or `Box`, and deep or rarely taken paths are awaited through `Box::pin` so their state does not inflate every caller.
Packing for a trip with a stopover: whatever you need after the stop must travel in your suitcase, so packing a whole wardrobe makes the case heavy wherever it goes. Ship the bulky items ahead and carry only the claim ticket, which is what a Vec or a Box::pin does for a future.
- An async fn's future stores only its arguments; locals live on the polling thread's stack.
- Calling drop(buf) before the .await always removes the buffer from the future.
- Awaiting a child future stores only a reference to it in the parent future.
- A future is always small because the compiler boxes its state automatically.
- Box::pin at the call site leaves the calling future's size unchanged.