Performance optimization isn't a single pass. It's a structured audit across the entire stack—from memory allocators and I/O patterns to lock contention and cache behavior. Most teams skip this discipline and reach for profilers only when production burns. By then, architectural choices have ossified, and micro-optimizations become expensive band-aids.
This checklist reflects the audits we run when diagnosing performance bottlenecks in high-throughput backends, real-time game engines, and compute-heavy applications. Every item here has surfaced critical regressions in production systems. Use it methodically.
1. Memory Allocation Patterns
Allocations dominate latency in tight loops. Profile allocator behavior first.
- Heap allocation frequency: Instrument
malloc/freecalls per request or frame. In Rust, enablejemallocatorormimallocand capture allocation stats. A REST API allocating >100 times per request is suspect. A game engine allocating per-frame in hot paths guarantees frame drops. - Object pooling: Reuse expensive objects (database connections, byte buffers, render targets). Measure cache hit rates. A pool with <80% hit rate wastes memory without reducing allocations.
- Zero-copy paths: Count copies of large payloads (request bodies, pixel buffers, audio samples). Use
mmap, shared memory, or arena allocators to eliminate intermediate buffers. A single redundant copy of a 10MB texture every frame costs 1.6 GB/s at 60 FPS. - Fragmentation: Long-running processes with variable-sized allocations fragment the heap. Monitor RSS growth over 24 hours. If RSS grows 20% under stable load, fragmentation or leaks are present. Switch to a compacting allocator or partition allocations by size class.
2. I/O and System Calls
System calls are microsecond-scale context switches. Batching and async I/O are non-negotiable for low-latency systems.
- System call count: Use
strace -cor eBPF to count syscalls per operation. A web handler making >10 syscalls (open, read, write, close) indicates unbatched I/O. Batch reads, use vectored I/O (readv/writev), or switch toio_uringon Linux. - Blocking I/O in async contexts: Trace blocking calls (
read,write,fsync) in async runtimes like Tokio. A single blocking call stalls the executor thread. Offload blocking I/O tospawn_blockingor dedicated thread pools. - File descriptor churn: Opening and closing files per request is expensive. Keep long-lived FDs open, or use
openatwith cached directory FDs. Measure FD table size withlsof; growth indicates leaks. - Network buffer tuning: Check
SO_SNDBUFandSO_RCVBUF. Default 128KB buffers bottleneck 10GbE links. Set to 4MB+ for high-throughput streams. Validate withss -mto confirm kernel allocated requested size.
3. Data Structures and Access Patterns
Cache misses cost 100+ cycles. Data layout determines whether you're memory-bound or compute-bound.
- Cache line utilization: Profile cache misses with
perf stat -e cache-misses,cache-references. <10% miss rate is healthy; >20% indicates poor locality. Pack hot fields into single cache lines (64 bytes). Separate read-hot from write-hot data to avoid false sharing. - Array-of-structs vs struct-of-arrays: AoS causes strided access when processing one field across many objects. SoA enables SIMD and prefetching. For particle systems or entity components, SoA delivers 2-4× throughput. Benchmark both layouts with your access pattern.
- Hash table load factor: Measure collision rate and bucket utilization. Load factor >0.75 degrades performance. If resizing is expensive, pre-size tables based on expected cardinality. Use FxHash or AHash in Rust for integer keys; they outperform SipHash by 3-5× with negligible collision risk in non-adversarial workloads.
- Index bloat in databases: Unused indexes slow writes and waste memory. Audit index usage with
pg_stat_user_indexes(Postgres) or equivalent. Drop indexes with zero scans. Partial indexes on filtered queries reduce size by 10-100×.
4. Concurrency and Synchronization
Lock contention serializes parallel work. Measure hold times and contention rates, not just the presence of locks.
- Lock hold time: Instrument critical sections with cycle counters. A mutex held for >1µs under contention is a serialization point. Shrink critical sections: move allocations, I/O, and logging outside locks.
- Contention rate: Use
perf lock contentionor vendor-specific tools (e.g.,parking_lotstats in Rust). If >10% of lock attempts block, contention dominates. Shard locks by key hash, use lock-free data structures, or switch to message-passing. - Read/write lock balance: RwLocks pessimize writes. If writes occur >1% of the time, reader bias causes writer starvation. Use
seqlockor optimistic concurrency instead. - Atomic operation cost: Atomic RMW operations (fetch_add, compare_exchange) are 10-50× slower than non-atomic ops on contended cache lines. Batch updates per thread, then publish atomically. Use relaxed ordering when sequencing isn't required.
5. CPU Utilization and Scheduling
High CPU doesn't mean efficient CPU. Profile instruction mix and scheduler behavior.
- IPC (instructions per cycle): Measure with
perf stat. Modern CPUs achieve 2-4 IPC on scalar code. <1.5 IPC suggests pipeline stalls from branch mispredicts or memory latency. Profile hotspots withperf record -e cyclesand inspect disassembly. - Branch misprediction rate: Check
perf stat -e branch-misses,branches. >5% mispredict rate indicates unpredictable branches. Replace conditional logic with branchless arithmetic or lookup tables. Example:result = array[condition]instead ofif (condition) result = x else result = y. - Context switch rate: Measure with
vmstat 1orperf stat -e context-switches. >1000 switches/sec/core under load indicates over-subscription or blocking in tight loops. Pin threads to cores, reduce thread count, or batch work to minimize scheduling. - NUMA topology: On multi-socket systems, remote memory access costs 2-3× local access. Use
numactl --hardwareandperf memto detect cross-socket traffic. Pin threads and allocate memory on the same node.
6. Algorithmic Complexity Validation
Big-O hides constants until N grows. Confirm theoretical complexity matches runtime behavior.
- Input size scaling: Benchmark operations at 10×, 100×, 1000× expected input size. Plot latency vs N on log-log scale. A straight line confirms O(N); upward curve indicates O(N²) or worse. We've seen "O(N)" implementations regress to O(N log N) due to hidden sorts in library code.
- Early termination: Ensure loops exit early when results are known. A search that iterates the full dataset after finding a match wastes cycles. Profile loop iteration counts to validate.
- Redundant computation: Cache expensive function results. A ray tracer recalculating matrix inverses per pixel instead of per frame loses 90% throughput. Memoize deterministic functions or lift invariants out of loops.
7. Compiler Optimization Verification
Trust but verify. Compilers don't always optimize as expected, especially across ABI boundaries.
- Inlining: Check disassembly for hot functions. Small functions (<10 instructions) should inline. If not, use
#[inline]in Rust or__attribute__((always_inline))in C. Verify withcargo asmorobjdump -d. - Vectorization: Profile with
perf stat -e fp_arith_inst_retired.scalar_single,fp_arith_inst_retired.128b_packed_single. If SIMD instructions are absent in tight loops, check alignment, stride, and aliasing. Use#[repr(align(32))]or explicit SIMD intrinsics. - Dead code elimination: Ensure unused code paths are compiled out. Use
cargo bloatornmto identify unexpectedly large binaries. Feature flags and const generics enable compile-time specialization. - PGO (Profile-Guided Optimization): Run production workloads with instrumentation, then rebuild with profile data. PGO improves branch prediction and inlining decisions, yielding 10-30% gains in CPU-bound code. Rust supports PGO via
rustcflags; measure before and after.
8. Instrumentation and Observability
You can't optimize what you can't measure. Embed low-overhead instrumentation from day one.
- Latency histograms: Track p50, p99, p99.9 latency for every operation. Means hide outliers. Use HDR Histogram or equivalent. A p99 of 10× p50 indicates high variance; investigate tail latency causes (GC pauses, lock contention, disk I/O).
- Trace sampling: Continuous profiling with low overhead (<1%) via eBPF or statistical sampling. Always-on profiling catches transient issues that disappear under manual profiling. Use
perf record -F 99 -gor vendor solutions like Parca. - Allocation tracking: Log allocation stacks for large allocations (>1MB). In Rust, wrap the global allocator to intercept
alloc/dealloc. Identify unexpected allocators in hot paths. - Custom counters: Expose internal metrics (queue depth, cache hit rate, retry count) via
/metricsendpoint. Correlate application-level metrics with system-level signals (CPU, memory) to pinpoint bottlenecks.
9. Environment-Specific Factors
Performance characteristics change across deployment environments. Validate in production-like conditions.
- CPU frequency scaling: Governors like
powersavethrottle CPU under load. Pin governor toperformanceon latency-sensitive hosts. Measure withcpupower frequency-info. - Thermal throttling: Sustained load triggers thermal limits. Monitor CPU temperature and frequency during benchmarks. Throttling can cut throughput by 30-50%.
- Virtualization overhead: VMs add 5-15% latency for I/O and syscalls. Containers have near-zero overhead for CPU but can throttle based on cgroup limits. Measure in both bare metal and production environments.
- Kernel tunables: Defaults are conservative. Increase
net.core.somaxconn,fs.file-max, andvm.max_map_countfor high-concurrency servers. Disable transparent huge pages if they cause latency spikes. Validate changes with A/B testing.
10. Real-World Validation
Synthetic benchmarks lie. Test under production traffic patterns.
- Load testing: Replay production request distributions (URI, payload size, arrival rate) in staging. Use tools like
wrk2orlocustwith latency injection to model WAN delays. Measure at 2× peak load to identify headroom. - Chaos testing: Inject faults (network partitions, disk latency, CPU throttling) and measure degradation. A 10ms network delay shouldn't cause 1000ms API latency; if it does, your system amplifies latency.
- Continuous benchmarking: Run microbenchmarks on every commit. Catch regressions early. Rust's
criteriondetects sub-5% performance changes. Fail CI on statistically significant slowdowns.
Implementing the Audit
This checklist is exhaustive by design. Prioritize based on symptoms: memory issues surface in allocator profiles, latency spikes point to I/O or locks, low throughput suggests cache misses or algorithmic problems. Work top-down through the stack, validating each hypothesis with measurements before moving deeper.
For systems built in Rust—our primary language for high-performance backends and compute-intensive workloads—many of these audits are simplified. Zero-cost abstractions, deterministic ownership, and unsafe boundaries make performance predictable. We've used this exact checklist to optimize real-time game servers, high-frequency data pipelines, and low-latency APIs where microseconds matter. The same principles apply whether you're building a mobile app backend in Rust or a game engine rendering loop.
Performance isn't a feature you bolt on. It's a discipline embedded in architecture, code review, and continuous integration. Run this audit quarterly, or whenever request latency or resource usage trends upward. The cost of ignoring performance compounds; the cost of disciplined audits is linear.


1 min read
3 Views

