Skip to main content

How to Avoid Lag Spikes in Rust Games: A Practical Guide to Memory Management

Learn how Rust avoids garbage-collection pauses, where memory can still hurt frame time, and the practical techniques that keep every frame on budget.

Updated 9 min readMarkdown
How to Avoid Lag Spikes in Rust Games: A Practical Guide to Memory Management

A 60 fps game gets 16.67 ms per frame. Miss it once and the player sees a hitch, no matter how good your average frame time is.

In 2020, Discord rewrote a Go service called Read States in Rust. The Go version was fast on average, but latency spiked roughly every two minutes.

The code already made very few allocations, so the problem wasn't the amount of garbage. The collector had to scan the entire LRU cache to confirm what was safe to free.

In the Rust version, an evicted entry is freed immediately, and the spikes were gone (Discord).

Read States is a server, not a game engine, but the lesson carries over: real-time systems are judged by their worst frame, not their average one.

This post covers what Rust gives you for that problem, what it doesn't, and the techniques that matter in practice.

TL;DR

  • Rust has no tracing garbage collector, so memory is freed deterministically when its owner goes out of scope.

  • The allocator is still there. Allocating in your tick loop, growing Vecs mid-frame, and leaking through Rc/Arc cycles can all hurt.

  • The core playbook: preallocate, reuse, use arenas for per-frame data, refer to entities by handle, and measure allocations.

1. Why the tail matters

Target frame rate Budget per frame
60 fps 16.67 ms
120 fps 8.33 ms

One 30 ms stall in a 60 fps game drops at least one frame. Averages hide that, so track P99 and worst-frame time, not only the mean.

2. Why garbage collectors cause spikes

A tracing collector has to find out what is still reachable, which can mean scanning a large part of the heap.

Engines on garbage-collected runtimes mitigate this. Unity's collector runs in incremental mode by default, spreading the work over several frames so each pause is shorter. Unity's docs are explicit about the limits: incremental mode doesn't make collection faster overall, and if the program changes too many references, the collector can fall back to a full, non-incremental collection (Unity manual).

GC runtimes can work for games. Rust removes the problem instead of managing it.

3. What Rust changes

Every value has one owner. When the owner goes out of scope, Drop runs and the memory is released at a known point in the code:

struct Particle { pos: [f32; 3], life: f32 }

fn spawn_burst() {
    let burst: Vec<Particle> = Vec::with_capacity(256);
    // ... use burst ...
} // `burst` is freed here, at a predictable point, with no collector involved

The borrow checker also rules out use-after-free, double-free, and data races at compile time, with no runtime cost.

4. What Rust does not fix

Removing the GC doesn't make allocation free. The Rust Performance Book says heap allocations are moderately expensive, and that small allocations are not necessarily cheaper than large ones.

Hazard What happens Fix
Vec/String growth mid-frame Contents are copied into a larger allocation with_capacity, reuse buffers
clone() on heap-owning types New allocations Borrow, or clone into an existing buffer
Rc/Arc cycles Memory is never freed Weak, or handles
Unbounded queues and caches Memory grows without limit Bounded channels, eviction
Lots of tiny Boxes Pointer chasing, cache misses Contiguous storage

5. The frame lifecycle

The goal is to do all your allocating at startup, then keep the frame loop free of heap allocation:

STARTUP (allocating is fine here)
  reserve buffers  ·  create frame arena  ·  load assets
        │
        ▼
EVERY FRAME (target: zero heap allocations)
  1. read input
  2. simulate          scratch data     → frame arena (bump pointer)
  3. prepare render    reusable buffers → clear(), keep capacity
  4. present
  5. frame_arena.reset()   ← everything from this frame freed at once
        │
        └──▶ next frame (back to step 1)

6. The techniques

6.1 Reserve once, reuse every frame

clear() resets a Vec's length but keeps its capacity, so a buffer reused every frame stops allocating after warm-up. Bevy's own documentation recommends this pattern: a Local is private to a system and persists between runs, so a Vec stored in one isn't reallocated on every call.

use bevy_ecs::prelude::*;

fn collect_nearby(mut scratch: Local<Vec<Entity>>) {
    // ... fill and use `scratch` this frame ...

    scratch.clear(); // empty for the next run; capacity is kept
}

Bevy's docs add one caveat: if the capacity could grow very large, check it occasionally and shrink it.

6.2 Keep small collections on the stack

SmallVec<[T; N]> stores up to N elements inline and only moves to the heap beyond that. The Performance Book notes it reliably reduces allocation rate but doesn't guarantee a speedup, so benchmark it.

6.3 Per-frame arenas

Scratch data that lives for exactly one frame (contact lists, temporary strings, visibility sets) suits a bump arena: allocation is a pointer increment, and resetting the arena frees everything at once. bumpalo is built for this kind of phase-oriented allocation.

use bumpalo::Bump;

struct Contact { a: u32, b: u32, depth: f32 }

fn main() {
    let mut frame_arena = Bump::with_capacity(1 << 20); // 1 MiB up front

    for _frame in 0..3 {
        let contact = frame_arena.alloc(Contact { a: 1, b: 2, depth: 0.1 });
        contact.depth += 0.05;
        // ... use `contact` during this frame ...

        frame_arena.reset(); // frees everything allocated this frame
    }
}

