Most software fails under load long before the code itself breaks. An API endpoint that returns in 18 milliseconds on your laptop stalls for four seconds under five thousand concurrent requests. A database table that feels instant at fifty thousand rows grinds to a halt once background jobs compete with live traffic for disk I/O and locks.
System design is the discipline of anticipating those breaking points before production traffic exposes them. Instead of memorizing buzzwords, strong architectural thinking starts from first principles: how bytes cross networks, where state lives, and which failure modes your users can tolerate.
In this guide, you will learn how modern distributed architectures scale from a single server to millions of requests per minute. For more architecture deep dives, explore our System Design Hub.
Your System Design Learning Roadmap
Performance Metrics & Scaling
Edge, DNS & Load Balancing
Caching & Database Partitioning
Queues, Rate Limits & Resilience
End-to-End Architecture Design
1. Latency, Throughput, and Service Level Objectives
Before adding servers or caches, define what "fast" and "reliable" mean for your workload. Two metrics anchor every capacity conversation: latency and throughput.
Latency is the duration required to handle a single request from start to finish, measured in milliseconds (ms). Throughput is the rate at which a system completes work over time, measured in requests per second (RPS), queries per second (QPS), or megabytes per second (MB/s).
Higher throughput does not guarantee lower latency, and optimizing one often degrades the other. Batching writes boosts throughput by amortizing disk flushes, yet individual requests wait longer inside the batch buffer, raising latency.
Why Averages Lie: Tail Latency (p95 and p99)
Mean latency hides worst-case behavior. If 99 requests finish in 10 ms and 1 request stalls for 2,000 ms during garbage collection, the average is roughly 30 ms—making dashboards look healthy while real users watch spinners.
Production teams track percentiles instead:
- p50 (Median): Half of all requests finish faster than this value.
- p95: 95% of requests meet or beat this threshold; the slowest 5% exceed it.
- p99: Exposes tail stalls caused by lock contention, retries, and network jitter.
Tail latency compounds in microservice fan-outs. If one page load fires 10 parallel backend calls and each has a 1% chance of stalling, the odds that at least one sub-request stalls jump to nearly 10% ($1 - 0.99^{10} \approx 0.0956$).
SLIs, SLOs, and SLAs
Reliability engineering separates targets into three concrete layers:
- SLI (Service Level Indicator): A measured signal, such as HTTP 200 success rate or p99 checkout latency.
- SLO (Service Level Objective): Your internal reliability target for an SLI over a rolling window, such as "99.9% of requests finish under 250 ms over 30 days."
- SLA (Service Level Agreement): A legal customer contract attaching credits or penalties if uptime falls below a looser threshold, such as 99.5%.
2. Vertical Scaling vs. Horizontal Scaling
Every growing system eventually outgrows its initial host. You have two paths to expand capacity: upgrade the machine (vertical scaling) or add more machines (horizontal scaling).
Vertical scaling (scaling up) adds CPU cores, RAM, faster NVMe storage, or higher network bandwidth to a single host. Because everything runs inside one operating system instance, you avoid distributed consensus, network partitions, and cross-node serialization overhead.
Horizontal scaling (scaling out) spreads traffic across a fleet of independent servers behind a routing layer. Commodity VMs or containers share the load, enabling elastic autoscaling during spikes and survival when individual hardware fails.

