Diagnosing Performance Bottlenecks and Planning Infrastructure Scale
System DesignModel answerLast updated
Debug a backend service that degrades under load, then calculate the infrastructure needed to support given traffic assumptions.
Context
You're responsible for a backend API service that has started exhibiting performance problems. When incoming traffic increases, response times degrade significantly and some requests time out completely.
Part 1: Performance Investigation and Remediation
Your service is experiencing latency spikes and timeouts during periods of elevated traffic. Walk through your approach to:
- Identify the root cause of the performance degradation
- Implement short-term fixes to stabilize the service immediately
- Design long-term improvements to prevent recurrence
You have full access to modify both the application code and the underlying infrastructure. Consider both reactive responses and proactive architectural changes.
Part 2: Infrastructure Sizing
Given a set of traffic and workload parameters, explain how you would calculate the required infrastructure capacity. Your answer should cover:
- What information you need (traffic patterns, performance requirements, resource consumption per operation, etc.)
- How to translate those inputs into concrete numbers for compute instances, database resources, storage, and network capacity
- A concrete worked example showing the calculations
Demonstrate that you can move from abstract requirements to quantified resource allocations.
Hints
Hint 1
Start with observability: metrics and traces will reveal where time is actually spent
Hint 2
Remember that systems don't degrade linearly—there's often a sharp cliff as resources saturate
Hint 3
Use Little's Law (concurrency = throughput × latency) to size pools and buffers
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Diagnosing Performance Bottlenecks and Planning Infrastructure Scale
This problem evaluates two complementary capabilities: systematic troubleshooting under production pressure and quantitative reasoning about infrastructure requirements. Strong answers connect these parts—the capacity model should explain why the system degraded, and the diagnosis reveals which assumptions in your model were incorrect.
Part 1: Root Cause Analysis and Mitigation
Begin with clarifying questions
Before diving into fixes, establish context:
- Does the degradation affect all API endpoints uniformly, or only specific ones?
- Are traffic spikes predictable (e.g., daily patterns, campaign launches) or irregular (sudden bot activity, cascading failures)?
- What are the current service level objectives (e.g., 95th percentile latency under 200ms)?
- Is the elevated traffic legitimate user activity?
These answers determine the solution path. Bot traffic needs rate limiting; legitimate growth demands more capacity.
Systematic diagnosis using observability
Use structured frameworks rather than guessing:
RED metrics (per endpoint):
- Request rate
- Error percentage
- Duration (median, 95th, 99th percentile)
Identify which endpoints show latency increases correlated with request volume.
USE metrics (per resource):
- Utilization (% of capacity used)
- Saturation (queue depths, wait times)
- Errors
Apply this to CPU, memory, network, disk I/O, and critically to constrained resources like connection pools, thread pools, and event loop lag.
Distributed tracing reveals where latency accumulates:
- Application processing time
- Database query execution
- Calls to external services
- Time waiting for resources
Common patterns and their signatures:
| Observable pattern | Probable cause |
|---|---|
| CPU at ceiling, latency proportional to load | Application is compute-bound; needs horizontal scaling or optimization |
| Low CPU but high latency | I/O blocking: database, external API, or lock contention |
| "Connection unavailable" in traces | Pool exhaustion (database connections, HTTP clients) |
| Database CPU saturated, slow query logs populated | Index missing, N+1 query patterns, lock contention |
| Memory growth, garbage collection stalls | Unbounded buffers, memory leaks, oversized payloads |
| Error spikes followed by latency explosions | Retry amplification: failed requests retried aggressively |
A critical concept: latency is nonlinear in utilization. Queueing theory shows wait time grows approximately as 1/(1−ρ) where ρ is utilization. Moving from 60% to 90% utilization can increase latency by 4×. Systems don't degrade smoothly—they collapse suddenly.
Immediate stabilization (minutes to hours)
-
Horizontal scaling of stateless application instances if app CPU is the constraint. Warning: if the database is saturated, adding app servers worsens the problem.
-
Load shedding and rate limiting:
- Deploy per-client rate limits using token bucket algorithms at the edge
- Return HTTP 429 or 503 proactively rather than accepting work that will timeout
- Differentiate critical paths (transactions, authentication) from optional features (analytics, recommendations)
-
Constrain queues and enforce timeouts:
- Set explicit timeouts on all outbound calls
- Limit queue depths to fail fast instead of accumulating stale requests
- Ensure timeouts cascade properly through the call chain
-
Prevent retry storms:
- Implement exponential backoff with randomized jitter
- Add client-side retry budgets
- Deploy circuit breakers around unstable dependencies
-
Cache frequently accessed data using Redis, Memcached, or CDN for static content and GET responses.
-
Disable non-essential features through feature flags for graceful degradation.
-
Quick database optimizations:
- Add indexes revealed by slow query analysis
- Terminate runaway queries
- Tune connection pool size; consider connection poolers like PgBouncer
Architectural improvements for resilience
-
Intelligent autoscaling: trigger on leading indicators like request rate or active connections, not lagging CPU metrics. Maintain warm capacity since scaling takes minutes.
-
Asynchronous processing: offload non-critical work (email delivery, report generation, webhook dispatching) to queues (Kafka, SQS, RabbitMQ) processed by background workers. Queues buffer spikes and convert bursty load into smooth throughput.
-
Database scaling strategies:
- Read replicas for read-dominated workloads
- Multi-layer caching (application, CDN, database)
- Horizontal partitioning or sharding for write-heavy scenarios
- Separate read and write paths (CQRS) when access patterns diverge
-
Resource isolation: separate connection and thread pools per dependency so one degraded service can't starve all operations.
-
Geographic distribution across multiple availability zones with health-check-aware load balancing.
-
Proactive validation: continuous load testing (using tools like k6, Gatling, or Locust) to discover capacity limits before users do.
-
Comprehensive observability: SLO-based alerting on latency and error budgets, dashboards tracking resource saturation metrics.
Part 2: Capacity Calculation Framework
Required inputs
- Traffic characteristics: daily active users, operations per user, read-to-write ratio, peak-to-average multiplier
- Performance targets: latency SLOs (e.g., 99th percentile under 150ms), availability requirements
- Unit economics: CPU time per request, memory footprint, database queries per operation, payload sizes (measured via profiling)
- Data requirements: bytes per write operation, retention period, replication factor, indexing overhead
- Growth trajectory: anticipated traffic increase over planning window (typically 12-18 months)
- Reliability requirements: number of availability zones, failure scenarios to tolerate
Worked calculation example
Starting assumptions:
- 8 million daily active users
- 25 operations per user daily
- Peak traffic is 5× average
- 85% reads, 15% writes
- 15ms CPU time per request
- Target: 120ms average latency
- 1.2 KB per write operation
- 8 KB average response size
Step 1: Request throughput
- Daily operations: 8M × 25 = 200M requests/day
- Average rate: 200M / 86,400 = 2,315 requests/second
- Peak rate: 2,315 × 5 = 11,575 requests/second
Design for peak, not average.
Step 2: Compute requirements
- One CPU core at 15ms/request achieves 66 requests/second at full utilization
- Target 65% utilization for latency headroom: 43 requests/second per core
- Cores required: 11,575 / 43 = 270 cores
- Using 16-vCPU instances: 270 / 16 ≈ 17 instances
- For 3-zone deployment tolerating single zone failure, each zone handles 50% of total traffic: 17 × 1.5 = 26 instances
- Add 40% growth buffer: 26 × 1.4 = 36 instances provisioned
Step 3: Concurrency and memory (applying Little's Law)
Little's Law: concurrent requests = throughput × latency
- In-flight requests: 11,575 req/s × 0.12s = 1,390 concurrent requests cluster-wide
- At 3 MB per request context: ~4.2 GB total (not a constraint for modern instances)
- Database connection requirements: if each request holds a connection for 25ms, we need 11,575 × 0.025 = 290 connections plus buffer ≈ 350 connections
Step 4: Database capacity
- Peak writes: 15% × 11,575 = 1,736 writes/second
- Peak reads: 85% × 11,575 = 9,839 reads/second
- Assuming 85% cache hit rate: 0.15 × 9,839 = 1,476 reads/second reach the database
- Total database load: ~3,200 queries/second
- One primary for writes, two read replicas handles this load; validate against database-specific benchmarks
Step 5: Storage projections
Use average rate for storage, not peak:
- Average writes: 2,315 × 0.15 = 347 writes/s
- Daily data: 347 × 1.2 KB × 86,400 = 36 GB/day
- Annual growth: 13 TB/year
- With 3× replication and 25% index overhead: 13 × 3 × 1.25 = 49 TB/year
- Factor retention policies and archival to cold storage
Step 6: Network bandwidth
- Peak egress: 11,575 req/s × 8 KB = 92.6 MB/s = 740 Mbps
- Manageable at the cluster level; offload static assets and cacheable responses to CDN
Step 7: Validation through testing
These calculations are hypotheses. Load test single instances under realistic conditions to measure actual capacity at your SLO, then validate the cluster can handle projected load with comfortable headroom. Monitor leading indicators in production and adjust as actual usage patterns emerge.
Common mistakes to avoid
- Sizing for average load instead of peak traffic
- Ignoring the nonlinear relationship between utilization and latency
- Forgetting redundancy and failure tolerance in capacity calculations
- Assuming infinite database connection pools or overlooking resource constraints
- Neglecting to include growth projections in infrastructure planning
- Optimizing prematurely without measuring where time is actually spent