Profiling CPU, Cache, and Disk Stalls in a Low-Latency Engine
System DesignModel answerLast updated
Build a measurement-first diagnosis and fix plan for three latency problems in a C++ trading service: CPU saturation, cache-hostile memory use, and slow synchronous log writes.
Context
You own a C++ service that ingests a high-rate stream of market updates and sends order acknowledgments. Under replayed peak-load tests, tail latency spikes in three separate setups. Each has a different resource as the suspect.
- Compute-limited run: The service falls behind during bursts, and the input queue grows without limit. Disk and network utilization are both low.
- Memory-limited run: After hours of running, throughput collapses while the process maintains a large in-memory limit order book. Total memory use is still well below physical RAM.
- Storage-limited run: During volatile periods, order acknowledgment latency rises roughly tenfold while the service writes audit records.
Task
For each of the three setups, answer the following:
- Measurement: Which OS tools and hardware or kernel counters would you use to confirm where the time is going? Be specific about what each reading would indicate.
- Likely cause: Propose a concrete design or code-level flaw that explains the symptoms.
- Fix: Describe the architectural, algorithmic, or systems-level change you would make.
- Validation: How would you prove the bottleneck is gone without breaking correctness, such as durability, thread safety, or deterministic order handling?
A strong answer is structured, ties each conclusion to a measurement, discusses trade-offs, and avoids jumping to fixes before there is evidence.
Hints
Hint 1
Start from the symptom and split it. High CPU could be user code, kernel time, or cores that are stalled waiting on memory. Look at IPC and the user/system split before choosing a fix.
Hint 2
For the memory case, total usage is fine, so think about locality: pointer-heavy containers, scattered allocations, cache and TLB misses, and page-level behavior that degrades over a long session.
Hint 3
For the I/O case, ask what the order thread waits on before it can send an ack. Then think about how to take the storage device off that path while keeping a clear durability guarantee.
Hint 4
For validation, think about replaying captured traffic through old and new builds and comparing outputs, plus checking invariants and running long soak tests.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use the same loop in all three cases: observe, hypothesize, confirm with a counter, fix, then verify. Many symptoms look alike. "High CPU" can be real compute, kernel overhead, or memory stalls that count as busy cycles. Measure before changing anything.
1. Compute-limited: queue grows without bound
Measurement
top -Horpidstat -t 1shows per-thread load. One thread at 100% while other cores idle indicates a serial bottleneck.mpstat -P ALLsplits%usr,%sys, and%soft. High%syssuggests syscalls or futex waits. High%softsuggests network softirq load.pidstat -wreports voluntary context switches (lock contention or blocking) and involuntary ones (preemption, so the thread is not isolated).perf stat -e cycles,instructions,branch-misses: IPC above roughly 2 suggests real compute. IPC below roughly 1 suggests stalls, so go to the memory case.perf record -gwith a flame graph shows where cycles are spent.
Likely cause
A single thread decodes, looks up the symbol, updates the book, and runs strategy callbacks. The hot path includes string-keyed std::unordered_map lookups, a heap allocation per message, virtual dispatch, and one recv() per packet. The flame graph would show malloc, hashing, and receive calls dominating. Throughput is capped at one core.
Fix
- Shard by instrument. Map symbols to small integer IDs at subscription time. Route messages to N workers, each owning a disjoint set of books, through lock-free SPSC ring buffers.
- Decode in place with fixed-layout structs, no hot-path allocation, and static dispatch (templates or a switch).
- Batch receives with
recvmmsg, or use kernel bypass if the latency budget justifies it. - Isolate and pin worker threads (
isolcpus,nohz_full,taskset) and busy-poll.
Trade-off: sharding adds a hop and complicates anything that spans symbols, and busy-polling burns cores.
Validation
- Replay a captured peak session through the old and new builds, and compare output streams (book states, order decisions) by hash.
- Sharding keeps per-symbol ordering, which is what determinism needs. Cross-symbol logic, such as portfolio risk checks, needs an explicit sequencing point.
- Run ThreadSanitizer on the queues.
- Measure p99 and p99.9 with HdrHistogram at 2-3x peak rate and confirm queue depth stays bounded.
2. Memory-limited: throughput collapses over a long session
Measurement
perf stat -e LLC-load-misses,dTLB-load-missesplus stall-cycle events. The signature is low IPC with a stall fraction that grows over session time.perf memorperf c2cidentifies which structures miss, and whether threads share cache lines (false sharing).vmstat 1:si/soshould be zero. If not, it is real swapping. Watch minor page faults withperf stat -e page-faults.- Check THP behavior through
/sys/kernel/mm/transparent_hugepageandcompact_stallin/proc/vmstat. - A flame graph showing time in
malloc/freeor allocator futexes points to allocator contention.
Likely cause
The book uses node-based containers, such as std::map of price to a list of orders plus an unordered_map by order ID. Every add and cancel allocates or frees a node. After hours of churn, nodes are scattered across the heap. Walking one price level touches many cache lines across many 4 KB pages, producing LLC and TLB misses. Freed memory returned to the OS causes refaults, and THP compaction adds millisecond stalls. RSS stays small; the problem is locality, not capacity.
Fix
- Flat array of price levels indexed by tick offset from a reference price, giving O(1) access and neighboring levels in shared cache lines. Use a sorted vector for sparse instruments.
- Slab or pool allocation for orders, with intrusive linked lists and an open-addressing hash by order ID. No malloc on the hot path.
- Hot/cold split: price, quantity, and links stay compact; metadata lives elsewhere.
- Pre-faulted huge pages for the pools,
mlockall, and THP defrag disabled to avoid compaction stalls.
Trade-off: arrays waste memory for wide price ranges, and fixed pools need capacity planning and an overflow policy.
Validation
- Differential testing: run the old book as a reference on identical replays and compare top-of-book and depth after every event.
- Invariants: level quantity equals the sum of its orders, there are no orphaned order IDs, and pool usage returns to baseline after a flush.
- Run ASan/UBSan in CI.
- Run a 24h+ soak test and confirm miss rates and p99 stay flat.
3. Storage-limited: ack latency rises 10x in volatility
Measurement
iostat -x 1: watch write await, queue size, and%utilon the log device.vmstat 1:waand blocked process count./proc/meminfo:DirtyandWritebackclimbing toward the dirty-page limit.strace -corperf trace: count and timewriteandfsyncon the order thread.- eBPF tools (
biolatency,offcputime): off-CPU stacks on the order thread inbalance_dirty_pagesor journal waits are strong evidence.
Likely cause
The order thread formats a text record and calls write() then fsync() before sending each ack. When the record rate spikes, fsync latency grows with device queue depth, and even plain write() blocks once dirty-page throttling kicks in. Device latency is directly on the critical path.
Fix
- Decouple logging. The order thread copies a fixed-size binary record (sequence number, TSC timestamp) into a preallocated SPSC ring, costing tens of nanoseconds.
- Dedicated logger thread on a non-critical core drains the ring and writes batches to a preallocated file (
fallocate), usingO_DIRECTor io_uring. - Group commit: call
fdatasynconce per batch or time window rather than per record. - Decide the durability contract explicitly. If an ack must not be sent before the record is durable, acks wait on the batch commit, which is a bounded delay. If a short loss window is acceptable, ack on ring enqueue and monitor lag.
- Put logs on a separate device from other I/O, and define ring-full behavior (back-pressure or counted drops) instead of letting it block silently.
Validation
- Crash tests: kill the process or power-cycle a VM at random points, then verify the log contains every record the durability contract promises, in sequence order.
- Check that sequence numbers have no gaps and that replaying the log reproduces state.
- Re-run volatility replays and compare ack latency percentiles and ring occupancy.
Common mistakes
- Adding threads before checking whether the stall is memory-bound.
- Treating a busy core as proof of compute-bound work without reading IPC.
- Optimizing averages instead of p99.9.
- Removing
fsyncwithout stating the new durability guarantee. - Skipping a long soak test, so degradation that appears only after hours goes unseen.