cargo-best-practices

Best practices for running cargo commands to prevent OOM

Cargo Build/Test Best Practices

Purpose: Prevent OOM crashes and resource exhaustion when running cargo commands.

Before Running Any Cargo Command

  1. Check for existing cargo processes:
    pgrep -af "cargo|rustc" | head -20
  2. If processes exist, wait or terminate:
    • If they are YOUR previous commands that are stale, terminate them:
      pkill -f "cargo test" pkill -f "cargo build"
    • If they are active and needed, WAIT for them to complete before starting new ones.
  3. Never run multiple cargo test/build commands in parallel:
    • ❌ BAD: Starting cargo test -p A while cargo test -p B is running
    • ✅ GOOD: Wait for one to finish, then start the next

Running Tests Safely

# Limit parallel jobs to prevent memory spikes
CARGO_BUILD_JOBS=8 cargo test -p <package> --lib

# For the large legends_client crate, use fewer jobs
CARGO_BUILD_JOBS=4 cargo test -p legends_client --lib

Monitoring During Build

If a build is taking too long or you suspect OOM risk:
# Check memory usage
free -h

# Check cargo process memory
ps aux | grep cargo | head -5

Key Rules

  1. One cargo build/test at a time per workspace
  2. Kill stale processes before starting new builds
  3. Use CARGO_BUILD_JOBS=8 or lower for memory-constrained systems
  4. Prefer cargo check over cargo build for quick validation