Define and optimize performance for a high-traffic microservice
System DesignModel answerLast updated
Design SLIs/SLOs, instrument a service, plan load tests, identify bottlenecks, and propose optimizations with trade-offs for a stateless HTTP API.
You're working on a stateless HTTP microservice that handles high request volumes. Walk through your approach to measuring and improving its performance.
Your response should cover:
-
SLIs and SLOs: Which service-level indicators would you track, and what objectives would you set? How do you choose meaningful targets?
-
Instrumentation and profiling: What telemetry would you collect, and which profiling techniques would you use to understand where time is spent?
-
Load testing strategy: How would you design load tests to validate performance? What scenarios matter most?
-
Bottleneck identification: What are the most common performance bottlenecks in HTTP services, and how do you diagnose each one?
-
Optimization approach: Propose specific improvements with their trade-offs. How do you prioritize which changes to make?
Assume a concrete example to ground your answer—such as a read-heavy API serving user data or content metadata—and explain your reasoning with numbers where relevant.
Hints
Hint 1
Use percentiles rather than averages for latency—tail latency matters under fan-out
Hint 2
Distinguish between open-loop and closed-loop load testing to avoid coordinated omission
Hint 3
Profile both on-CPU and off-CPU time; waiting on locks or I/O often dominates actual computation
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
I'll walk through the full cycle: define what success looks like, measure the system, identify the constraint, optimize it, and verify the improvement.
Let me anchor this with a concrete service: a user profile API that serves a mobile app's home feed. It handles 25,000 QPS on average and 70,000 QPS during evening peaks. Each request fetches user metadata from a cache layer backed by a sharded PostgreSQL cluster, plus two downstream service calls for personalization and content ranking.
1. Define SLIs and SLOs
Choose indicators that reflect actual user experience, measured at the service boundary.
| SLI | What it measures | Example SLO |
|---|---|---|
| Latency | Server-side duration for successful requests, as percentiles | p50 < 25 ms, p99 < 120 ms, p99.9 < 350 ms (30-day window) |
| Availability | Fraction of non-error responses | ≥ 99.95% |
| Throughput | Sustained QPS while meeting latency SLO | ≥ 70k QPS with 40% capacity margin (tested to ~100k) |
| Saturation | Resource utilization at peak | CPU < 60%, connection pool wait < 2 ms at p99 |
Key principles:
-
Percentiles, not averages. Averages hide outliers. With fan-out to 50 backend services, even if each has 1% tail latency, approximately 40% of user requests will encounter at least one slow call (1 − 0.99⁵⁰ ≈ 0.39).
-
Error budgets drive decisions. 99.95% availability over 30 days allows roughly 22 minutes of downtime. When you've spent 80% of the budget, you pause feature work and focus on stability.
-
Throughput means sustainable load. It's not "the point where everything collapses"—it's the QPS you can handle while still meeting the p99 latency target.
-
Aggregate percentiles correctly. Compute from mergeable histograms (HdrHistogram, Prometheus buckets). Averaging per-instance p99 values produces meaningless numbers.
2. Instrumentation and profiling
Deploy four layers of telemetry:
Metrics (Prometheus, Datadog)
- RED method for every endpoint: Rate (requests/sec), Errors (by status code), Duration (as histogram).
- USE method for every resource: Utilization, Saturation, Errors. Track CPU, memory, disk I/O, network, thread pools, and database connection pools.
- Label by endpoint, status, region, and deployment version. Avoid high-cardinality dimensions like user IDs.
Distributed tracing (OpenTelemetry)
- Use tail-based sampling: retain 100% of errors and requests exceeding the p99 SLO, plus 1–5% of normal requests.
- Traces reveal where latency hides—queueing, serialization overhead, or a specific downstream dependency.
Structured logs with trace and span IDs for deep dives into individual failures.
Continuous profiling in production (low overhead, always on):
- CPU profiling (pprof, async-profiler, eBPF): flame graphs show hot code paths—often JSON parsing, regex operations, or compression.
- Heap and allocation profiling: catch garbage collection pressure.
- Off-CPU profiling: reveal time spent waiting on locks, disk I/O, or network. Latency problems frequently live here, not in computation.
- Database side: slow query logs,
EXPLAIN ANALYZE, lock-wait metrics, and buffer pool hit rates.
Use Little's Law to sanity-check capacity: concurrency = throughput × latency. At 70k QPS with 40 ms average latency, roughly 2,800 requests are in flight simultaneously. Thread pools and connection pools must accommodate that, or requests will queue.
3. Load testing strategy
Environment: Use a staging cluster that mirrors production data volume and schema, so cache hit rates and query plans match reality. Alternatively, replay sampled production traffic.
Workload realism: Real request distributions follow a power law—the top 5% of users or content keys account for 60% of traffic. Uniformly random keys artificially hurt cache performance; a single repeated key artificially helps.
Use open-loop generators (wrk2, Gatling, k6 with constant arrival rate). Closed-loop tools like ab or hey suffer from coordinated omission: when the server slows down, the client automatically sends fewer requests, hiding tail latency.
Test scenarios:
-
Baseline: Run current peak load (70k QPS) for 30 minutes. Confirm SLOs hold and identify utilization patterns.
-
Ramp test: Increase load by 10% every 5 minutes until latency exceeds the SLO. This finds the performance knee and reveals which resource saturates first.
-
Soak test: Run at 70–80% of capacity for 12–24 hours to catch memory leaks, GC drift, or slow connection leaks.
-
Spike test: Jump from baseline to 3× load instantly. This validates autoscaling response time, circuit breakers, and load shedding.
-
Chaos test: Kill a cache node, inject 150 ms delay into a dependency, or fail a database replica. Verify timeout behavior, retry logic, and graceful degradation.
Pass/fail criteria: Each test must meet the SLO table. Record which resource hit its limit at the performance knee.
4. Bottleneck identification
| Bottleneck | Symptoms | Diagnosis |
|---|---|---|
| CPU | High utilization; latency scales linearly with QPS | Flame graph: hot spots in serialization (JSON/protobuf), logging, regex, compression |
| Memory / GC | Periodic p99 latency spikes; sawtooth heap usage | GC pause logs, allocation profiler |
| Lock contention | Low CPU yet high latency; growing thread run queues | Off-CPU profile, lock/mutex profiling |
| Database | Connection pool exhaustion, slow queries, replica lag, lock waits | Slow query log, EXPLAIN, per-shard load distribution |
| Cache | Low hit rate, hot-key overload, stampedes after TTL expiry | Hit-ratio metrics, per-key request rate, miss burst correlation with deployments |
| Network / downstream | High p99 in RPC spans; TCP retransmits; cross-region calls | Trace spans, TCP stats, payload size analysis |
| Disk I/O | High iowait; slow fsync or commits | iostat, I/O queue depth, commit latency |
5. Optimization approach
Fix the measured bottleneck first. Change one thing, re-run the same load test, and verify improvement. Iterate.
Application / CPU optimizations:
- Switch to faster serialization (Cap'n Proto, FlatBuffers instead of JSON), reuse buffers, reduce allocations.
- Trade-off: increased code complexity, harder debugging.
- Offload non-critical work—analytics events, counter updates—to an async queue (Kafka, SQS).
- Trade-off: eventual consistency; new failure mode for queue backlog.
Caching:
- Deploy multi-tier caching: in-process LRU (Caffeine, Guava) for ultra-hot keys, plus distributed Redis/Memcached.
- Trade-off: stale data; cache invalidation logic becomes critical.
- Prevent cache stampedes with request coalescing (singleflight pattern), jittered TTLs, and stale-while-revalidate semantics.
- Replicate hot keys across multiple cache nodes or serve them from local memory.
Database:
- Add covering indexes to eliminate table scans; batch reads to avoid N+1 queries.
- Trade-off: indexes slow writes and consume storage.
- Route read traffic to replicas.
- Trade-off: replication lag. Implement read-after-write consistency for user-facing data (e.g., route the same user's requests to the same replica for 5 seconds after a write).
- Use a connection pooler (PgBouncer, ProxySQL) to multiplex thousands of application connections onto fewer database connections.
- Shard to distribute hot rows.
- Trade-off: cross-shard queries become harder; rebalancing adds operational complexity.
Concurrency and queueing:
- Tune thread pool sizes based on Little's Law and avoid blocking I/O on request-handling threads.
- Implement load shedding: reject requests with HTTP 503 when queue depth exceeds a threshold, preserving latency for requests that do get served.
- Trade-off: deliberate failures, but better than cascading timeouts.
Common mistakes to avoid:
- Optimizing before measuring. "Add caching" might do nothing if the bottleneck is CPU-bound serialization.
- Tuning in isolation. A change that improves p50 can make p99 worse.
- Ignoring tail latency. Users perceive the slowest part of the experience.
Summary
Performance engineering is a closed loop: define success with SLIs and SLOs, instrument to measure all resources, load test with realistic traffic, profile to find the true bottleneck, apply the most impactful fix, and verify. Ground every decision in data, articulate trade-offs, and prioritize changes by their impact on the SLO that matters most to users.