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
- Check for existing cargo processes:
pgrep -af "cargo|rustc" | head -20 - 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.
- If they are YOUR previous commands that are stale, terminate them:
- Never run multiple cargo test/build commands in parallel:
- ❌ BAD: Starting
cargo test -p Awhilecargo test -p Bis running - ✅ GOOD: Wait for one to finish, then start the next
- ❌ BAD: Starting
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 --libMonitoring 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 -5Key Rules
- One cargo build/test at a time per workspace
- Kill stale processes before starting new builds
- Use
CARGO_BUILD_JOBS=8or lower for memory-constrained systems - Prefer
cargo checkovercargo buildfor quick validation