System Design
Purpose and Requirements
System design translates product goals into a concrete topology of services, storage engines, network boundaries, and failure-handling mechanisms. Before choosing databases or frameworks, engineers must establish what the system must do and how reliably it must perform under load.
Functional Requirements
Functional requirements define the observable behaviors, APIs, and data flows that users or downstream services depend on. Documenting concrete use cases early prevents designing infrastructure for features the system never needs.
- Core capabilities: Specify the primary operations (for example, creating an order, uploading media, or querying a timeline) and their expected inputs and outputs.
- Data ownership: Identify which service owns each entity, how records are validated, and which consistency rules apply to state transitions.
- System boundaries: Clarify external integrations, authentication boundaries, and read-to-write ratios (such as 100:1 read-heavy feeds versus write-heavy telemetry).
Non-Functional Requirements and SLOs
Non-functional requirements govern how a system behaves under stress, partial failure, and growth. Quantifying these targets with Service Level Indicators (SLIs), Service Level Objectives (SLOs), and Service Level Agreements (SLAs) turns vague goals into measurable engineering constraints.
- Latency percentiles: Measure response times at
p50(median),p95, andp99(tail latency) rather than averages, because tail spikes dominate user experience in distributed fan-out calls. - Throughput: Estimate requests per second (RPS), peak burst multipliers, and bandwidth so network and compute tiers are sized for spikes rather than daily averages.
- Availability and durability: Distinguish uptime (e.g., 99.9% allows ~8.76 hours of downtime per year; 99.99% allows ~52.6 minutes) from durability (preventing committed data loss via replication and backups).
Layered System Architecture
Most production web systems separate traffic routing, stateless application compute, fast caching, asynchronous job processing, and durable storage into distinct layers so each tier can scale and fail independently.
Figure 1: End-to-end request and background-job topology separating stateless compute from caching, queuing, and replicated storage.
Scaling and Load Balancing
As request volume grows, a single server eventually hits CPU, memory, disk I/O, or network saturation. Scaling strategies determine how you add capacity without introducing single points of failure.
Vertical vs. Horizontal Scaling
Vertical scaling (scaling up) upgrades an existing machine with faster CPUs, more RAM, or NVMe storage, whereas horizontal scaling (scaling out) distributes work across a fleet of commodity nodes.
- Vertical scaling: Requires minimal architectural change and avoids distributed coordination, but hits a hard hardware ceiling and creates a single point of failure during restarts or hardware faults.
- Horizontal scaling: Supports elastic capacity and rolling zero-downtime deployments, but requires load balancing, externalized state, and explicit handling of partial network failures.
Stateless Services and Load Balancers
Horizontal scaling works cleanly only when application servers are stateless—meaning any node can handle any request because session tokens, uploaded files, and shared state live in external stores such as Redis, object storage, or a database.
- L4 vs. L7 load balancing: Layer 4 (transport) balancers forward TCP/UDP packets at high speed, while Layer 7 (application) balancers inspect HTTP headers, paths, and cookies to route traffic, terminate TLS, and enforce rate limits.
- Health checks and draining: Active health checks remove unhealthy instances from rotation automatically, while connection draining lets in-flight requests finish before a node shuts down.
Data Storage, Caching, and Consistency
Stateless compute scales horizontally with minimal friction, whereas stateful data tiers are usually the primary bottleneck. Choosing how to replicate, partition, cache, and synchronize data defines the system's latency and correctness guarantees.
Replication and Sharding
Replication copies the same dataset across multiple nodes for fault tolerance and read throughput, while sharding splits a dataset across independent partitions so no single node stores or writes everything.
- Primary-replica replication: Writes go to a single primary and replicate asynchronously (or semi-synchronously) to read replicas. Read-your-own-writes anomalies can occur if a user reads from a lagging replica immediately after writing.
- Horizontal sharding: Partitioning by a shard key (such as
tenant_idor consistent-hasheduser_id) scales write throughput, but cross-shard joins and hot keys (celebrity accounts) require careful key design.
Caching Strategies
In-memory caches (such as Redis or Memcached) reduce database load and cut read latency from tens of milliseconds to sub-millisecond lookups, at the cost of managing stale data.
- Cache-aside (lazy loading): The application checks the cache first; on a miss, it queries the database, writes the result to the cache with a time-to-live (TTL), and returns it.
- Write-through and write-behind: Write-through updates cache and database synchronously together, keeping them aligned at higher write latency. Write-behind buffers writes in cache and flushes asynchronously, trading durability risk for high write throughput.
- Cache stampede protection: When a popular key expires, hundreds of concurrent misses can overwhelm the database; request coalescing (singleflight) or jittered TTLs prevent cascading overload.
CAP and PACELC Trade-Offs
In a distributed data store, network partitions are inevitable. The CAP theorem states that during a network partition (P), a system must choose between strict Consistency (C, rejecting or blocking writes that cannot reach a quorum) and Availability (A, serving potentially stale reads or accepting divergent writes).
The PACELC theorem extends CAP to normal operation without partitions (Else): even when the network is healthy, distributed stores must trade off Latency (L) against Consistency (C), because synchronous cross-region replication adds network round-trip latency to every write.
System Design Trade-Off Matrix
Every architectural mechanism solves one bottleneck while introducing new operational complexity. Use the matrix below to weigh common design choices against their failure modes.
| Mechanism | Primary Benefit | Key Trade-Off / Cost | When to Choose |
|---|---|---|---|
| Vertical Scaling | Zero distributed coordination; low operational overhead | Hardware ceiling; single point of failure | Early-stage workloads or single-node databases |
| Horizontal Scaling | Elastic capacity and rolling fault tolerance | Requires stateless tiers, load balancers, and health checks | High-throughput APIs and variable traffic |
| Read Replicas | Scales read QPS and improves regional read latency | Replication lag can serve stale reads after writes | Read-heavy workloads tolerating eventual consistency |
| Sharding | Scales write throughput and total storage beyond one node | Complex rebalancing, hotspots, and no cross-shard joins | Datasets exceeding single-primary write or disk limits |
| Cache-Aside | Caches only requested data; resilient to cache restarts | Cache miss penalty and potential stale reads until TTL | General-purpose read acceleration |
| Async Message Queue | Smooths traffic bursts; decouples slow downstream work | Eventual completion; requires idempotent consumers and DLQs | Email, billing webhooks, video encoding, and batch jobs |
Asynchronous Processing and Resilience
Distributed systems fail partially: downstream APIs slow down, disks fill, and packets drop. Resilient architectures isolate slow work behind queues and protect synchronous paths with bounded timeouts and circuit breakers.
Message Queues and Backpressure
Synchronous request-response chains couple caller latency to the slowest downstream dependency. Introducing a message queue (such as Kafka, RabbitMQ, or SQS) lets producers acknowledge work quickly while workers process jobs at a sustainable pace.
- Backpressure: When consumers fall behind, bounded queues and rate limiters signal producers to slow down instead of exhausting memory and crashing the cluster.
- Dead-letter queues (DLQ): Poison messages that fail repeatedly after bounded retries are routed to a DLQ for inspection so they do not block healthy traffic.
Timeouts, Retries, and Circuit Breakers
Without strict timeouts, a stalled dependency ties up worker threads until the entire service becomes unresponsive. Combining bounded timeouts with jittered retries and circuit breakers prevents localized slowdowns from becoming system-wide outages.
- Exponential backoff with jitter: Retrying immediately amplifies load on a struggling server (thundering herd). Waiting
base * 2^attempt + random_jitterspreads retry waves safely. - Idempotency keys: Because networks can drop responses after a server commits a write, mutating endpoints (such as payments) require client-supplied idempotency keys so retries do not charge a user twice.
- Circuit breakers: A circuit breaker tracks failure rates across three states—Closed (normal traffic), Open (fail fast without calling the broken dependency), and Half-Open (probe with limited requests to verify recovery).
Observability and Cost Economics
You cannot operate or debug a distributed system you cannot observe. Alongside technical reliability, engineers balance infrastructure cost, legal compliance (such as data residency and retention), and ethical data handling.
- Three pillars of observability: Structured logs capture discrete events, metrics track aggregated latency/error/saturation trends against SLOs, and distributed traces follow a single request ID across service boundaries.
- Cost-aware architecture: Over-provisioning multi-region active-active databases or caching rarely read data inflates cloud spend without improving user-facing SLOs; measure cost per request alongside p99 latency.
Core Design Principles and Best Practices
Technology stacks evolve, but sound architectural habits remain consistent across decades of systems engineering.
Modularity, Abstraction, and Restraint
Strong architectures minimize unnecessary coupling so teams can evolve components independently without risking system-wide regressions.
- Clear module boundaries: Hide internal storage details behind well-defined service or API contracts so consumers do not depend on private schemas.
- Design for failure: Assume any network call can time out, any disk can fail, and any dependency can return malformed data.
- Avoid premature distribution: A well-structured modular monolith is faster to debug, deploy, and refactor than a premature microservice mesh when team size and scale do not justify network boundaries.
Iterative Design Workflow
When approaching a new system design problem, follow a repeatable engineering sequence rather than jumping straight to tool names:
- Clarify requirements and SLOs: Lock down core use cases, read/write ratios, latency targets, and consistency needs.
- Estimate capacity: Perform back-of-the-envelope calculations for QPS, storage growth, and peak bandwidth.
- Sketch the high-level topology: Trace the critical read and write paths across edge, compute, cache, queue, and storage tiers.
- Identify bottlenecks and failure modes: Stress-test the design for hot keys, replication lag, cascading retries, and single points of failure.
- Record Architecture Decision Records (ADRs): Document the chosen option, rejected alternatives, and trade-offs so future maintainers understand why the system looks the way it does.