System design fundamentals, from single servers to distributed architectures
Learn how to architect scalable systems by progressing from single-node web servers to load-balanced, cached, and partitioned distributed services.
MonksBit Desk
November 25, 2026 · 9 min read · 44 views
Read
System design is the process of defining the architecture, components, modules, interfaces, and data flow of a computing system to satisfy specified operational and business requirements. It solves the problem of scaling software reliably so that applications can handle increasing traffic, large datasets, and hardware failures without degrading performance.
You will need. Basic knowledge of client-server networking (HTTP requests and responses) · Familiarity with standard data structures like dictionaries and lists
The full lesson
Level 1 · Beginner: The single-server paradigm and client-server communication
Every web application starts with a client and a server. A client is an agent such as a browser or mobile device that initiates a request, and a server is a computer program running on hardware that listens for incoming requests, performs computations, and returns responses.
In a minimal architecture, a single server handles every task: it serves static assets, executes business logic, and reads or writes application state into local memory or a local file on the same machine. For instance, consider a lightweight key-value service where a user sends a key and receives the associated value.
While this architecture is simple to deploy and understand, it has a single point of failure. If the machine runs out of memory, crashes, or loses power, the entire system becomes completely unavailable to all clients.
A single-node in-memory store simulating a monolithic server
class SingleServer: def __init__(self): self.storage = {} def handle_request(self, method: str, key: str, value: str = None) -> dict: if method == "GET": if key in self.storage: return {"status": 200, "data": self.storage[key]} return {"status": 404, "error": "Key not found"} elif method == "SET": self.storage[key] = value return {"status": 201, "message": "Stored successfully"} return {"status": 400, "error": "Unsupported method"}# Demonstrationserver = SingleServer()print(server.handle_request("SET", "user_1", "Alice"))print(server.handle_request("GET", "user_1"))print(server.handle_request("GET", "user_2"))
Key takeaways
- A client initiates requests and a server listens, processes, and returns responses.
- A monolithic single-server setup couples business logic, routing, and persistence into one machine.
- Single-server setups are vulnerable to complete outages when traffic surges or hardware fails.
Level 2 · Intermediate: Horizontal scaling, load balancing, and caching
When a single machine reaches its compute or memory ceiling, you can scale vertically by buying a larger machine, or scale horizontally by adding more machines. Horizontal scaling is standard in system design because commodity machines are cost-effective and can be scaled incrementally.
Horizontal scaling introduces two immediate requirements: distributing incoming traffic among multiple servers and maintaining fast data access. A load balancer sits between clients and servers, dispatching requests across an array of worker nodes using algorithms such as round-robin or least-connections.
To prevent worker nodes and back-end databases from handling redundant disk or compute operations, systems place an in-memory cache close to the application layer. The cache stores frequently accessed key-value pairs in RAM, allowing reads to complete in sub-millisecond time. If a key is present, it is a cache hit; if absent, it is a cache miss, prompting a database lookup followed by a cache update.
Edge cases in this architecture include server crashes during request dispatch and cache invalidation staleness. If a worker goes down, the load balancer must detect the failure via health checks and reroute traffic to healthy nodes without user-facing failures.
A round-robin load balancer dispatching requests to multiple worker nodes with a shared cache
from typing import List, Dict, Optionalclass Cache: def __init__(self, capacity: int = 100): self.capacity = capacity self.data: Dict[str, str] = {} def get(self, key: str) -> Optional[str]: return self.data.get(key) def put(self, key: str, value: str) -> None: if len(self.data) >= self.capacity: oldest_key = next(iter(self.data)) del self.data[oldest_key] self.data[key] = valueclass BackendWorker: def __init__(self, worker_id: int, database: Dict[str, str], cache: Cache): self.worker_id = worker_id self.database = database self.cache = cache self.is_healthy = True def process_get(self, key: str) -> dict: cached_value = self.cache.get(key) if cached_value is not None: return {"worker": self.worker_id, "source": "cache", "value": cached_value} db_value = self.database.get(key) if db_value is not None: self.cache.put(key, db_value) return {"worker": self.worker_id, "source": "db", "value": db_value} return {"worker": self.worker_id, "source": "none", "value": None}class LoadBalancer: def __init__(self, workers: List[BackendWorker]): self.workers = workers self.current_idx = 0 def route(self, key: str) -> dict: healthy_workers = [w for w in self.workers if w.is_healthy] if not healthy_workers: return {"status": 503, "error": "No healthy workers available"} worker = healthy_workers[self.current_idx % len(healthy_workers)] self.current_idx = (self.current_idx + 1) % len(healthy_workers) return {"status": 200, "payload": worker.process_get(key)}# Demonstrationshared_db = {"item_a": "Widget", "item_b": "Gadget"}shared_cache = Cache(capacity=2)workers = [BackendWorker(i, shared_db, shared_cache) for i in range(2)]lb = LoadBalancer(workers)print(lb.route("item_a")) # Cache miss, loads from DBprint(lb.route("item_a")) # Cache hit on next workerworkers[0].is_healthy = Falseprint(lb.route("item_b")) # Handled exclusively by healthy worker
Key takeaways
- Horizontal scaling adds more machines in parallel instead of making a single machine more powerful.
- A load balancer sits in front of servers to distribute traffic evenly and isolate failed nodes.
- Caching reduces latency and database load by keeping frequently accessed entries in memory.
Level 3 · Advanced: Data partitioning, consistent hashing, and trade-offs
As stored data exceeds the storage capacity of a single database, the data layer itself must be partitioned across multiple nodes. This technique is known as database sharding or partitioning. When sharding, queries must be directed to the exact node that owns the target key.
A naive approach partitions keys using the modulus operator: hash(key) % N, where N is the number of nodes. However, adding or removing a node changes N, causing almost every key to remap to a different server. In production systems, this triggers a cache stampede or heavy database migration.
Consistent hashing solves this problem by mapping both nodes and keys to positions on an abstract circular ring. A key is assigned to the first node encountered moving clockwise along the ring. When a node is added or removed, only keys residing between that node and its predecessor are migrated, minimizing rebalancing overhead to k/N keys on average, where k is total keys.
Distributed systems must balance competing trade-offs characterized by the CAP theorem: Consistency (all nodes see identical data simultaneously), Availability (every request receives a non-error response), and Partition Tolerance (the system continues operating despite lost network packets). Because physical networks inherently experience partitions, engineers must choose between enforcing strict consistency or maintaining uninterrupted availability.
Consistent hashing ring implementation with virtual nodes for uniform balance
import bisectimport hashlibfrom typing import List, Dictclass ConsistentHashRing: def __init__(self, replicas: int = 3): self.replicas = replicas self.ring: List[int] = [] self.ring_to_node: Dict[int, str] = {} def _hash(self, key: str) -> int: return int(hashlib.md5(key.encode("utf-8")).hexdigest(), 16) def add_node(self, node: str) -> None: for i in range(self.replicas): vnode_key = f"{node}-replica-{i}" val = self._hash(vnode_key) bisect.insort(self.ring, val) self.ring_to_node[val] = node def remove_node(self, node: str) -> None: for i in range(self.replicas): vnode_key = f"{node}-replica-{i}" val = self._hash(vnode_key) idx = bisect.bisect_left(self.ring, val) if idx < len(self.ring) and self.ring[idx] == val: del self.ring[idx] del self.ring_to_node[val] def get_node(self, key: str) -> str: if not self.ring: raise ValueError("Ring is empty") val = self._hash(key) idx = bisect.bisect_right(self.ring, val) if idx == len(self.ring): idx = 0 return self.ring_to_node[self.ring[idx]]# Demonstrationring = ConsistentHashRing(replicas=3)ring.add_node("Database_A")ring.add_node("Database_B")print("user_100 routed to:", ring.get_node("user_100"))print("user_200 routed to:", ring.get_node("user_200"))ring.add_node("Database_C")print("user_100 routed to after adding node:", ring.get_node("user_100"))
Key takeaways
- Consistent hashing minimizes key relocation during scale-out or scale-in events from O(N) to O(K/N).
- Virtual nodes ensure uniform distribution of keys across nodes to prevent hot spots.
- The CAP theorem dictates that distributed systems cannot simultaneously achieve strong consistency and 100% availability during network splits.
Complexity
- Time: O(1) average lookup for single-server and cache; O(log(V * N)) key lookup on a consistent hash ring where N is nodes and V is virtual replicas.
- Space: O(N * V) auxiliary memory to store hash ring coordinates, plus O(K) memory for the actual cached data entries.
Accessing an in-memory hash table or routing via round-robin uses constant O(1) time. Finding a responsible node on a consistent hash ring uses binary search over N*V sorted positions, requiring O(log(N*V)) time.
Common mistakes
- Treating caching as a primary database rather than an ephemeral layer subject to eviction and data loss.
- Using naive modulo hashing (hash(key) % N) for sharding, which invalidates all assignments when node counts change.
- Failing to implement timeouts, circuit breakers, or health checks on backend workers, leading to cascading failures.
- Premature optimization by introducing complex microservices and sharded storage before traffic patterns demand them.
Practice problems
- Weighted round-robin dispatcher (easy). Hint: Assign integer capacity weights to each worker and distribute requests proportionally instead of sequentially.
- Least-Recently-Used (LRU) cache (medium). Hint: Combine a standard hash map with a doubly linked list to achieve O(1) reads, writes, and evictions.
- Replication and split-brain detection (hard). Hint: Simulate a quorum consensus protocol where writes require confirmation from a majority ((N/2) + 1) of nodes.
Summary
System design is the structured discipline of planning software architectures that handle scale, minimize latency, and tolerate failures. Starting from a single client-server node, systems evolve through horizontal scaling, load balancing, caching, and consistent data partitioning to maintain reliability and performance under load.
Was this helpful?
Comments (0)
Sign in or create an account to join the conversation.
- No comments yet. Be the first!