The Statelessness Prerequisite
Horizontal scaling works cleanly only when application servers are stateless. If Server A keeps a user's cart or login session in local memory, routing the next request to Server B breaks the user's session.
Externalize mutable state into shared infrastructure:
- Store ephemeral sessions and rate counters in an in-memory store like Redis.
- Persist durable domain state in a shared relational or NoSQL database.
- Stream media uploads directly to object storage such as Amazon S3 rather than local disk.
When Vertical Scaling Wins
Avoid premature distributed complexity. One modern server with 64 vCPUs, 256 GB RAM, and NVMe disks can handle tens of thousands of queries per second with proper indexing and connection pooling.
Vertical scaling eventually hits hardware limits, requires brief restarts for major upgrades, and leaves a single point of failure (SPOF). Most mature architectures combine both: moderately sized, vertically tuned instances arranged in a horizontally scaled fleet.
3. DNS, CDNs, and Edge Caching
Network latency is bounded by the speed of light in fiber (~200,000 km/s). A round trip between Tokyo and Virginia takes over 150 ms before your application executes a single line of code. Moving resolution and cached content closer to users removes unnecessary transcontinental hops.
How DNS Shapes Traffic
The Domain Name System (DNS) resolves hostnames like api.example.com into IP addresses and acts as your first traffic-routing layer:
- GeoDNS: Returns the IP of the regional cluster closest to the caller.
- Weighted Routing: Splits responses across regions (e.g., 90%
us-east, 10%us-west) for canary rollouts or migrations. - Failover: Health-checks endpoints and stops advertising dead IPs once Time-to-Live (TTL) expires.
Balance DNS TTLs carefully. A 60-second TTL enables fast regional failover, whereas a 3,600-second TTL cuts resolver traffic and shields authoritative nameservers from bursts.
CDNs and Edge Caching
A Content Delivery Network (CDN) operates globally distributed Points of Presence (PoPs) that serve cached assets within 10–20 ms of users. Browsers fetch scripts, images, and cacheable API responses from a nearby PoP instead of crossing oceans to your origin.
CDNs populate edge nodes using two models:
- Pull CDN: On a miss, the edge fetches from your origin, returns the response, and caches it based on HTTP headers.
- Push CDN: Your deployment pipeline uploads static assets directly to edge storage ahead of traffic.
Control edge caching explicitly using Cache-Control headers:
public, max-age=31536000, immutablefor content-hashed static files (/app.8f3a1c.js).public, s-maxage=60, stale-while-revalidate=30to serve cached edge responses for 60 seconds while refreshing asynchronously.private, no-storefor personalized or sensitive payloads.
Review HTTP headers, status codes, and payload semantics in our guide to REST APIs, HTTP methods, and JSON.
4. Load Balancing and Traffic Routing Algorithms
Once traffic reaches your datacenter, a load balancer distributes connections across healthy backend nodes. It prevents single-server saturation and hides backend IP changes during deployments or autoscaling.
Layer 4 vs. Layer 7 Load Balancing
- Layer 4 (Transport): Routes packets using IP addresses and TCP/UDP ports without terminating TLS or reading HTTP headers. Solutions like IPVS and AWS NLB handle millions of packets per second at minimal latency.
- Layer 7 (Application): Terminates TLS, inspects HTTP paths, headers, and cookies, and routes dynamically—sending
/searchto search nodes and/checkoutto billing nodes. NGINX, HAProxy, and Envoy operate here.
Routing Algorithms Compared
| Algorithm | Routing Logic | State Needed | Best Use Case | Trade-Off |
|---|---|---|---|---|
| Round Robin | Cycles sequentially through backends | None | Identical servers with uniform fast requests | Ignores slow queries piling up |
| Weighted Round Robin | Sends more requests to higher weights | Static weights | Mixed instance sizes during upgrades | Weights ignore live CPU load |
| Least Connections | Picks backend with fewest active requests | Open connection count | Uneven request costs (uploads, reports) | Slight coordination overhead |
| IP Hash | Hashes client IP modulo server count | None | Lightweight affinity without cookies | Skews behind shared NAT gateways |
| Consistent Hashing | Maps keys and servers onto a hash ring | Virtual node ring | Distributed caches and sharded routers | Higher setup complexity |
Consistent hashing prevents cache collapse when nodes scale. Naive hash(key) % N remaps nearly 100% of keys whenever N changes. Consistent hashing maps servers and keys onto a $0$ to $2^{32}-1$ ring using virtual nodes, so adding or removing a node moves only about $1/N$ of keys.
NGINX Upstream Configuration
This Layer 7 config pairs least_conn with passive health checks, connection pooling, and tight timeouts:
upstream app_backends {
least_conn;
server 10.0.1.11:8080 max_fails=3 fail_timeout=15s;
server 10.0.1.12:8080 max_fails=3 fail_timeout=15s;
keepalive 64;
}
server {
listen 443 ssl http2;
server_name api.example.com;
location / {
proxy_pass http://app_backends;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_connect_timeout 2s;
proxy_read_timeout 10s;
proxy_next_upstream error timeout http_502 http_503;
}
}Setting keepalive 64 with proxy_set_header Connection "" reuses upstream TCP sockets, avoiding repeated TCP handshakes and ephemeral port exhaustion.
5. Application Caching Strategies and Eviction Policies
Memory reads complete in under 1 millisecond, compared to 5–50 ms for indexed disk queries. Caching leverages locality of reference: a small slice of hot keys drives most read traffic.
Core Caching Patterns
| Pattern | Read Flow | Write Flow | Trade-Off | Best Fit |
|---|---|---|---|---|
| Cache-Aside | App checks cache; on miss, reads DB and populates cache | App writes DB, then deletes cache key | Brief eventual consistency; caches only hot reads | General read-heavy APIs |
| Read-Through | Cache library fetches from DB on miss | App writes DB (often paired with Write-Through) | Cleaner app code; requires provider plugin | Standardized data layers |
| Write-Through | Reads hit warm cache reliably | App writes cache, which synchronously writes DB | Fresh cache; higher write latency | Low-staleness read/write mixes |
| Write-Behind | Reads hit cache directly | App writes cache; flushes async to DB | Ultra-fast writes; data loss risk on crash | High-ingest counters, telemetry |
DEL) after updating the database instead of overwriting it (SET). Concurrent writes updating the DB and cache out of order can leave stale values trapped until TTL expiration.Eviction Policies and Stampede Prevention
When Redis or Memcached fills maxmemory, eviction policies reclaim space:
- LRU (Least Recently Used): Evicts items untouched the longest using an $O(1)$ hash map and doubly linked list (see our Data Structures guide).
- LFU (Least Frequently Used): Tracks decaying access counts so rarely hit keys are evicted before consistently hot ones.
- TTL Expiration: Bounds staleness even if an invalidation event fails.
When a popular key expires under heavy traffic, thousands of concurrent misses hit the database at once—a cache stampede (thundering herd). Prevent stampedes with TTL jitter (adding random seconds to TTLs), mutex single-flight locks (letting one worker rebuild the key), and short negative caching (null entries) to block nonexistent-ID probes.
Cache-Aside with Stampede Lock and Jitter
import { randomInt } from 'node:crypto';
import type { Redis } from 'ioredis';
export async function getUserProfile(
redis: Redis,
dbFetch: (id: string) => Promise<Record<string, unknown> | null>,
userId: string
) {
const key = `user:${userId}`;
const hit = await redis.get(key);
if (hit) return JSON.parse(hit);
const lockKey = `lock:${key}`;
const gotLock = await redis.set(lockKey, '1', 'PX', 3000, 'NX');
if (!gotLock) {
await new Promise((r) => setTimeout(r, 50));
const retry = await redis.get(key);
if (retry) return JSON.parse(retry);
}
try {
const profile = await dbFetch(userId);
if (!profile) {
await redis.set(key, 'null', 'EX', 30);
return null;
}
await redis.set(key, JSON.stringify(profile), 'EX', 300 + randomInt(0, 61));
return profile;
} finally {
if (gotLock) await redis.del(lockKey);
}
}6. Databases at Scale: Replication, Sharding, and CAP/PACELC
Caches speed up reads, but databases guard durable state. When one database node saturates CPU, locks, or disk I/O, you scale via replication and sharding.

