Sub topic 2
Horizontal Scaling: More Machines
Horizontal scaling
This chapter assumes you understand client-server architecture, CPU and memory, and the basic roles of web servers and databases.
Horizontal scaling, or scaling out, increases capacity by adding machines or application instances. A request can run on any healthy instance. This approach helps when one server has reached a resource limit or when you need higher availability.
A typical flow looks like this:
Adding machines does not automatically improve performance. The application, network, and data tier must support parallel work.
Spreading requests with a load balancer
A load balancer receives client requests and selects a backend instance. Common policies include round robin, least connections, and weighted routing. It should also run health checks so that failed instances stop receiving traffic.
This small example models round-robin routing:
from itertools import cycle
servers = ["app-1", "app-2", "app-3"]
pool = cycle(servers)
for request_id in range(5):
print(request_id, "->", next(pool))Real load balancers also terminate TLS, enforce connection limits, and sometimes route by URL or tenant.
Keeping application servers stateless
A stateless application server does not keep request-specific state only in its local memory or disk. Any instance can handle the next request. Store sessions in a shared data store, and store uploaded files in shared object storage.
Sticky sessions can send one user to the same instance, but they reduce flexibility and make failures harder to handle. Stateless design usually makes rolling deployments, failover, and autoscaling simpler.
Scaling the data tier
The database often becomes the bottleneck. Read replicas copy data from a primary database and serve read queries. Applications must tolerate replication lag because a replica may briefly contain older data.
Sharding partitions rows across database nodes using a shard key, such as customer ID. Sharding increases write and storage capacity, but cross-shard queries, transactions, and rebalancing become more difficult.
Exercise
Why can adding application servers fail to improve a system?
Show answer
The load balancer may expose a shared bottleneck, such as an overloaded database, network, or external service.