Investigating Latency Spikes After Traffic Doubles
System DesignModel answerLast updated
Diagnose and resolve severe performance degradation in a distributed system after user load doubles, using observability and root-cause analysis.
Context
Your team operates a web-based task tracking platform. After migrating several major customers onto your infrastructure, the active user base grew from 5 million to 10 million daily active users, and request volume increased from 50,000 requests per second to 100,000 requests per second.
Users now report that the application feels significantly slower. Your monitoring reveals that the primary endpoint for loading work items (GET /api/v1/projects/{projectId}/board) shows alarming degradation:
- Median latency increased from 40ms to 180ms
- 95th percentile latency jumped from 120ms to 2,100ms
- 99th percentile latency spiked from 250ms to 5,400ms
- Gateway timeout errors (HTTP 504) reached 3.2%
Your application servers show modest resource consumption: average CPU at 42% and memory at 55%. Yet the database connection pools frequently reach their limit, and your Redis cache cluster shows eviction rates that are four times higher than before.
Architecture Overview
Your stack consists of:
- Edge Layer: CDN and reverse proxies distribute traffic to regional API gateways
- Application Layer: Stateless services (Go and Java) running in Kubernetes handle business logic, authorization, and data aggregation
- Cache Layer: Redis cluster storing session state, tenant settings, and preprocessed work item data
- Storage Layer: PostgreSQL primary-replica cluster for structured data, plus Elasticsearch for full-text search
Your Task
Explain how you would investigate this performance collapse and restore healthy operation. Cover:
-
Immediate Stabilization: What actions would you take in the first hour to reduce impact on users while investigation continues?
-
Investigation Approach: Which specific metrics, traces, and logs would you examine to pinpoint the bottleneck? Describe your methodology for isolating the failure tier.
-
Root Cause Hypotheses: Analyze potential failure modes across application runtime (threading, garbage collection, connection management), caching (memory pressure, hot keys, invalidation patterns), and database (query performance, connection exhaustion, replication lag).
-
Permanent Resolution: Propose architectural and implementation changes that will support the increased scale without recurring issues.
Hints
Hint 1
Low CPU usage with high latency suggests threads are waiting, not computing—what shared resources do they wait for?
Hint 2
A 2× traffic increase causing 50× worse tail latency points to a nonlinear relationship—what could amplify load in this way?
Hint 3
Consider how the arrival of large customers might differ from your previous workload in data size and query patterns.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Understanding the Symptoms
The critical observation is that CPU utilization remains low (42%) while latency has spiked dramatically. This indicates a wait-bound rather than compute-bound failure. Threads are idle, blocked on I/O resources—specifically database connections and cache lookups.
The pattern suggests a cascading failure triggered by workload characteristics that changed qualitatively, not just quantitatively, when large enterprise customers joined the platform.
1. Immediate Stabilization (First Hour)
Before investigating root causes, protect user experience and prevent further degradation:
Reduce load and limit blast radius:
- Implement per-tenant rate limiting on the affected endpoint
- If possible, route newly migrated customers to isolated application replicas
- Serve degraded responses (cached snapshots or paginated subsets) rather than timing out
- Temporarily disable non-critical features that add database load
Prevent amplification:
- Reduce retry attempts to maximum one retry with exponential backoff and jitter
- Enable circuit breakers on database client libraries
- Align timeouts across layers (gateway: 3s, service: 2.5s, database: 2s) to prevent orphaned work
Add breathing room to bottlenecked resources:
- Increase Redis memory capacity or add cache shards
- Configure cache to reject or compress values over 1MB
- Add a database read replica if capacity exists
- Do NOT simply increase
max_connectionson the database—this often worsens contention
Verify recent changes:
- Check deployment logs for code changes coinciding with the migration
- Review the customer migration process for data loading patterns
2. Investigation Approach
Endpoint-level metrics (RED method): Track Rate, Errors, and Duration segmented by tenant, board size, region, and pod. If latency concentrates in specific tenants with large datasets, this confirms workload skew. If uniform, it indicates shared resource exhaustion.
Resource-level metrics (USE method):
| Layer | Utilization | Saturation | Errors |
|---|---|---|---|
| Application | CPU, memory | Thread/goroutine count, GC pause time | Timeout exceptions |
| Connection pool | Active/max ratio | Queue depth, acquire latency | Acquire timeouts |
| Redis | Memory per shard, CPU | Eviction rate, commands/sec | Connection timeouts |
| PostgreSQL | CPU, disk I/O, buffer hit rate | Active connections, lock waits | Statement cancellations |
Distributed tracing: Sample p99 traces and compare to p50 baseline traces. Look for:
- Long
connection_pool.acquirespans (often 1+ seconds) dwarfing actual query time - Large cache value retrievals (multi-MB payloads) with high deserialization overhead
- N+1 query patterns for authorization checks across hundreds of work items
Database introspection:
- Query
pg_stat_statementssorted by total execution time to find expensive queries - Check
pg_stat_activityfor wait events (Lock,IO,Client) - Run
EXPLAIN ANALYZEon slow queries for large tenants to detect missing indexes or poor plans - Verify that statistics are current (
ANALYZEshould run after bulk data loads)
Cache analysis:
- Use Redis
SLOWLOGto find expensive operations - Run
--bigkeysto identify oversized cache entries - Check per-shard metrics for hot partition imbalance
3. Root Cause Hypotheses
The most likely explanation is a cache effectiveness collapse triggered by workload skew:
The cascade:
- Large enterprise customers have boards with tens of thousands of work items, creating multi-megabyte cached objects
- These large values consume disproportionate Redis memory, triggering aggressive eviction of smaller, frequently accessed keys
- Cache hit rate plummets from ~98% to ~80% across all tenants
- Cache misses fall through to PostgreSQL replicas
- Database queries that performed well on small datasets (1,000 rows) execute slowly on large datasets (100,000 rows) due to unoptimized query plans or missing composite indexes
- Slow queries hold database connections longer
- Connection pools exhaust, causing application threads to block on acquisition
- Gateway timeouts trigger retries, further amplifying database load
Quantifying with Little's Law:
- Before: 50k QPS × 2% miss rate × 3 queries per request × 10ms = ~30 concurrent connections
- After: 100k QPS × 20% miss rate × 3 queries per request × 25ms = ~1,500 concurrent connections
A 2× traffic increase caused a 50× increase in required database concurrency.
Additional failure modes by tier:
Application:
- Thread pool exhaustion as threads block on connection acquisition
- GC pressure from deserializing large JSON payloads
- Goroutine explosion if Go services spawn unlimited concurrent database calls
Cache:
- Hot key concentration on specific Redis shards serving large tenants
- Cache stampedes when tenant-wide keys expire simultaneously
- Coarse invalidation strategies (entire board invalidated on single item update)
Database:
- Missing composite indexes on
(project_id, status, rank)for filtering and ordering - Stale query statistics causing poor execution plans
- Row-level lock contention on rank updates for drag-and-drop operations
- Replication lag if migration write volume delayed WAL replay
4. Permanent Resolution
Immediate fixes (days):
- Add composite indexes identified through query analysis
- Refresh statistics with
ANALYZEon affected tables - Implement server-side pagination with keyset (cursor) pagination for large result sets
- Batch permission checks into single queries or cache ACL decisions
- Deploy PgBouncer in transaction pooling mode to multiplex connections efficiently
Data model and caching strategy (weeks):
- Never cache complete board state as a monolithic blob
- Cache at item or column granularity with independent TTLs
- Implement write-through caching on updates to avoid full invalidation
- Set maximum cache value size (e.g., 512KB) with rejection or compression
- Partition large tenants' cache keys across shards more evenly
Architectural evolution (months):
- Implement tenant isolation: route high-scale customers to dedicated infrastructure
- Pre-aggregate and materialize views for large boards with background refresh
- Introduce read-through cache patterns with request coalescing to prevent stampedes
- Add application-level query result caching with short TTLs for expensive aggregations
- Consider separate read-optimized data stores (denormalized tables, materialized views, or CQRS pattern)
Observability improvements:
- Add per-tenant resource consumption metrics and alerting
- Implement synthetic monitoring that tests large-board performance continuously
- Create runbooks for connection pool exhaustion and cache eviction spikes
- Set up alerts on queue depth and connection acquire time, not just CPU/memory
Common Mistakes to Avoid
- Only scaling horizontally: Adding more application pods increases total database connection demand, potentially worsening the problem
- Ignoring workload characteristics: Treating all requests identically when large-tenant queries have fundamentally different performance profiles
- Optimizing for averages: Focusing on median latency when tail latency indicates the real user pain
- Premature optimization: Implementing complex solutions before confirming the actual bottleneck through measurement
The key insight is recognizing that doubling traffic doesn't simply double resource needs—when combined with workload skew, it can create nonlinear resource amplification that overwhelms shared infrastructure.