Read Replicas and Replication Lag
Read-heavy apps (10:1 or 100:1 reads to writes) use primary-replica replication. All writes hit the primary, which streams its Write-Ahead Log (WAL) asynchronously to read replicas.
Because asynchronous replicas lag behind the primary by milliseconds—or seconds during bursts—a user updating their profile may read stale data on the next refresh. Fix this with read-your-own-writes routing: send a user's reads to the primary for a few seconds right after they perform a write.
Partitioning and Sharding
Before sharding across physical clusters, single-node declarative partitioning keeps indexes compact and maintenance fast:
CREATE TABLE audit_events (
event_id BIGINT NOT NULL,
tenant_id INT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
payload JSONB NOT NULL
) PARTITION BY RANGE (created_at);
CREATE TABLE audit_events_2026_11 PARTITION OF audit_events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE INDEX idx_audit_2026_11_tenant
ON audit_events_2026_11 (tenant_id, created_at DESC);Once writes or storage outgrow one primary, split rows horizontally across independent shards:
- Hash Sharding: Spreads writes evenly using
hash(shard_key)or consistent hashing. Fast key lookups, costly scatter-gather range queries. - Range Sharding: Groups contiguous ranges (e.g.,
tenant_id1–100k). Fast range scans, but risks hot shards on sequential keys. - Directory Sharding: Stores key-to-shard mappings in a lookup service for flexible rebalancing, adding lookup overhead.
SQL vs. NoSQL and CAP / PACELC
Relational SQL engines (PostgreSQL, MySQL) enforce schemas and ACID guarantees (see our SQL Basics Guide), while NoSQL engines trade joins for horizontal write scale.
| Paradigm | Data Model | Scaling Strength | Consistency | Ideal Workload |
|---|---|---|---|---|
| Relational (SQL) | Normalized tables | Vertical + read replicas; sharded via Citus/Vitess | Strong ACID | Payments, orders, relational integrity |
| Key-Value | Value by primary key | Linear horizontal sharding | Tunable (often eventual) | Sessions, flags, shopping carts |
| Document | JSON/BSON documents | Built-in replica sets and sharding | Strong per-document | Catalogs, CMS, user profiles |
| Wide-Column | Sparse column families | Multi-region write throughput | Tunable (AP default) | Telemetry, IoT ingestion, logs |
Two theorems govern distributed databases:
- CAP Theorem: During a network partition (P), a distributed store chooses Consistency (C) (rejecting potentially stale operations) or Availability (A) (serving requests despite split state). Real systems are CP (etcd, ZooKeeper) or AP (Cassandra, DNS).
- PACELC Theorem: Extends CAP to healthy networks. If Partitioned (P), choose A or C; Else (E), choose between Latency (L) and Consistency (C). Synchronous cross-region replication ensures consistency (
PC/EC) at higher write latency; asynchronous replication stays fast (PA/EL) with eventual consistency.
7. Asynchronous Processing and Message Queues
Slow side effects—sending emails, rendering PDFs, indexing search—should not block HTTP responses. Offloading work to a message queue absorbs traffic spikes and prevents downstream slowdowns from stalling API threads.
RabbitMQ vs. Kafka
- Message Brokers (RabbitMQ, SQS): Push or deliver tasks to competing workers and delete each message upon acknowledgment (
ACK). Ideal for background jobs and complex routing. - Event Logs (Apache Kafka, Redpanda): Append immutable events to ordered, partitioned logs retained for days. Consumers track their own offsets, letting analytics, billing, and search pipelines replay the same stream independently.
At-Least-Once Delivery and Idempotency
Because workers crash and networks drop ACKs, most queues provide at-least-once delivery. Every consumer must be idempotent so duplicate deliveries never double-charge customers or corrupt state:
export async function handlePaymentCaptured(
db: { query: (sql: string, params: unknown[]) => Promise<{ rowCount: number }> },
event: { eventId: string; orderId: string; amountCents: number }
): Promise<void> {
const claimed = await db.query(
`INSERT INTO processed_events (event_id, processed_at)
VALUES ($1, NOW()) ON CONFLICT (event_id) DO NOTHING`,
[event.eventId]
);
if (claimed.rowCount === 0) return; // Safe duplicate skip
await db.query(
`UPDATE orders SET status = 'PAID', paid_cents = $2 WHERE id = $1`,
[event.orderId, event.amountCents]
);
}Pair this with the Transactional Outbox pattern: write domain updates and an outbox row inside one local ACID transaction, then relay outbox rows to Kafka reliably.
Dead-Letter Queues (DLQs)
Poison messages—malformed payloads or missing references—block workers if retried endlessly. Cap retries with exponential backoff and route persistent failures to a Dead-Letter Queue (DLQ) where engineers can inspect, fix, and replay them safely.
8. Rate Limiting, Backpressure, and Circuit Breakers
Resilient systems protect themselves when demand surges or dependencies fail, returning HTTP 429 Too Many Requests with a Retry-After header rather than crashing.
Rate Limiting Algorithms
- Token Bucket: Holds up to
Btokens, refilling atRtokens/second. Permits brief bursts while enforcing an average rate. - Leaky Bucket: Queues requests in a fixed FIFO buffer draining at a constant rate, smoothing downstream spikes.
- Fixed Window Counter: Counts requests per discrete interval; memory-light, though vulnerable to 2x boundary bursts.
- Sliding Window Counter: Blends the prior and current window counts to stop boundary spikes cleanly.
Distributed Token Bucket in Redis
Running rate limits in local app memory fails across clusters. Executing a Redis Lua script keeps token math atomic across all API servers:
import type { Redis } from 'ioredis';
const LUA_BUCKET = `
local key = KEYS[1]
local cap, rate, now = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local d = redis.call("HMGET", key, "tokens", "ts")
local tokens = math.min(cap, (tonumber(d[1]) or cap) + math.max(0, now - (tonumber(d[2]) or now)) * rate)
local ok = tokens >= 1 and 1 or 0
if ok == 1 then tokens = tokens - 1 end
redis.call("HMSET", key, "tokens", tokens, "ts", now)
redis.call("EXPIRE", key, math.ceil(cap / rate) * 2)
return ok
`;
export async function allowRequest(redis: Redis, clientKey: string, cap = 20, rate = 5) {
const res = await redis.eval(LUA_BUCKET, 1, `rl:${clientKey}`, cap, rate, Date.now() / 1000);
return res === 1;
}Backpressure and Circuit Breakers
When downstream services stall, holding open threads causes cascading failures. Backpressure rejects excess work early instead of letting queues grow unbounded. Circuit breakers isolate failing dependencies across three states:
- Closed: Traffic passes normally while tracking error rates.
- Open: Trips when failures cross a threshold, failing fast locally for a cooldown period to let the dependency recover.
- Half-Open: Sends limited probe requests after cooldown; closes on success or reopens on failure.
9. Real-World Walkthrough: Designing a Scalable URL Shortener
Let's combine these building blocks to design a global URL shortener like Bitly, starting from scale estimates and tracing both request paths.
Step 1Requirements and Capacity Math
Core scope: Shorten URLs to 7-character aliases, redirect with sub-20 ms latency at the edge/cache, and track click counts asynchronously.
Back-of-the-envelope sizing:
- Writes: 100 million new links/month $\rightarrow \frac{100\text{M}}{30 \times 86{,}400} \approx 38.6 \text{ writes/sec}$ (~120 peak).
- Reads (100:1 ratio): 10 billion redirects/month $\rightarrow 3{,}860 \text{ reads/sec}$ (~15,000–20,000 peak).
- 5-year storage: $100\text{M} \times 12 \times 5 = 6\text{ billion}$ rows. At ~500 bytes/row, storage totals ~3 TB.
- Key space: Base62 (
0-9,a-z,A-Z) with 7 characters provides $62^7 \approx 3.52 \text{ trillion}$ unique codes.
Step 2End-to-End Request Flow

