A system is scalable if it can handle growing load (more users, requests or data) by adding resources, with performance staying acceptable and cost growing roughly in proportion. You can scale up (a bigger machine) or out (more machines), and scaling out only works smoothly when servers are stateless. This lesson follows a system from a single server to millions of users, then covers database scaling, autoscaling, finding bottlenecks and the scale cube.
Think of it like
A growing coffee shop
When the line gets long, you can buy a faster espresso machine (vertical scaling), but there is a limit to how fast one machine and one barista can go. Or you can add more baristas and machines (horizontal scaling), which works only if any barista can serve any customer: orders must be written on the cup, not remembered by one person (statelessness). Eventually you open more branches (regions), split roles into cashier and baristas (services), and give each branch its own stock (sharding).
Performance problem or scalability problem?
If the system is slow for a single user, you have a performance problem: fix the algorithm, the query or the index. If it is fast for one user but slow under load, you have a scalability problem: some resource saturates as demand grows. Scalability is always relative to a load parameter, such as requests per second, concurrent connections, data volume or the read/write ratio, so name the one that matters.
Vertical vs horizontal scaling
Vertical (scale up)
- Bigger machine: more CPU, RAM, faster disks
- No code changes; no distributed-systems problems
- Hard ceiling: the largest instance available
- Cost grows faster than capacity at the high end
- Still a single point of failure; upgrades often need downtime
Horizontal (scale out)
- More machines behind a load balancer
- Near-linear capacity growth with commodity hardware
- Redundancy: one machine failing is routine
- Requires stateless services or partitioned data
- Adds coordination, consistency and operational complexity
Statelessness: the key to scaling out
A server is stateless if it keeps nothing between requests that another server would need: no in-memory sessions, no local file uploads, no per-user caches that must be consistent. Then any request can go to any server, the load balancer can use any algorithm, servers can be added or killed at will, and a crash loses nothing.
| State | Where it should live instead |
|---|---|
| User sessions and carts | A shared store such as Redis, or a signed token (JWT) on the client. See Authentication & Security. |
| Uploaded files | Blob & Object Storage such as S3, never the server's local disk |
| Cached data | A shared cache cluster; local caches only for data that tolerates staleness |
| Background job state | A queue or database, so any worker can pick up the job |
| Rate-limit counters | A shared store, so limits hold across servers. See Rate Limiting. |
From one server to millions of users
Real systems grow in stages, and each stage fixes the bottleneck the previous one hit. The user counts are rough and depend heavily on the workload. Play with the simulation above to watch each change relieve one bottleneck and expose the next.
- 1
One server
Web app, database and files on a single machine. Perfect for a prototype; any failure is total downtime.
- 2
Separate the database
Move the database to its own machine so web and data tiers can be sized and scaled independently.
- 3
Load balancer plus several web servers
Make the web tier stateless (sessions in Redis), put a load balancer in front, and run at least two servers for redundancy. See Load Balancing.
- 4
Database replication
Add read replicas: writes go to the primary, reads spread across replicas. Also gives failover if the primary dies. See Database Replication.
- 5
Cache
Put Redis or Memcached in front of the database for hot reads; often cuts database load by an order of magnitude. See Caching.
- 6
CDN
Serve images, scripts and video from edge locations near users. See Content Delivery Networks.
- 7
Queues and async workers
Move slow work (emails, thumbnails, fan-out) off the request path onto a queue processed by an independently scaled worker pool. See Message Queues & Pub/Sub.
- 8
Autoscaling and multiple availability zones
Add and remove web servers automatically with load, spread across zones so one data center failure is survivable.
- 9
Shard the database
When writes or data volume outgrow one primary, partition data across many databases by a shard key. See Sharding & Partitioning.
- 10
Split services and go multi-region
Decompose by function so teams and components scale independently, and serve users from several regions. See Monoliths vs Microservices.
Scaling the database
Stateless tiers scale by cloning. Data does not, because copies must stay consistent and some operations need all the data in one place. That is why the database is usually the hardest part to scale, and why the options below each come with a trade-off.
| Technique | Scales | Cost / trade-off |
|---|---|---|
| Vertical scaling | Everything, up to a limit | Expensive at the top end; still one machine |
| Read replicas (Database Replication) | Reads, plus failover | Replication lag; writes still hit one primary |
| Caching (Caching) | Hot reads | Invalidation and staleness; cold-start stampedes |
| Sharding (Sharding & Partitioning) | Writes and storage | Cross-shard queries and transactions, rebalancing, hot keys |
| Functional partitioning | Separate databases per domain (users, orders) | No joins across domains; distributed transactions |
| Denormalization | Read-heavy queries | Duplicate data to keep in sync on every write |
| Different store for the job (SQL vs NoSQL Databases) | Specific access patterns | Another system to operate; weaker transactions in many NoSQL stores |
Autoscaling
Autoscaling adds or removes instances automatically based on a metric. It turns horizontal scaling from a manual chore into a control loop, and saves money by shrinking capacity at night. It only works for stateless tiers, or ones that can rebalance work quickly.
- Pick the right signal: CPU for compute-bound web servers, request rate or latency for I/O-bound ones, queue depth for workers, connection count for WebSocket gateways.
- Target tracking ("keep average CPU at 60%") is simpler and more stable than hand-written step rules.
- Leave headroom: new instances take minutes to boot and warm caches. Scale before saturation, not at it.
- Scale in slowly: use a cooldown or stabilization window so brief dips do not cause flapping, and drain connections before terminating.
- Know the predictable peaks: use scheduled or predictive scaling for daily cycles and planned events.
- Set a maximum: a runaway bug or attack should not scale you into a giant bill, or into exhausting your database's connection limit.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 3 # never fewer than 3: survive a zone failure
maxReplicas: 50 # cap cost and downstream load
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
behavior:
scaleDown:
stabilizationWindowSeconds: 300 # wait 5 min before shrinkingFinding bottlenecks
- 1
Measure under realistic load
Load-test with production-like data and traffic mix. Guessing where the bottleneck is fails surprisingly often.
- 2
Check every resource with USE
For each resource (CPU, memory, disk, network, connection pools, locks), look at Utilization, Saturation (queueing) and Errors. See Observability.
- 3
Find the constraint
The first resource to saturate caps the whole system. Common culprits: database CPU or locks, connection pool size, a single-threaded component, a hot key, network egress.
- 4
Relieve it and repeat
Fix that one bottleneck (index, cache, more replicas, batching), then measure again. The bottleneck always moves somewhere else.
The scale cube
The Art of Scalability describes three independent ways to scale an application, drawn as the axes of a cube. Large systems use all three.
| Axis | Idea | Example | Solves | Costs |
|---|---|---|---|---|
| X: horizontal duplication | Run N identical copies behind a load balancer | 20 identical web servers | Request volume | Needs statelessness; data tier still shared |
| Y: functional decomposition | Split by function or service | Separate user, order and search services | Code and team scale, independent scaling | Network calls, distributed failures, data ownership |
| Z: data partitioning | Each copy handles a subset of the data | Shard users by user_id, or route by region | Data volume and write throughput | Routing, cross-partition queries, rebalancing |
Implementation
Sessions live in Redis keyed by a random ID in a cookie, so any server instance can handle any request and a crashed server loses nothing.
import json
import os
import uuid
import redis
from flask import Flask, jsonify, make_response, request
app = Flask(__name__)
store = redis.Redis.from_url(os.environ.get("REDIS_URL", "redis://localhost:6379"))
SESSION_TTL_SECONDS = 60 * 60 * 24
def load_session() -> tuple[str, dict]:
sid = request.cookies.get("sid")
raw = store.get(f"session:{sid}") if sid else None
return (sid, json.loads(raw)) if sid and raw else (str(uuid.uuid4()), {})
@app.post("/cart/items")
def add_item():
sid, session = load_session()
session.setdefault("cart", []).append(request.get_json()["sku"])
store.set(f"session:{sid}", json.dumps(session), ex=SESSION_TTL_SECONDS)
# HOSTNAME differs per instance: watch requests land on different servers
resp = make_response(jsonify(cart=session["cart"], served_by=os.environ.get("HOSTNAME")))
resp.set_cookie("sid", sid, max_age=SESSION_TTL_SECONDS, httponly=True, secure=True, samesite="Lax")
return respKey takeaways
- Scalability means handling more load by adding resources; always name the load parameter (QPS, data size, connections).
- Scale up for simplicity until you hit a ceiling; scale out for capacity and redundancy.
- Horizontal scaling requires stateless servers: move sessions, files and counters into shared stores.
- Systems evolve in stages: separate DB, load balancer, replicas, cache, CDN, queues, autoscaling, sharding, services, regions.
- The data tier is the hardest to scale: replicas and caches scale reads, sharding scales writes and storage.
- Find the real bottleneck by measuring; serial fractions and coordination limit how far adding machines helps (Amdahl's law).
Common pitfalls
- Keeping sessions or uploads on local server memory or disk, which breaks as soon as there are two servers.
- Scaling the web tier while the single database is the actual bottleneck.
- Jumping to sharding or microservices before simpler options (indexes, caching, replicas, a bigger box) are exhausted.
- Autoscaling on the wrong metric (CPU for I/O-bound services) or without a maximum.
- Reading from asynchronous replicas right after a write and showing users stale data.
Interview tips
- Present scaling as an evolution driven by numbers from your estimate, not a list of components.
- Say "stateless" explicitly and explain where state lives instead.
- Use the scale cube vocabulary (X, Y and Z axes) to organize your answer when asked how to scale further.
Real-world applications
- Growing a startup from one VM to a multi-region deployment.
- Handling seasonal peaks (Black Friday, ticket launches) with autoscaling.
- Planning database capacity: when to add replicas, caches or shards.
Test yourself
Why must web servers be stateless to scale horizontally with a simple load balancer?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.