AI Hints
Home›System Design Tutorial›Closer and Bigger
System Design · Lesson 33 of 120

Autoscaling

More servers on demand.

⏱ 2 min read▶ Video at 37:55🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

Shoply's traffic isn't flat. It's quiet at night, busy in the evening, and huge on sale days. Paying for sale day servers all year is wasteful. Autoscaling adds and removes servers automatically.

Autoscaling
From the video: Autoscaling
  • Quiet nights
  • Busy sale days
  • Add and remove automatically

A simple scaling rule

An autoscaler follows a rule. Here, the goal is to keep each server's CPU around sixty percent. Every minute, it measures the total load, and works out how many servers that needs. Run it. As traffic climbs through the day, servers are added, and as it drops at night, they're removed.

autoscale.pypython
import math

TARGET = 60          # % CPU per server
MIN_S, MAX_S = 2, 20

load = {"03:00": 70, "09:00": 240, "13:00": 420, "19:00": 900, "23:00": 180}
for hour, total_cpu in load.items():
    need = math.ceil(total_cpu / TARGET)
    servers = max(MIN_S, min(MAX_S, need))
    print(f"{hour}  load {total_cpu:>3}%  -> {servers:>2} servers")
Output
03:00  load  70%  ->  2 servers
09:00  load 240%  ->  4 servers
13:00  load 420%  ->  7 servers
19:00  load 900%  -> 15 servers
23:00  load 180%  ->  3 servers

Autoscaling tips

A few tips. Always set a minimum, so you survive a sudden spike, and a maximum, so a bug can't run up a huge bill. Scale up quickly, but scale down slowly, to avoid flapping. And remember, new servers take a minute or two to start. Autoscaling only works for stateless servers.

keyvalue
Minimumsurvive sudden spikes
Maximumprotect the bill
Up fast, down slowavoid flapping
Stateless onlyany server can join

Summary

Autoscaling adds servers when load is high and removes them when it's low, within limits you set. Next, protecting the system from too many requests.

Key takeaways
  • Target a metric
  • Min and max
  • Stateless servers
Next up: Rate Limiting — protecting the system