Step 3Write and Read Execution
Write Path (POST /api/v1/urls):
- The Layer 7 load balancer and Redis token-bucket limiter screen abuse.
- Instead of truncating hashes (which risks collisions and requires DB retries), stateless API nodes claim pre-allocated numeric ID ranges from a Key Generation Service (KGS) and Base62-encode them into unique 7-character slugs.
- The API writes
(short_code, long_url, created_at)to the sharded primary database (partitioned byshort_code) and returns201 Created.
Read Path (GET /:code):
- Viral links hit the CDN edge cache first, returning
HTTP 302 Foundin under 15 ms. (Use302instead of301if you track analytics, since browsers aggressively cache301redirects locally and bypass your servers.) - On an edge miss, stateless redirect servers check Redis (
GET url:a9Xz2Qp). Caching the top 20% hot links consumes only gigabytes of RAM while absorbing roughly 80% of traffic. - On a cache miss, the service reads a database replica, warms Redis with a jittered TTL, returns
302, and fires aLinkClickedevent to Kafka so background workers aggregate analytics without locking the redirect path.
10. Common Architecture Mistakes and Production Observability
Even sound diagrams break in production when teams ignore operational pitfalls or lack telemetry:
- Premature Microservices: Splitting a small team's codebase into 20 microservices trades fast function calls for network latency, distributed debugging, and schema drift. Start with a modular monolith and extract services only where scaling or team boundaries demand it.
- Unbounded Queries and Buffers: Running
SELECT *withoutLIMITor buffering infinite tasks in memory guarantees Out-Of-Memory crashes during spikes. - N+1 Query Storms: Fetching 50 rows then looping 50 extra queries turns one request into 51 round trips. Batch with
IN (...)clauses or DataLoaders. - Hidden SPOFs: Three stateless containers still fail together if they share one un-replicated NAT gateway, unclustered Redis node, or expiring TLS certificate.
Production Observability
Instrument every service across three pillars:
- Metrics: Monitor Google SRE's Four Golden Signals—Latency (p50/p95/p99), Traffic (RPS), Errors (5xx rates), and Saturation (CPU, memory, pool exhaustion). Apply the RED method (Rate, Errors, Duration) to services and USE (Utilization, Saturation, Errors) to hosts.
- Structured Logs: Emit JSON logs with correlation IDs and durations; scrub secrets and PII.
- Distributed Tracing: Propagate W3C
traceparentheaders end-to-end so trace waterfalls expose exact bottlenecks across load balancers, caches, and databases.
Frequently Asked Questions (FAQs)
1. When should I migrate from a monolith to microservices?
Stay on a modular monolith until clear scaling or organizational friction forces a split—such as isolating CPU-heavy media workers from an API, enforcing strict compliance boundaries, or unblocking large independent teams.
2. What is the difference between partitioning and sharding?
Partitioning splits one large table into smaller physical segments inside a single database instance. Sharding spreads horizontal partitions across separate database servers, giving each shard independent CPU, memory, and disk capacity.
3. Why use HTTP 302 instead of HTTP 301 for a URL shortener?
HTTP 301 tells browsers the move is permanent, so they cache the target URL locally and skip your server on repeat clicks. HTTP 302 keeps traffic flowing through your infrastructure for analytics and destination updates.
4. How does consistent hashing reduce cache misses when scaling?
Modulo hashing (hash(key) % N) remaps nearly every key when N changes. Consistent hashing places nodes and keys on a virtual ring so adding or removing a server shifts only roughly 1/N of cached keys.
5. How do applications prevent stale reads from replication lag?
Route a user's immediate post-mutation reads back to the primary database for a short window ("read-your-own-writes"), or track replication log sequence numbers (LSNs) before serving from replicas.
6. When is Kafka better than RabbitMQ?
Use Kafka for high-throughput ordered event streams, multi-consumer fan-out, and event replay. Use RabbitMQ for traditional background task queues, per-message routing rules, and short-lived job dispatch.
7. How do I pick SQL vs. NoSQL in a system design interview?
Default to SQL for relational integrity, ad-hoc queries, and ACID transactions like payments. Choose NoSQL for massive write scale, flexible schemas, multi-region availability, or simple key-value lookups.
8. What separates an SLO from an SLA?
An SLO is an internal engineering target (e.g., 99.95% uptime) guiding error budgets and release velocity. An SLA is a customer contract with financial remedies, usually set slightly looser than the SLO.
9. Why do automatic retries cause outages?
Retrying immediately during a partial degradation multiplies load on an already saturated dependency, turning brief slowdowns into a cascading retry storm. Always apply exponential backoff, jitter, and retry budgets.
Conclusion
Scalable systems rely on fundamentals rather than exotic tools: keep compute stateless, serve hot reads from CDNs and caches, protect databases with replicas and clean shard keys, offload slow work to idempotent queues, and guard boundaries with rate limits and circuit breakers. Measure first with percentiles and Golden Signals, and add complexity only when real numbers require it.
