Member-only story
The Rust Profiling Tweak That Cut Our CPU Usage by 73.9%
We thought our Rust service was already quick. It wasn’t — it was wasting CPU cycles like crazy.
The graphs told the story: CPU was climbing, traffic wasn’t. After profiling, we found the bottleneck, made a small change, and CPU usage dropped by 73.9%.
How We Found the Problem
This service handles HTTP requests, parses JSON payloads, and writes to PostgreSQL.
During a load test, CPU hit uncomfortable peaks. I suspected the database first — but I was wrong. We dropped in pprof and generated a flamegraph:
use pprof::protos::Message;
use std::{fs::File, io::Write};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let guard = pprof::ProfilerGuard::new(100)?; // 100 Hz sampling
run_service()?; // Start your actual app here
if let Ok(report) = guard.report().build() {
let mut file = File::create("flamegraph.svg")?;
report.flamegraph(&mut file)?;
}
Ok(())
}The flamegraph didn’t lie — serde_json::from_str was chewing up CPU time.
The Root Cause
We were parsing JSON on every request, even if the payload was exactly the same as the previous one.
