Types of Latency
In distributed systems, latency appears at every layer.
Latency Sources
Full Request Latency:
Client Device ──── 5ms (local processing)
↓
DNS Resolution ──── 10ms (domain lookup)
↓
TCP Connection ──── 20ms (3-way handshake)
↓
TLS Negotiation ──── 30ms (if HTTPS)
↓
Network Transit ──── 10-100ms (geographic distance)
↓
Server Processing ──── 50ms (business logic)
↓
Database Query ──── 100ms (data retrieval)
↓
Response Transit ──── 10-100ms (back to client)
↓
Client Rendering ──── 20ms (display response)
Total: ~250-400ms typical
Types of Latency
| Type | Description | Typical Value |
|---|---|---|
| Network Latency | Time for data to travel between nodes | 1-100ms |
| Processing Latency | Time to process a request | 1-50ms |
| Queue Latency | Time waiting in a queue | 0-1000ms |
| Disk Latency | Time to read/write disk | 0.1-10ms |
| Memory Latency | Time to access RAM | 0.0001ms |
Geographic Latency
Same Data Center: 0.1-1ms
Same City: 1-5ms
Same Country: 5-20ms
Cross-Continent: 50-200ms
Examples:
New York → London: 70ms
New York → Tokyo: 160ms
New York → Sydney: 200ms
Latency by Component
Component Latency Optimization
─────────────────────────────────────────────
Browser rendering 10-50ms Virtual DOM, SSR
DNS lookup 10-50ms DNS caching
TCP handshake 20-40ms Keep-alive, HTTP/2
TLS handshake 30-50ms TLS session resumption
CDN edge 1-10ms Edge caching
Application server 10-100ms Caching, optimization
Database 1-1000ms Indexing, caching
External API 50-500ms Async, caching
Latency Percentiles in Practice
Web Application Typical Latency:
P50: 100ms (median user)
P95: 300ms (95% of users)
P99: 500ms (99% of users)
P999: 1000ms (1% of users)
If P99 > 1 second, users start noticing delays.
Measuring Latency
Accurate latency measurement is essential for identifying bottlenecks and verifying improvements.
Measurement Methods
End-to-End Measurement:
Start Timer ──→ Request ──→ Response ──→ Stop Timer
Total Latency = End Time - Start Time
Server-Side Measurement:
Request Received ──→ Processing ──→ Response Sent
↓ ↓
Start Timer Stop Timer
Network Measurement:
Ping: ICMP echo request/response
Traceroute: Path and latency per hop
Latency Measurement Tools
| Tool | Purpose | What it Measures |
|---|---|---|
| curl | HTTP requests | Response time |
| ping | Network connectivity | Round-trip time |
| traceroute | Network path | Per-hop latency |
| ab/wrk | Load testing | Throughput, latency |
| Prometheus | Monitoring | Application metrics |
Measuring Application Latency
# Example: Timing a request
import time
start = time.time()
response = requests.get('https://api.example.com/data')
latency = (time.time() - start) * 1000 # Convert to ms
print(f'Request latency: {latency:.2f}ms')
Latency Distribution
Latency Distribution (1000 requests):
0-50ms: 500 requests (50%) ████████████
50-100ms: 200 requests (20%) ████████
100-200ms: 150 requests (15%) ██████
200-500ms: 100 requests (10%) ████
500ms+: 50 requests (5%) ██
P50 = 45ms
P95 = 180ms
P99 = 350ms
Common Measurement Mistakes
- Measuring only average: Miss slow requests
- Ignoring cold starts: First request is slower
- Not warming cache: Cold cache results are misleading
- Measuring in dev: Production latency differs
- Not accounting for GC: Garbage collection pauses
Reducing Latency
Latency reduction strategies target each layer of the request path.
Strategy Overview
Reduce Latency
├── Network
│ ├── CDN (closer to users)
│ ├── HTTP/2 (multiplexing)
│ ├── Keep-alive (connection reuse)
│ └── Compression (smaller payloads)
├── Server
│ ├── Caching (avoid recomputation)
│ ├── Async I/O (non-blocking)
│ ├── Connection pooling (reuse connections)
│ └── Load balancing (closer servers)
├── Database
│ ├── Indexing (faster lookups)
│ ├── Query optimization (less work)
│ ├── Read replicas (closer reads)
│ └── Caching (avoid queries)
└── Client
├── Lazy loading (load on demand)
├── Prefetching (anticipate needs)
├── Code splitting (smaller bundles)
└── Service workers (offline support)
CDN for Latency Reduction
Without CDN:
User (Tokyo) ──── 160ms ────→ Origin (New York)
With CDN:
User (Tokyo) ──── 5ms ────→ Edge (Tokyo)
Edge (Tokyo) ──── 160ms ────→ Origin (New York)
(only on cache miss)
Caching for Latency
Cache Hit Path (fast):
User → App Server → Cache (1ms) → Response
Cache Miss Path (slow):
User → App Server → Cache (miss) → Database (100ms) → Response
↓
Cache result for next time
Async Processing
Synchronous (slow):
User → Request → [Wait for DB] → [Wait for Email] → Response
(200ms) (300ms) (500ms total)
Asynchronous (fast):
User → Request → [DB] → Response → [Email job]
(200ms) (200ms)
User gets response in 200ms, email sent asynchronously.
Latency Reduction Checklist
- Profile first: Find where time is actually spent
- Cache aggressively: Cache everything possible
- Use CDN: Put content closer to users
- Optimize queries: Index properly, avoid N+1
- Async non-critical: Don't block on emails, logs
- Compress responses: Use gzip/brotli
- HTTP/2: Multiplex requests
- Keep connections alive: Avoid TCP handshake overhead
Practice Problems
Design a scalable Latency system. Cover high-level architecture, data model, and API design.
Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliabilityHow would you scale Latency to handle 10x the current load? Identify bottlenecks and solutions.
Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decompositionAnalyze potential failure modes for Latency and design mitigation strategies.
Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradationQuiz
1. What is the typical network latency between US East and US West coast?
2. Which is the most effective way to reduce latency for static assets?
3. What is the difference between network latency and processing latency?
4. Why is async processing useful for reducing latency?
Flashcards
Question
What are the main sources of latency in a web request?
Click to reveal answer
Answer
DNS resolution (10-50ms), TCP handshake (20-40ms), TLS negotiation (30-50ms), network transit (10-100ms), server processing (10-100ms), database queries (1-1000ms).
Question
How does a CDN reduce latency?
Click to reveal answer
Answer
CDNs cache content at edge locations close to users. Users request from nearby edge (5ms) instead of distant origin (100ms+), reducing network latency.
Question
What is the difference between P50 and P99 latency?
Click to reveal answer
Answer
P50 (median) is the latency 50% of requests experience. P99 is the latency 99% of requests experience - it shows the worst-case for most users.
Question
Name 3 ways to reduce latency in a web application.
Click to reveal answer
Answer
1) CDN for static assets, 2) Caching (Redis, Memcached), 3) Database indexing, 4) Async processing, 5) HTTP/2, 6) Compression.
Question
What is Latency?
Click to reveal answer
Answer
Latency is a key concept in system design.
Revision Notes
Key Takeaways
- 1.Latency appears at every layer: network, processing, database
- 2.Use percentiles to understand actual user experience
- 3.CDNs and caching are the most effective latency reduction tools
- 4.Async processing prevents blocking on slow operations
- 5.Always measure before optimizing
Interview Tips
- •Discuss latency targets for each layer of the system
- •Consider geographic latency for global systems
- •Mention CDN strategy for static assets
- •Discuss cache hit rates and their impact on latency
Cheat Sheet
Latency - Cheat Sheet
Types of Latency:
| Type | Value |
|---|---|
| Same DC | 0.1-1ms |
| Same city | 1-5ms |
| Same country | 5-20ms |
| Cross-continent | 50-200ms |
Measurement:
- Use percentiles (P50, P95, P99)
- Don't just measure average
- Measure in production
Reduction Strategies:
- CDN (closer to users)
- Caching (avoid recomputation)
- Indexing (faster queries)
- Async processing (don't block)
- HTTP/2 (multiplexing)
- Compression (smaller payloads)
Web App Targets:
P50 < 100ms
P95 < 300ms
P99 < 500ms