My Rust Program Crashed in Production in 40 Seconds (The Stack Was the Reason)
The program worked perfectly in development. A thousand iterations, clean output, no complaints from the compiler. I pushed it to production, pointed real traffic at it, and watched it die within forty seconds.
The error was a stack overflow. Which is the kind of thing that feels deeply personal, like the computer is trying to tell you something about yourself.
The frustrating part was that nothing in the code looked obviously wrong. No infinite loops, no unbounded recursion visible at a glance, no obvious disaster waiting to happen. The problem was subtler than that, and understanding it properly required going back to something I had assumed I already understood: where memory actually lives when a program runs.
If you came from Python or Java, you probably never had to think about this. The JVM and CPython runtime manage memory at a level that makes the question mostly invisible. In C and C++, you thought about it constantly because forgetting meant segfaults and memory leaks in equal measure. Rust sits in an interesting position: it gives you the control of C++ with none of the runtime hand-holding of Java, and it catches a surprisingly large class of memory bugs at compile time.
Stack overflow is one of the bugs it cannot catch. That gap is where my production incident lived.
This was the first time I realised Rust was not hiding the problem. It was just refusing to guess for me.
The stack is fast because it is dumb
Every function call in your program gets a stack frame. That frame holds the function’s local variables, its parameters, and the return address that tells the CPU where to go when the function finishes. When the function returns, the frame is popped off and that memory is immediately available again. No allocation, no bookkeeping, no garbage collector negotiating with the operating system.
The stack is just a pointer that moves up when you call a function and back down when you return. That simplicity is exactly why it is fast.
The trade-off is that the stack is fixed in size, typically somewhere between 1MB and 8MB depending on the platform, and if you exceed that limit the operating system kills your thread. No warning. No graceful degradation. Just death.
In Rust, every value you declare inside a function lives on the stack by default:
fn process() {
let x: u64 = 42; // 8 bytes on the stack
let buffer: [u8; 4096] = [0; 4096]; // 4KB on the stack, right now, unconditionally
let count: usize = 0; // 8 bytes on the stack
// total: ~4KB of stack used just by declaring these
}
fn process() {
let x: u64 = 42; // 8 bytes on the stack
let buffer: [u8; 4096] = [0; 4096]; // 4KB on the stack, right now, unconditionally
let count: usize = 0; // 8 bytes on the stack
// total: ~4KB of stack used just by declaring these
}
That buffer declaration does not wait until you use it. The moment process() is called, 4KB gets reserved on the stack frame. If process() calls another function that also declares a 4KB buffer, and that function calls another, you are chaining allocations with every level of the call stack.
The stack does not complain until it runs out of room. When it does, the error arrives at runtime with no warning from the compiler beforehand.
In Java, you get a StackOverflowError with a stack trace. In Python, you get RecursionError: maximum recursion depth exceeded and you can raise the limit with sys.setrecursionlimit if you feel like living dangerously. In C++, you get undefined behaviour, which is C++’s way of saying anything could happen and your debugger will probably lie to you about what did. In Rust, you get thread 'main' has overflowed its stack, which is at least honest, even if the information arrives after the damage is done.
The crash that introduced me to this properly came from a recursive parser. Each call declared a local buffer for intermediate work:
Result {
let mut buffer = [0u8; 4096]; // 4KB on the stack per recursive call
let mut scratch = [0u8; 1024]; // another 1KB
if let Some(child_input) = extract_child(input) {
let child = parse_node(child_input, depth + 1)?;
}
Ok(Node::new())
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn parse_node(input: &str, depth: usize) -> Result<Node, ParseError> {
let mut buffer = [0u8; 4096]; // 4KB on the stack per recursive call
let mut scratch = [0u8; 1024]; // another 1KB
if let Some(child_input) = extract_child(input) {
let child = parse_node(child_input, depth + 1)?;
}
Ok(Node::new())
}
fn parse_node(input: &str, depth: usize) -> Result<Node, ParseError> {
let mut buffer = [0u8; 4096]; // 4KB on the stack per recursive call
let mut scratch = [0u8; 1024]; // another 1KB
if let Some(child_input) = extract_child(input) {
let child = parse_node(child_input, depth + 1)?;
}
Ok(Node::new())
}
Under low load, recursion depth never got past forty frames. Under real traffic, certain malformed inputs drove it past two hundred frames, each carrying 5KB of stack allocation. At two hundred frames that is 1MB of stack used just for these buffers, on top of everything else the frames needed.
The thread ran out of space. Forty seconds after deployment.
The compiler had nothing useful to say about this beforehand. The borrow checker does not know how deep your call stack will get at peak times, when a particular user submits a particularly creative request. The safety guarantees are real and valuable. They are also not complete, and that distinction matters in production.
The heap trades speed for flexibility
Heap memory is the alternative. When you allocate on the heap, the allocator finds a chunk of memory somewhere in the process’s address space, hands you a pointer to it, and keeps track of what is in use. The heap can grow to use all available memory on the system.
Your stack cannot say the same.
In Java and Python, almost everything lives on the heap and you never think about it. Every object you create in Java is heap-allocated. The garbage collector handles reclamation and you pay for that convenience in throughput, pause times, and the inability to predict exactly when memory gets freed.
In Rust, heap allocation happens when you explicitly ask for it:
<button data-code="fn process() {
// Stack: only the pointer, length, and capacity live here (24 bytes)
// Heap: the actual 4096 bytes live there
let buffer: Vec = vec![0u8; 4096];
// Stack: only a pointer (8 bytes)
// Heap: the u64 value itself lives there
let boxed_value: Box = Box::new(42);
// When this function returns, Rust automatically frees both heap allocations.
// No GC. No manual free(). Ownership ends, memory is released.
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn process() {
// Stack: only the pointer, length, and capacity live here (24 bytes)
// Heap: the actual 4096 bytes live there
let buffer: Vec<u8> = vec![0u8; 4096];
// Stack: only a pointer (8 bytes)
// Heap: the u64 value itself lives there
let boxed_value: Box<u64> = Box::new(42);
// When this function returns, Rust automatically frees both heap allocations.
// No GC. No manual free(). Ownership ends, memory is released.
}
fn process() {
// Stack: only the pointer, length, and capacity live here (24 bytes)
// Heap: the actual 4096 bytes live there
let buffer: Vec<u8> = vec![0u8; 4096];
// Stack: only a pointer (8 bytes)
// Heap: the u64 value itself lives there
let boxed_value: Box<u64> = Box::new(42);
// When this function returns, Rust automatically frees both heap allocations.
// No GC. No manual free(). Ownership ends, memory is released.
}
Rust frees the heap memory the moment the owner goes out of scope, deterministically, with no GC pause. You cannot forget to free it because the compiler will not let the owner outlive its allocation. You control exactly which data goes to the heap and which stays on the stack, and that control is the whole point.
The cost is real. Heap allocation requires the allocator to find free space, update its bookkeeping structures, and potentially ask the OS for more memory. The data also tends to sit further from the CPU’s cache than stack data, which matters in tight loops.
The practical rule: if you know the size at compile time and it is not large, the stack is fine. If the size is dynamic, unknown at compile time, or genuinely large, put it on the heap.
What fixed the crashing parser
The first fix was moving the local buffers out of the recursive function and passing them down by mutable reference:
<button data-code="fn parse_node(
input: &str,
depth: usize,
buffer: &'a mut Vec, // allocated once before recursion starts
scratch: &'a mut Vec, // same
) -> Result {
buffer.clear();
scratch.clear();
if let Some(child_input) = extract_child(input) {
let child = parse_node(child_input, depth + 1, buffer, scratch)?;
}
Ok(Node::new())
}
fn parse(input: &str) -> Result {
let mut buffer = Vec::with_capacity(4096); // allocated once on the heap
let mut scratch = Vec::with_capacity(1024);
parse_node(input, 0, &mut buffer, &mut scratch)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn parse_node<'a>(
input: &str,
depth: usize,
buffer: &'a mut Vec<u8>, // allocated once before recursion starts
scratch: &'a mut Vec<u8>, // same
) -> Result<Node, ParseError> {
buffer.clear();
scratch.clear();
if let Some(child_input) = extract_child(input) {
let child = parse_node(child_input, depth + 1, buffer, scratch)?;
}
Ok(Node::new())
}
fn parse(input: &str) -> Result<Node, ParseError> {
let mut buffer = Vec::with_capacity(4096); // allocated once on the heap
let mut scratch = Vec::with_capacity(1024);
parse_node(input, 0, &mut buffer, &mut scratch)
}
fn parse_node<'a>(
input: &str,
depth: usize,
buffer: &'a mut Vec<u8>, // allocated once before recursion starts
scratch: &'a mut Vec<u8>, // same
) -> Result<Node, ParseError> {
buffer.clear();
scratch.clear();
if let Some(child_input) = extract_child(input) {
let child = parse_node(child_input, depth + 1, buffer, scratch)?;
}
Ok(Node::new())
}
fn parse(input: &str) -> Result<Node, ParseError> {
let mut buffer = Vec::with_capacity(4096); // allocated once on the heap
let mut scratch = Vec::with_capacity(1024);
parse_node(input, 0, &mut buffer, &mut scratch)
}
Stack usage per frame dropped from 5KB to a handful of pointer-sized values. The same inputs that had been crashing at two hundred frames deep now handled a thousand without complaint.
The more principled fix was converting the recursion to an explicit stack using a Vec as a work queue. This is the same pattern Java engineers reach for when they hit StackOverflowError in tree traversals, and for the same reason: the call stack has a hard limit, and the heap does not:
Result<Vec, ParseError> {
// Work queue lives on the heap. Grows as needed. Call stack stays shallow.
let mut work_queue: Vec = vec![(input, 0)];
let mut results: Vec = Vec::new();
let mut buffer = Vec::with_capacity(4096); while let Some((current_input, depth)) = work_queue.pop() {
buffer.clear();
if let Some(child_input) = extract_child(current_input) {
work_queue.push((child_input, depth + 1));
}
results.push(Node::new());
} Ok(results)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn parse_iterative(input: &str) -> Result<Vec<Node>, ParseError> {
// Work queue lives on the heap. Grows as needed. Call stack stays shallow.
let mut work_queue: Vec<(&str, usize)> = vec![(input, 0)];
let mut results: Vec<Node> = Vec::new();
let mut buffer = Vec::with_capacity(4096); while let Some((current_input, depth)) = work_queue.pop() {
buffer.clear();
if let Some(child_input) = extract_child(current_input) {
work_queue.push((child_input, depth + 1));
}
results.push(Node::new());
} Ok(results)
}
fn parse_iterative(input: &str) -> Result<Vec<Node>, ParseError> {
// Work queue lives on the heap. Grows as needed. Call stack stays shallow.
let mut work_queue: Vec<(&str, usize)> = vec![(input, 0)];
let mut results: Vec<Node> = Vec::new();
let mut buffer = Vec::with_capacity(4096); while let Some((current_input, depth)) = work_queue.pop() {
buffer.clear();
if let Some(child_input) = extract_child(current_input) {
work_queue.push((child_input, depth + 1));
}
results.push(Node::new());
} Ok(results)
}
The call stack is now flat regardless of input complexity. The OS is fine with heap memory growing as needed. It is not fine with you blowing through the thread stack limit, which is fixed at process start and not negotiable at runtime.
Looking at the iterative version next to the recursive one, the thing that strikes you is how much the call stack had been doing invisibly. Tracking position, managing intermediate state, deciding when to go deeper and when to return. Moving that work to an explicit data structure makes it visible, which means it is now debuggable, inspectable, and not dependent on a platform limit you cannot control.
That is a meaningful shift, and not just in this parser.
The silent performance killer
The more insidious version of this problem does not crash. It just gets slower in ways that are genuinely confusing until you understand what is happening.
Consider a struct that holds a large fixed-size array:
struct ProcessingContext {
buffer: [u8; 1_048_576], // 1MB array
config: Config,
state: ProcessingState,
}
fn process(ctx: ProcessingContext) { // passes by value
// Rust copies the entire 1MB struct onto this function's stack frame.
// This happens even if you only read ctx.config.
let _ = ctx.config.timeout;
}
struct ProcessingContext {
buffer: [u8; 1_048_576], // 1MB array
config: Config,
state: ProcessingState,
}
fn process(ctx: ProcessingContext) { // passes by value
// Rust copies the entire 1MB struct onto this function's stack frame.
// This happens even if you only read ctx.config.
let _ = ctx.config.timeout;
}
In Java this problem does not exist because objects are always passed by reference. In Rust, value semantics are the default, which makes Rust predictable and explicit, but it also means you have to notice when you are copying large data structures unnecessarily. The compiler will not warn you. The program will not crash. It will just be slower than it should be, in a way that does not show up obviously in a profiler unless you know to look for memcpy calls in hot paths.
The fix:
<button data-code="fn process(ctx: &ProcessingContext) { // pass a reference instead
// 8 bytes copied onto the stack (a pointer), not 1MB
let _ = ctx.config.timeout;
}
// Or if the struct really needs to own large data, put the array on the heap:
struct ProcessingContext {
buffer: Box, // pointer on stack, 1MB on heap
config: Config,
state: ProcessingState,
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn process(ctx: &ProcessingContext) { // pass a reference instead
// 8 bytes copied onto the stack (a pointer), not 1MB
let _ = ctx.config.timeout;
}
// Or if the struct really needs to own large data, put the array on the heap:
struct ProcessingContext {
buffer: Box<[u8; 1_048_576]>, // pointer on stack, 1MB on heap
config: Config,
state: ProcessingState,
}
fn process(ctx: &ProcessingContext) { // pass a reference instead
// 8 bytes copied onto the stack (a pointer), not 1MB
let _ = ctx.config.timeout;
}
// Or if the struct really needs to own large data, put the array on the heap:
struct ProcessingContext {
buffer: Box<[u8; 1_048_576]>, // pointer on stack, 1MB on heap
config: Config,
state: ProcessingState,
}
The Box version means copying the struct copies only the pointer. Under the hood this is exactly what Java does automatically for every object. Rust just makes you write it explicitly, which means you always know what is happening, even when what is happening is slow.
The allocator becomes the bottleneck under concurrency
Under high concurrency, memory stops being an abstract concept and becomes a shared resource every thread is fighting over.
Every thread allocating and freeing heap memory goes through the same allocator lock. Under enough contention, that lock starts showing up in your profiles in ways that are genuinely surprising the first time you see them. Java engineers who have tuned JVM garbage collectors will recognise this dressed differently. The GC pauses are the Java version of allocator contention, and the solutions are conceptually the same: reduce allocation pressure, use thread-local allocation where possible.
The default allocator in Rust is the system allocator, reasonable for most workloads but not optimised for high-frequency small allocations across many threads. Switching to jemalloc is a one-line change:
// Cargo.toml
// [dependencies]
// tikv-jemallocator = "0.5"
use tikv_jemallocator::Jemalloc;
#[global_allocator]
static GLOBAL: Jemalloc = Jemalloc;
fn main() {
// Everything from here uses jemalloc instead of the system allocator.
// Thread-local arenas, reduced lock contention, meaningful throughput gains
// on servers doing high-frequency small allocations.
}
// Cargo.toml
// [dependencies]
// tikv-jemallocator = "0.5"
use tikv_jemallocator::Jemalloc;
#[global_allocator]
static GLOBAL: Jemalloc = Jemalloc;
fn main() {
// Everything from here uses jemalloc instead of the system allocator.
// Thread-local arenas, reduced lock contention, meaningful throughput gains
// on servers doing high-frequency small allocations.
}
Python has a similar concept with pymalloc, its internal allocator for small objects, though you have far less control over it. In C++, custom allocators have existed for decades but require significantly more work to wire in. Rust’s #[global_allocator] attribute makes the swap trivial, which is one of those small ergonomic wins that matters more than it looks once you are actually debugging a production latency spike at 2am.
The fix for my crashing parser took two lines. What took longer was unlearning the assumption I had brought from Python and Java: that local variables are cheap, that the stack is just there, infinite and invisible, not something a working engineer needs to think about.
Those runtimes absorb that assumption quietly. They handle it for you, somewhere underneath, in ways you never see. Rust does not absorb it. Rust looked at my parser, the one that worked perfectly in development and died forty seconds into production traffic, and handed the problem back to me without comment.
It was right to do that. I just needed to understand why.
If Rust memory model and systems programming are the kind of thing you find yourself reading about at unreasonable hours, the field guide is available here.
$7 — Zero to Rust: A Systems Programmer’s Field Guide
You can read the free sample here — Free 20-page sample

