Scalability
Scalability is not “add more servers”. It is the property that adding resources produces a proportional increase in capacity. Most systems stop scaling because one component is not divisible: a single writer, a single lock, a session in one process’s memory.
The 60-second answer
Section titled “The 60-second answer”Scale vertically first — it is simple and buys time — then horizontally, which requires stateless services so any instance can serve any request. Move sessions to a shared store or a signed token. Find the bottleneck before adding capacity: measure, do not guess. Scale reads with replicas, caches and CDNs; scale writes with partitioning, batching and asynchronous processing, because writes are the hard side. Estimate with QPS, storage and bandwidth, using rough orders of magnitude.
Vertical vs horizontal
Section titled “Vertical vs horizontal”| Vertical (bigger machine) | Horizontal (more machines) | |
|---|---|---|
| Complexity | None; same code | Needs statelessness, discovery, partitioning |
| Ceiling | Hardware limit, often expensive | Effectively unbounded for divisible workloads |
| Failure | One big SPOF | Redundancy built in |
| Cost curve | Superlinear at the top end | Linear until coordination costs appear |
Start vertical. A single modern server with 64 cores, 256GB RAM and NVMe handles an enormous amount of traffic. Move horizontal when you hit a hard ceiling, need redundancy, or need geographic distribution — not because it is architecturally fashionable.
Stateless services
Section titled “Stateless services”A service is horizontally scalable when any instance can serve any request. That requires:
- No user state in process memory.
- No local filesystem dependency for correctness (logs and temp files are fine).
- Config from the environment, not from the machine.
- Background jobs that are safe to run on multiple instances, or run separately.
Statelessness also makes deploys safe: you can kill an instance at any moment and the load balancer routes elsewhere. Stateful services need draining, leader election or sharding.
Sessions
Section titled “Sessions”The classic “why does this not scale” question.
| Approach | How | Trade-off |
|---|---|---|
| In-process memory | Session hash in the app process | Breaks on the second node; loses sessions on deploy |
| Sticky sessions | Load balancer pins a user to a node | Uneven load, breaks on node loss, complicates deploys |
| Shared store | Session id in a cookie, data in Redis | One more dependency, but standard and correct |
| Signed token | All state in a JWT | No lookup, but revocation is hard |
Shared store is the default answer. Sticky sessions are a workaround, not a design.
Finding the bottleneck
Section titled “Finding the bottleneck”A system scales only as well as its least-scalable component. Candidates that name the wrong one add capacity where it does not help and pay for it.
Measure in this order:
- Latency by endpoint and by dependency. Which call dominates the p99?
- Saturation. CPU, memory, disk IOPS, network, connection pool, thread pool, open file descriptors. The first resource to hit 100% is the bottleneck.
- Queueing. Latency rising while CPU is at 60% usually means a saturated pool or a downstream slowdown, not CPU.
- Lock contention and serialisation. A single-row counter, a global mutex, a table-level lock.
Common bottlenecks, in rough order of frequency in interviews:
- The database write path (single primary).
- A hot partition or a single hot key.
- Unbounded result sets and missing indexes.
- Synchronous calls to slow third parties.
- Connection pool exhaustion under high concurrency.
- Chatty service-to-service calls (N+1 across the network).
Scaling reads
Section titled “Scaling reads”- Cache in front of the database, at the layer closest to the reader (browser, CDN, Redis).
- Read replicas for read-heavy workloads. Watch for replication lag: a user who writes and immediately reads may see their own write disappear. Route that read to the primary, or use sticky read-after-write for a short window.
- Denormalise for read patterns: precomputed counters, materialised views, duplicated columns. The cost moves to the write path.
- CDN for anything static or cacheable at the edge.
Scaling writes
Section titled “Scaling writes”This is where designs actually fail.
- Batch and buffer. Group inserts, use
COPY, or accumulate events and flush periodically. - Asynchronously offload non-critical writes (analytics, notifications, audit) to a queue.
- Partition / shard by a key with high cardinality and even access. Choose the shard key for the most common query, and accept that cross-shard queries become expensive.
- Avoid global counters. A single increment hot row serialises everything. Shard the counter into N rows and sum on read, or use a CRDT-like approach.
- Reduce write amplification. Every secondary index is another write. Fewer, better indexes.
The arithmetic you must be able to do
Section titled “The arithmetic you must be able to do”Users: 10M DAUWrites: 5 actions/user/day = 50M/day ≈ 580/s, peak 3× ≈ 1,700/sReads: 20× writes = 1B/day ≈ 11,600/s, peak ≈ 35,000/sRow size: 500 bytesStorage/day: 50M × 0.5KB = 25GB/day ≈ 9TB/yearWith replicas ×3: ≈ 27TB/yearCache: 20% of reads are hot; 35,000 × 0.2 × 0.5KB ≈ 3.5MB/s working set growthThen check the design: 35,000 reads/s from one Postgres primary is not comfortable; with a 95% cache hit rate it is 1,750/s to the database, which is. That is the whole argument for the cache, and it takes one line.
Failure and elasticity
Section titled “Failure and elasticity”Scalability without elasticity is fragile:
- Autoscaling needs a signal (CPU, queue depth, p99 latency) and a cooldown. Queue depth scales consumers better than CPU does.
- Load shedding beats collapse: reject or degrade when saturated rather than timing out everyone. See Rate Limiting.
- Retry storms amplify an outage. Retries need backoff, jitter and a budget.
- Warm-up matters: a new instance with a cold cache and an empty connection pool is slow, so ramp traffic gradually.
Follow-up questions
Section titled “Follow-up questions”- Where does sticky session state break during a rolling deploy?
- Your read replicas lag by two seconds. Which user-visible behaviour breaks?
- You sharded by user id, and now need “top posts in the last hour”. What do you do?
- Which resource saturates first in a JSON API at 10k rps: CPU, sockets, or the database pool?
- How does adding a cache change your capacity plan, and what happens when it fails?
- At what point does adding instances stop helping?
Common traps
Section titled “Common traps”- “Scaling means more servers.” Without statelessness it means more inconsistent servers.
- “We will shard later.” Fine, but the shard key determines your query capabilities. Choose it deliberately now, even if you do not shard yet.
- “Read replicas fix write load.” They do not; they multiply it slightly (replication) and only help reads.
- “Caching makes it consistent.” It trades consistency for speed. Say which one you gave up.
- “Autoscaling solves traffic spikes.” It reacts in minutes; a spike can exhaust a database in seconds. Rate limits and queues absorb what autoscaling cannot.