How we built a faster 3D bin packer in Rust

| Engineering

Bin packing is a classic NP-hard problem. As the number of items grows, the time to find a "perfect" solution increases exponentially.

When you're an API serving real-time e-commerce checkout requests, waiting 30 seconds for a result isn't an option. We needed a solution that was fast, dense, and reliable. That's why we chose Rust.


Why standard libraries weren't enough

Most open-source bin packing libraries are written in Python or JavaScript and use simple "First Fit" heuristics. They place an item in the first spot it fits. This is fast, but it leaves massive air gaps.

If you are shipping thousands of packages a day, those air gaps translate to real money lost on shipping costs. We needed an algorithm that could look ahead, rotate items intelligently, and stack them stably.

Interpreted (Python/JS)

Great for logic, slow for math.

  • Garbage Collection: Unpredictable pauses
  • Memory Overhead: High per-object
  • Latency: ~200ms - 2s

Native (Rust)

Compiled to machine code.

  • Memory Management: Deterministic (RAII)
  • Data Layout: Cache-friendly
  • Latency: ~2ms - 15ms

Why Rust?

The core of a bin packer is a geometry engine. It performs millions of intersection tests ("Does box A overlap with box B?") per request.

Rust offered us three key advantages:

  • Value Semantics: We can store items contiguously in memory (vectors of structs) rather than as pointers to objects on a heap. This drastically reduces CPU cache misses.
  • Safety without GC: We can construct complex graph structures for "item stability" (ensuring heavy items aren't on top of fragile ones) without worrying about dangling pointers or garbage collection pauses.
  • Type System: Rust's strong typing ensures we never accidentally compare a `Weight` to a `Length`.
struct Bin {
    w: u32,
    h: u32,
    d: u32,
    remaining_volume: u64,
    items: Vec<Placement>,
}

// Zero-cost abstractions allow us to model complex
// geometry without runtime overhead.
impl Bin {
    fn find_best_fit(&self, item: &Item) -> Option<Placement> {
        // ... optimized extreme point heuristic
    }
}

The Results

By porting our logic to Rust, we achieved a 50x speedup over our initial Python prototype while simultaneously adding complex features like:

  • 6-axis Rotation: Checking all possible orientations for the best fit.
  • Stability Checks: Ensuring items have 60%+ bottom surface support.
  • Weight Distribution: Checking center-of-gravity.

Developer First

We didn't just build a fast engine; we wrapped it in a clean, typed API. Whether you use TypeScript, Python, or Go, you get the full power of our Rust engine without the complexity.