TExcelTAD
Home › System Design › Scalability

Scalability

A system is scalable if it can handle more load by adding resources, without a redesign. Load can mean more requests per second, more data, more users or more complex queries. There are two basic ways to add resources.

Vertical scaling (scale up) Horizontal scaling (scale out)
How Bigger machine: more CPU, RAM, faster disks More machines of the same size
Code changes Usually none Application must be able to run on many nodes
Limit The largest machine you can buy Coordination overhead, data partitioning
Failure One big box is still one point of failure Losing one node out of 20 costs 5% capacity
Cost curve Gets expensive fast at the high end Roughly linear

Most real systems do both: they scale the database vertically for as long as possible (it's simpler) and scale stateless web servers horizontally from day one.

Statelessness: the key to scaling out

A server is stateless when it keeps no client-specific data between requests: sessions, carts and uploads live in a shared store (cache, database, object store). Then any server can handle any request, and a load balancer can spread traffic freely. Here's the difference in a model:

python · try it yourself
class StatefulServer:
    def __init__(self, name):
        self.name, self.sessions = name, {}

    def handle(self, user, item):
        cart = self.sessions.setdefault(user, [])
        cart.append(item)
        return f"{self.name}: {user}'s cart = {cart}"

shared_store = {}

class StatelessServer:
    def __init__(self, name):
        self.name = name

    def handle(self, user, item):
        cart = shared_store.setdefault(user, [])
        cart.append(item)
        return f"{self.name}: {user}'s cart = {cart}"

print("stateful, round robin:")
servers = [StatefulServer("s1"), StatefulServer("s2")]
for i, item in enumerate(["book", "pen", "lamp"]):
    print(" ", servers[i % 2].handle("ana", item))

print("stateless, round robin:")
servers = [StatelessServer("s1"), StatelessServer("s2")]
for i, item in enumerate(["book", "pen", "lamp"]):
    print(" ", servers[i % 2].handle("ana", item))
stateful, round robin:
  s1: ana's cart = ['book']
  s2: ana's cart = ['pen']
  s1: ana's cart = ['book', 'lamp']
stateless, round robin:
  s1: ana's cart = ['book']
  s2: ana's cart = ['book', 'pen']
  s1: ana's cart = ['book', 'pen', 'lamp']

With stateful servers Ana's cart is split across two machines, and she "loses" items depending on which server answers. "Sticky sessions" (always sending a user to the same server) hide the problem but make scaling and failover harder. Moving state out is the cleaner fix.

Why scaling is never perfectly linear

Doubling servers rarely doubles throughput. Some work is serial (a shared lock, a single primary database), and nodes spend time coordinating. Amdahl's law captures the serial part: if a fraction s of the work cannot be parallelised, the speed-up with n nodes is 1 / (s + (1 - s) / n). The Universal Scalability Law adds a coherence cost k that grows with the number of pairs of nodes, so beyond some point adding nodes makes things slower.

python · try it yourself
def amdahl(n, serial):
    return 1 / (serial + (1 - serial) / n)

def usl(n, contention, coherence):
    return n / (1 + contention * (n - 1) + coherence * n * (n - 1))

print(" nodes  ideal  amdahl(5%)  usl(5%, 0.1%)")
for n in [1, 2, 4, 8, 16, 32, 64, 128]:
    print(f"{n:6} {n:6} {amdahl(n, 0.05):11.1f} {usl(n, 0.05, 0.001):14.1f}")
 nodes  ideal  amdahl(5%)  usl(5%, 0.1%)
     1      1         1.0            1.0
     2      2         1.9            1.9
     4      4         3.5            3.4
     8      8         5.9            5.7
    16     16         9.1            8.0
    32     32        12.5            9.0
    64     64        15.4            7.8
   128    128        17.4            5.4

With just 5% serial work, 128 nodes give only about a 17x speed-up. Add a tiny coherence cost and the curve peaks and then falls: more nodes, less throughput. The design lesson: remove shared bottlenecks (global locks, a single counter, one hot database row) before adding machines.

Finding the bottleneck

Scaling one tier only helps until the next tier saturates. A request usually passes through several tiers, and the cluster's throughput is set by the tier with the least capacity:

python · try it yourself
tiers = {
    # tier: (capacity per node in requests/s, number of nodes)
    "load balancer": (50_000, 2),
    "app servers":   (1_000, 8),
    "cache":         (80_000, 1),
    "database":      (9_000, 1),
}

def capacity(tiers):
    return {name: per_node * nodes for name, (per_node, nodes) in tiers.items()}

caps = capacity(tiers)
for name, cap in caps.items():
    print(f"{name:<14} {cap:>8,} req/s")
bottleneck = min(caps, key=caps.get)
print("bottleneck:", bottleneck, f"({caps[bottleneck]:,} req/s)")

tiers["app servers"] = (1_000, 12)
caps = capacity(tiers)
bottleneck = min(caps, key=caps.get)
print("after adding 4 app servers, bottleneck:", bottleneck, f"({caps[bottleneck]:,} req/s)")
load balancer   100,000 req/s
app servers       8,000 req/s
cache            80,000 req/s
database          9,000 req/s
bottleneck: app servers (8,000 req/s)
after adding 4 app servers, bottleneck: database (9,000 req/s)

Adding app servers moved the bottleneck to the database. The next step would be a cache in front of it (so fewer requests reach it) or read replicas.

Scaling checklist

  1. Make app servers stateless and put them behind a load balancer.
  2. Add a cache for hot reads; add a CDN for static files.
  3. Add read replicas for read-heavy databases.
  4. Move slow work to queues and workers so requests return quickly.
  5. Partition (shard) data once one database primary can't take the writes or the data size.
  6. Split into services when teams, not machines, are the bottleneck.

Note: Scaling down matters too. Autoscaling groups add nodes at peak and remove them at night, which is where much of the cloud's cost saving comes from. That only works with stateless nodes.

Test yourself

Why are stateless application servers easier to scale horizontally?

  1. They use less memory
  2. Any server can handle any request, so a load balancer can spread traffic freely
  3. They don't need a database
  4. They never fail

According to Amdahl's law with 5% serial work, what is the maximum possible speed-up, even with infinite nodes?

  1. 5x
  2. 20x
  3. 95x
  4. Unlimited

In the bottleneck model, what limits throughput after adding app servers?

  1. The load balancer
  2. The cache
  3. The database
  4. Nothing, it scales linearly