- Part 5 of 21 in System Design Roadmap: From Beginner to Intermediate Architecture Beginner
Client-server architecture, from raw sockets to scaled distributed systems
Learn how client-server architecture works, implement custom TCP communication in Python, and scale services with connection handling and load distribution.
MonksBit Desk
November 25, 2026 · 9 min read · 34 views
Read
Client-server architecture is a distributed computing model where workloads are partitioned between service requesters, called clients, and service providers, called servers. Clients initiate communication sessions to request specific resources or operations, and servers listen for incoming requests, process them, and return appropriate responses.
You will need. Basic knowledge of Python syntax and data structures · Familiarity with network concepts such as IP addresses and ports
The full lesson
Level 1 · Beginner: Foundations of request and response communication
At its core, client-server communication relies on two distinct roles operating over a network. The server is a continuously running process that binds to a known network address and port, listening passively for incoming connections. The client is an active process that initiates contact whenever it requires data or needs to trigger an action on the server.
The fundamental pattern of interaction is the request-response cycle. First, the client establishes a connection to the listening server address. Second, the client formats an inquiry into a sequence of bytes and transmits it over the wire. Third, the server reads the message, interprets the command, produces an outcome, and writes a response back. Finally, either party terminates the connection or keeps it open for subsequent exchanges.
Consider a basic key-value retrieval service. The server holds an in-memory dictionary containing user data. A client connects, transmits the string message GET alice, and awaits the outcome. The server parses the instruction, locates the entry associated with the key alice, and replies with the corresponding profile string. The client displays the string and closes the socket.
Minimal synchronous client and server communicating over a TCP socket
import socketimport threadingdef run_server(): server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_sock.bind(("127.0.0.1", 65432)) server_sock.listen(1) conn, addr = server_sock.accept() data = conn.recv(1024).decode("utf-8") store = {"alice": "Active, Admin", "bob": "Inactive, Member"} response = store.get(data.strip(), "Not Found") conn.sendall(response.encode("utf-8")) conn.close() server_sock.close()def run_client(): client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_sock.connect(("127.0.0.1", 65432)) client_sock.sendall(b"alice") response = client_sock.recv(1024).decode("utf-8") client_sock.close() return responseif __name__ == "__main__": t = threading.Thread(target=run_server) t.start() result = run_client() t.join() print("Client received:", result)
Key takeaways
- Servers wait passively for incoming connections, while clients initiate requests.
- A connection requires both an IP address to locate the host and a port number to address the specific process.
- Data sent over raw network sockets must be serialized into bytes before transmission and deserialized upon receipt.
Level 2 · Intermediate: Handling multiple clients, framing, and robust state management
Real-world servers cannot block indefinitely on a single client connection. When one client connects, a basic synchronous server fails to accept others until that single interaction finishes. To support multiple simultaneous clients, servers delegate each accepted connection to separate threads, asynchronous event loops, or worker subprocesses.
A primary challenge in stream-oriented protocols like TCP is message framing. Stream sockets deliver continuous byte sequences without inherent message boundaries; two messages sent in quick succession may arrive joined together, or a single message may arrive in arbitrary fragments. Production systems implement protocols such as length-prefix framing or delimiter-based termination to reconstruct discrete application messages.
Server state can be classified as stateful or stateless. In a stateful architecture, the server retains ongoing context between distinct requests from the same client, such as an open session or temporary checkout cart. In a stateless architecture, each request must carry all context necessary for processing, enabling any server instance in a cluster to handle any incoming request interchangeably.
Threaded server implementing length-prefixed protocol framing and robust error handling
import socketimport structimport threadingclass LengthPrefixedServer: def __init__(self, host: str = "127.0.0.1", port: int = 9000): self.host = host self.port = port self.running = False self.sock = None def start(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.host, self.port)) self.sock.listen(128) self.running = True while self.running: try: conn, addr = self.sock.accept() client_thread = threading.Thread(target=self._handle_client, args=(conn, addr), daemon=True) client_thread.start() except OSError: break def _recv_exact(self, conn: socket.socket, num_bytes: int) -> bytes: buffer = bytearray() while len(buffer) < num_bytes: chunk = conn.recv(num_bytes - len(buffer)) if not chunk: raise ConnectionError("Client disconnected unexpectedly") buffer.extend(chunk) return bytes(buffer) def _handle_client(self, conn: socket.socket, addr): try: while True: header = self._recv_exact(conn, 4) msg_len = struct.unpack("!I", header)[0] payload = self._recv_exact(conn, msg_len).decode("utf-8") response_payload = f"ACK: {payload.upper()}".encode("utf-8") response_header = struct.pack("!I", len(response_payload)) conn.sendall(response_header + response_payload) except (ConnectionError, struct.error): pass finally: conn.close() def stop(self): self.running = False if self.sock: self.sock.close()def test_client(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", 9000)) payload = "ping".encode("utf-8") sock.sendall(struct.pack("!I", len(payload)) + payload) length = struct.unpack("!I", sock.recv(4))[0] ack = sock.recv(length).decode("utf-8") sock.close() assert ack == "ACK: PING"if __name__ == "__main__": server = LengthPrefixedServer() srv_thread = threading.Thread(target=server.start, daemon=True) srv_thread.start() test_client() server.stop()
Key takeaways
- Threaded or event-driven workers allow a server to service multiple clients concurrently.
- TCP byte streams lack natural message borders, making explicit framing protocols essential.
- Stateless servers simplify horizontal scaling because no local state is bound to a specific machine.
Level 3 · Advanced: Scaling patterns, reverse proxies, and architecture limits
As client volume exceeds what a single machine can serve, the architecture must evolve from a monolithic server to a multi-tier design. Vertical scaling adds CPU, memory, and network throughput to a single node, but eventually reaches hard hardware cost and performance boundaries. Horizontal scaling deploys multiple homogeneous server replicas behind a reverse proxy or load balancer.
Load balancers distribute inbound client traffic across healthy backends using algorithms such as round-robin, least connections, or consistent hashing of request attributes. Reverse proxies, like NGINX or Envoy, also handle transport-layer security termination, request routing, caching, and rate limiting, insulating application servers from direct client exposure and malicious traffic spikes.
When adopting distributed client-server systems, teams encounter the limits defined by Amdahl's Law and the CAP theorem. As stateless API servers scale horizontally, the underlying bottleneck shifts to shared datastores, consensus coordinators, or network bandwidth. Techniques like distributed read caches, database read replicas, and asynchronous job queues become mandatory to prevent service degradation under extreme contention.
In-memory round-robin load balancer redirecting client requests across a pool of backend servers
import itertoolsfrom typing import List, Dict, Optionalclass BackendNode: def __init__(self, node_id: str, is_healthy: bool = True): self.node_id = node_id self.is_healthy = is_healthy def process_request(self, request: Dict[str, str]) -> Dict[str, str]: return {"status": "200 OK", "node": self.node_id, "data": f"Processed: {request.get('action')}"}class RoundRobinLoadBalancer: def __init__(self, backends: List[BackendNode]): self._backends = backends self._cycle = itertools.cycle(self._backends) def dispatch(self, request: Dict[str, str]) -> Optional[Dict[str, str]]: attempts = 0 max_attempts = len(self._backends) while attempts < max_attempts: backend = next(self._cycle) attempts += 1 if backend.is_healthy: return backend.process_request(request) return {"status": "503 Service Unavailable", "node": "none", "data": "All nodes down"}if __name__ == "__main__": nodes = [BackendNode("server-1"), BackendNode("server-2"), BackendNode("server-3")] lb = RoundRobinLoadBalancer(nodes) for req_id in range(4): res = lb.dispatch({"action": f"fetch_item_{req_id}"}) print(f"Req {req_id} -> Handled by {res['node']}: {res['data']}")
Key takeaways
- Reverse proxies and load balancers decouple client addressing from back-end service topology.
- Horizontal scaling distributes requests across independent server replicas to eliminate single points of failure.
- System throughput ceilings eventually migrate from the compute tier to the shared data tier.
Complexity
- Time: Best: O(1), Average: O(N) or O(1) depending on lookup, Worst: O(N)
- Space: O(C + M) where C is active connections and M is server-side memory
Request processing time depends on the operation performed; hash table lookups take O(1) average time, while scanning unindexed data takes O(N). Memory consumption scales linearly with concurrent open connection buffers O(C) and application storage requirements O(M).
Common mistakes
- Assuming TCP stream receives align one-to-one with individual write calls, leading to corrupted or split messages.
- Failing to close idle or disconnected sockets, which causes operating system file descriptor leaks.
- Storing user session state in server memory in a load-balanced cluster without session stickiness or an external cache.
- Neglecting network timeouts on client requests, causing calling threads to hang permanently during network partitions.
- Over-allocating OS threads per connection instead of using non-blocking I/O event loops for thousands of concurrent sessions.
Practice problems
- Echo Server with Graceful Shutdown (easy). Hint: Catch interrupt signals such as KeyboardInterrupt or SIGINT to close server sockets and existing client connections cleanly.
- Heartbeat Connection Monitor (medium). Hint: Maintain an updated timestamp for each client and sweep connections periodically using a background thread or timer.
- Consistent Hash Load Balancer (hard). Hint: Map both server nodes and client keys to an integer ring using a uniform hashing function such as MD5 or SHA-256.
Summary
Client-server architecture divides computing duties into requesting clients and responding servers. Starting from direct, low-level TCP socket interactions, production systems incorporate multi-threading, explicit message framing, stateless API contracts, and horizontal load balancing to deliver reliable, high-throughput distributed software.
Finish the Prove step above to complete this lesson.
System Design Roadmap: From Beginner to Intermediate Architecture · 5 of 21
Was this helpful?
Comments (0)
Sign in or create an account to join the conversation.
- No comments yet. Be the first!