Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

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.

Sumit KumarUpdated Oct 11, 20264 min readSystem Design
Vertical vs Horizontal Scaling and the CAP Theorem

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 scaling adds CPU and RAM to one server while horizontal scaling adds more servers behind a load balancer; CAP theorem triangle of consistency, availability and partition tolerance
Vertical (scale up)Horizontal (scale out)
HowMore CPU, RAM, faster disks on one machineMore machines sharing the load
Code changesUsually noneApp must be stateless or distributed-aware
LimitHardware ceiling; cost rises steeplyNearly unlimited
FailureSingle point of failureSurvives individual node failures
Downtime to scaleOften a restartAdd nodes live
ComplexityLowHigh: load balancing, consistency, coordination
Good forEarly stage, relational databasesWeb/API tiers, large-scale data stores
Scale up first, then out

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.

JavaScript
// 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#

NGINX
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;
    }
}
AlgorithmHow it picks a server
Round robinEach server in turn
Least connectionsThe server with the fewest active connections
IP hash / consistent hashingSame client or key goes to the same server
WeightedBigger servers receive more traffic

3. Caching#

The fastest query is the one you never send to the database. Use the cache-aside pattern:

Python
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 product

Add a CDN for static assets and cacheable responses close to users.

4. Scaling the database#

TechniqueWhat it doesTrade-off
Read replicasCopies of the primary handle read queriesReplication lag: reads may be slightly stale
Sharding (partitioning)Split rows across databases by a shard keyCross-shard queries and transactions get hard
Connection poolingReuse connections (PgBouncer, HikariCP)Needs tuning
DenormalisationStore precomputed data to avoid joinsMust keep copies in sync
Java
// 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 keys

5. 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.

Text
          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.
TypeBehaviour during a partitionExamplesGood for
CPRejects some requests to stay correctZooKeeper, etcd, HBase, MongoDB (majority writes), SpannerPayments, inventory, leader election, config
APStays up, may return stale dataCassandra, DynamoDB (default), CouchDB, RiakShopping carts, feeds, likes, analytics
"CA" isn't a real option for distributed systems

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.

SQL
-- 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#

ModelGuarantee
Strong (linearizable)Reads always see the latest committed write
Read-your-writesA user always sees their own updates
Monotonic readsYou never see older data after seeing newer data
EventualIf 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.