Gotcha: values in a bump arena do not have Drop run when the arena is reset. Keep types that own resources (file handles, sockets, heap-backed Vecs) out of it, or wrap them in bumpalo::boxed::Box so their destructors run.

6.4 Handles instead of pointers

Games constantly point at things that may disappear. Instead of Rc<RefCell<Enemy>> graphs, store entities in one contiguous collection and refer to them by generational handle. slotmap works this way: a removed key stays invalid even if its slot is later reused, so a stale handle fails the lookup instead of pointing at the wrong entity.

use slotmap::{new_key_type, SlotMap};

new_key_type! { struct EnemyId; }
struct Enemy { hp: i32 }

fn main() {
    // Preallocate at load time; no reallocation until 1,024 enemies exist.
    let mut enemies: SlotMap<EnemyId, Enemy> = SlotMap::with_capacity_and_key(1024);

    let id = enemies.insert(Enemy { hp: 100 });
    enemies.remove(id);
    assert!(enemies.get(id).is_none()); // stale handle detected
}

Handles are plain data, so they also avoid Rc cycles.

6.5 Data-oriented storage with an ECS

An Entity Component System stores each component type contiguously, which suits the cache. Bevy lets you choose the layout per component (docs):

Storage Iteration Add/remove component
Table (default) Fast, cache-friendly Slower
Sparse set Slower Fast
use bevy_ecs::prelude::*;

#[derive(Component)]                  // table storage: iterated every frame
struct Position { x: f32, y: f32 }

#[derive(Component)]
#[component(storage = "SparseSet")]   // added and removed often (e.g., a status effect)
struct Bleeding { damage_rate: f32 }

Rule of thumb: components read every frame go in tables, and components that come and go often go in sparse sets.

6.6 Choose the allocator deliberately

Rust lets you replace the global allocator. mimalloc is a drop-in wrapper around Microsoft's allocator (building it requires a C compiler):

use mimalloc::MiMalloc;

#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;

Treat this as an experiment and benchmark with your own workload before adopting it.

7. Don't let queues and caches grow without bound

Memory that is never freed is also a latency problem, because the process eventually stalls or gets killed.

  • Use bounded channels (for example std::sync::mpsc::sync_channel) so a slow consumer applies backpressure instead of letting a queue grow.

  • Give caches a fixed capacity and an eviction policy.

  • Break Rc/Arc cycles with Weak, or replace pointers with handles.

8. Measure, don't guess

The Performance Book recommends DHAT, which reports where allocations happen, how often, how large they are, and how long they live. The dhat crate also has a testing mode, so you can turn "the tick loop doesn't allocate" into an automated test:

#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;

#[test]
fn tick_does_not_allocate_after_warmup() {
    let _profiler = dhat::Profiler::builder().testing().build();

    let mut world = World::new();   // placeholder for your engine; preallocates at startup
    world.tick();                   // warm-up frame
    let before = dhat::HeapStats::get();

    for _ in 0..1000 { world.tick(); }

    let after = dhat::HeapStats::get();
    dhat::assert_eq!(before.total_blocks, after.total_blocks);
}

The profiler is process-wide and counts allocations from every thread, so keep a test like this in its own integration-test file and avoid background threads that allocate.

Other tools: cargo flamegraph / perf for CPU time, Tracy for per-frame timing, heaptrack for heap growth, tokio-console for async services, and criterion for micro-benchmarks.

9. Safety boundaries

  • Keep unsafe small and well-reviewed.

  • At FFI boundaries (for example, embedding Rust in a C# or C++ engine), know the unwinding rules. Since Rust 1.81, a panic that escapes a plain extern "C" function aborts the process. If unwinding across the boundary is intended, both sides must use the "C-unwind" ABI (stable since 1.71) (release notes). Otherwise, catch panics with std::panic::catch_unwind before they reach the boundary.

10. Trade-offs

What you gain: predictable memory release, no GC pauses, compile-time memory and thread safety.

What it costs: a steeper learning curve, longer compile times, and a game-specific ecosystem that is smaller than C++ or C#. Discord's team also had to work with young async tooling at the time of their rewrite.

What it doesn't mean: you don't need Rust to ship a smooth game. Incremental collection plus allocation discipline works for many titles. Rust pays off most when you have hard latency targets, tight memory budgets, or long-running servers.

Checklist

  • The per-frame loop doesn't allocate after warm-up (enforced by a test)

  • Buffers are sized with with_capacity and reused with clear()

  • Per-frame scratch data is in an arena (and holds no types that need Drop)

  • Entities are referenced by handle, not by cyclic Rc/Arc

  • Queues are bounded and caches have eviction

  • P99 frame time and peak memory are tracked

  • unsafe and FFI boundaries are reviewed

References


Published via ZyVOP — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.

About the author

  • One platform to write, cross-post to Dev.to, Medium, WordPress, Hashnode, and Bluesky, and protect your SEO with canonical links. Zero paywalls and full content ownership.

No comments yet. Be the first to comment.