Vertical vs Horizontal Scaling and the CAP Theorem
Learn how systems scale: vertical vs horizontal scaling, stateless services, load balancing, caching, database replication and sharding, plus the CAP theorem, PACELC and consistency models explained with examples.
Your app has gone from 1,000 to 1,000,000 users and the server is struggling. There are two basic ways to grow: make the machine bigger (vertical scaling) or add more machines (horizontal scaling). The moment you go horizontal, you're building a distributed system, and the CAP theorem starts to matter.
Vertical vs horizontal scaling#
| Vertical (scale up) | Horizontal (scale out) | |
|---|---|---|
| How | More CPU, RAM, faster disks on one machine | More machines sharing the load |
| Code changes | Usually none | App must be stateless or distributed-aware |
| Limit | Hardware ceiling; cost rises steeply | Nearly unlimited |
| Failure | Single point of failure | Survives individual node failures |
| Downtime to scale | Often a restart | Add nodes live |
| Complexity | Low | High: load balancing, consistency, coordination |
| Good for | Early stage, relational databases | Web/API tiers, large-scale data stores |
A single modern server with 64 cores and 512 GB RAM can handle a surprising amount. Vertical scaling buys time cheaply; move to horizontal scaling when you hit real limits or need high availability.
Building blocks of horizontal scaling#
1. Stateless application servers#
If a server stores session data in memory, the next request must return to the same server. Move state to a shared store so any instance can serve any request.
// Express: sessions in Redis instead of process memory
import session from "express-session";
import { RedisStore } from "connect-redis";
import { createClient } from "redis";
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
app.use(session({
store: new RedisStore({ client: redis }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
}));2. Load balancers#
upstream api {
least_conn; # or round-robin (default), ip_hash
server 10.0.0.11:8080;
server 10.0.0.12:8080;
server 10.0.0.13:8080 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
location / {
proxy_pass http://api;
}
}| Algorithm | How it picks a server |
|---|---|
| Round robin | Each server in turn |
| Least connections | The server with the fewest active connections |
| IP hash / consistent hashing | Same client or key goes to the same server |
| Weighted | Bigger servers receive more traffic |
3. Caching#
The fastest query is the one you never send to the database. Use the cache-aside pattern:
def get_product(product_id):
key = f"product:{product_id}"
cached = redis.get(key)
if cached:
return json.loads(cached) # cache hit
product = db.query("SELECT * FROM products WHERE id = %s", product_id)
redis.setex(key, 300, json.dumps(product)) # cache for 5 minutes
return productAdd a CDN for static assets and cacheable responses close to users.
4. Scaling the database#
| Technique | What it does | Trade-off |
|---|---|---|
| Read replicas | Copies of the primary handle read queries | Replication lag: reads may be slightly stale |
| Sharding (partitioning) | Split rows across databases by a shard key | Cross-shard queries and transactions get hard |
| Connection pooling | Reuse connections (PgBouncer, HikariCP) | Needs tuning |
| Denormalisation | Store precomputed data to avoid joins | Must keep copies in sync |
// Simple hash-based shard routing
int shardFor(long userId, int shardCount) {
return (int) Math.floorMod(Long.hashCode(userId), shardCount);
}
// Prefer consistent hashing so adding a shard moves only ~1/N of keys5. Asynchronous processing#
Push slow work onto a queue and let workers scale independently; see message queues: Kafka vs RabbitMQ.
The CAP theorem#
In a distributed data store, when a network partition splits nodes so they can't talk to each other, you must choose between:
- Consistency (C): every read returns the most recent write (or an error).
- Availability (A): every request gets a non-error response, even if it might be stale.
- Partition tolerance (P): the system keeps working despite lost messages between nodes.
Networks will partition, so P isn't optional. The real choice is CP or AP during a partition.
Node A ✕───network partition───✕ Node B
Client writes x=2 to A. Another client reads x from B.
CP choice: B refuses (error/timeout) until it can confirm the latest value.
AP choice: B answers x=1 (stale), and the nodes reconcile later.| Type | Behaviour during a partition | Examples | Good for |
|---|---|---|---|
| CP | Rejects some requests to stay correct | ZooKeeper, etcd, HBase, MongoDB (majority writes), Spanner | Payments, inventory, leader election, config |
| AP | Stays up, may return stale data | Cassandra, DynamoDB (default), CouchDB, Riak | Shopping carts, feeds, likes, analytics |
A single-node database is "CA" only because it can't partition. As soon as data is replicated across a network, you have to decide what happens when that network fails.
Beyond CAP: PACELC#
CAP only describes behaviour during partitions. PACELC adds: if Partitioned, choose A or C; Else, choose Latency or Consistency. Even when everything is healthy, waiting for replicas to confirm a write adds latency. DynamoDB and Cassandra are PA/EL; Spanner is PC/EC.
Tunable consistency with quorums#
Systems like Cassandra let you pick per query. With N replicas, write to W and read from R; if R + W > N, reads overlap with the latest write.
-- Cassandra, replication factor 3
CONSISTENCY QUORUM; -- 2 of 3 replicas for both reads and writes → 2 + 2 > 3
SELECT * FROM carts WHERE user_id = 42;Consistency models at a glance#
| Model | Guarantee |
|---|---|
| Strong (linearizable) | Reads always see the latest committed write |
| Read-your-writes | A user always sees their own updates |
| Monotonic reads | You never see older data after seeing newer data |
| Eventual | If writes stop, all replicas converge over time |
For the database side of this trade-off see SQL vs NoSQL and ACID transactions. For how all of these combine in a real design, read designing a URL shortener.
Key takeaways#
- Vertical scaling makes one machine bigger; horizontal scaling adds machines and removes the single point of failure.
- Horizontal scaling needs stateless services, load balancers, caching and a scalable data layer.
- Databases scale with read replicas, sharding (ideally with consistent hashing), pooling and caching.
- The CAP theorem says that during a network partition a distributed store must choose consistency or availability.
- PACELC adds the latency vs consistency trade-off that exists even without partitions; quorums let you tune it.