Two different questions
Scalability asks: when load grows, can the system keep its latency and throughput targets by adding resources? Reliability asks: when parts fail, does the system keep meeting its targets, or at least fail in a way that is safe and visible? They pull on the same tools (more machines, more copies of data) but for different reasons, and an interviewer wants to hear which problem each choice solves.
Vertical versus horizontal scaling
- Vertical (a bigger machine): no code change, no distributed-systems problems, lowest latency because everything is in one memory space. Limited by the largest machine you can buy and a single point of failure.
- Horizontal (more machines): near-unbounded capacity and natural redundancy, at the cost of partitioning data, coordinating state, and network hops on every cross-node operation.
Scale vertically until a requirement forces you not to. Trading systems often stay deliberately vertical on the hot path (one process, pinned cores, no network hop inside the decision loop) and scale horizontally only around it, for example by sharding instruments across independent engines.
Stateless services scale horizontally for free: put them behind a load balancer and add copies. State is the hard part: it must be partitioned (sharded), replicated, or both.
Little's law
For any stable system, the average number of requests in flight , the throughput and the average time in the system satisfy
At requests/s with ms average latency, requests are in flight on average. That number sizes thread pools, connection pools and queues; if a database allows 50 connections, the service cannot sustain that load at that latency.
Load balancing and consistent hashing
A load balancer spreads requests over replicas: round-robin for uniform requests, least-connections when request costs vary, and key-based routing when the same key must reach the same node (a cache shard, a per-symbol order book).
Key-based routing with hash(key) % N has a nasty property: changing remaps almost every key, so adding one cache node empties the whole cache. Consistent hashing places nodes (each at many "virtual" points) on a ring and sends each key to the next node clockwise, so adding one node to moves only about of the keys.
import bisect
import hashlib
def h(s: str) -> int:
return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")
def modulo_owner(key: str, n: int) -> int:
return h(key) % n
def ring(n: int, vnodes: int = 100) -> list[tuple[int, int]]:
return sorted((h(f"node{i}#{v}"), i) for i in range(n) for v in range(vnodes))
def ring_owner(key: str, points: list[tuple[int, int]]) -> int:
i = bisect.bisect(points, (h(key), -1)) % len(points)
return points[i][1]
keys = [f"AAPL-{d}" for d in range(100_000)]
mod_moved = sum(modulo_owner(k, 10) != modulo_owner(k, 11) for k in keys)
r10, r11 = ring(10), ring(11)
ring_moved = sum(ring_owner(k, r10) != ring_owner(k, r11) for k in keys)
print(f"modulo hashing: {mod_moved / len(keys):.1%} of keys move")
print(f"consistent hashing: {ring_moved / len(keys):.1%} of keys move")
print(f"ideal: {1 / 11:.1%}")
Output:
modulo hashing: 91.0% of keys move
consistent hashing: 8.9% of keys move
ideal: 9.1%
With modulo hashing a key keeps its owner only if h % 10 == h % 11, which happens for about of keys, so about move.
Caching
A cache trades freshness and memory for latency and back-end load. With hit rate , cache lookup time and back-end time (paid on a miss after the lookup),
With ms and ms: at the mean is ms; at it is ms, and the back end sees a tenth of the load it saw at 90%. Going from 90% to 99% hit rate matters far more than going from 0% to 50%.
The hard parts of caching are invalidation (when the source changes, who evicts the stale entry?), stampedes (a popular key expires and a thousand requests hit the back end at once; fix with request coalescing or staggered expiry) and cold starts (a restarted cache sends full load to a back end sized for 1% of it).
Replication
- Leader–follower: writes go to one leader and stream to followers; reads can go to followers. Synchronous replication waits for a follower before acknowledging, so an acknowledged write survives the leader's loss, at the cost of write latency. Asynchronous replication acknowledges immediately, so a failover can lose the writes still in flight.
- Quorums: with replicas, write to and read from . If , every read set overlaps every write set, so a read sees the latest acknowledged write (for example , , ).
- Replication lag makes followers stale. A user who writes and immediately reads from a follower may not see their own write; route such reads to the leader or track a version.
Failure modes and how to survive them
| Failure | What it looks like | Standard defence |
|---|---|---|
| Crash | Process or machine disappears | Redundant replicas, health checks, automatic failover |
| Slow node (gray failure) | Still answers health checks but at 10× latency | Timeouts, hedged requests, outlier ejection |
| Network partition | Two halves each think the other died | Quorums, fencing tokens so only one leader can write |
| Overload | Queues grow, latency explodes, timeouts trigger retries that add more load | Admission control, load shedding, retries with backoff and jitter, retry budgets |
| Bad deploy or config | Every replica fails the same way at once | Canary releases, gradual rollout, fast rollback |
| Data corruption | Wrong values served confidently | Checksums, validation at boundaries, reconciliation against an independent source |
Redundancy does not help against correlated failures: three replicas running the same bad build fail together. Diversity (staged rollouts, independent data sources, separate availability zones) is what protects against those.
Failover
Active–passive: a standby takes over when the primary's heartbeats stop. Recovery time is detection time plus promotion time, and the danger is split brain: a primary that was only partitioned, not dead, keeps writing. Fencing (the standby revokes the old primary's write access, or every write carries a leader epoch that storage checks) prevents two writers. Active–active: all replicas serve traffic, so there is no promotion delay, but concurrent writes to the same key need conflict resolution or single-owner partitioning.
Two terms to use precisely: RTO (recovery time objective) is how long the service may be down; RPO (recovery point objective) is how much recent data may be lost.
SLOs and error budgets
An SLI is a measured quantity (fraction of requests served successfully under 100 ms). An SLO is the target for it (99.9% over 30 days). The error budget is the allowed shortfall: of 30 days is minutes of full outage, or the equivalent in failed requests. Teams spend the budget on releases and risk; when it is gone, they slow down.
| Availability | Downtime per year | Downtime per 30 days |
|---|---|---|
| 99% | 87.6 hours | 7.2 hours |
| 99.9% | 8.76 hours | 43.2 minutes |
| 99.99% | 52.6 minutes | 4.3 minutes |
Worked example
availability of a request path
An order-entry request passes through a gateway, a risk service and a database, each independently available 99.9% of the time. (a) What is the availability of the path? (b) The database is replaced by an active–passive pair where each node is 99% available and failover is instant. What is the availability of the database tier? (c) The pair uses asynchronous replication with up to 200 ms of lag at 5,000 writes/s. What is the worst-case RPO in writes?
Show solutionHide solution
(a) Serial components multiply. All three must be up:
Unavailability is about , roughly hours a year: three "three nines" components make a path that is barely above two and a half nines. Every component added in series costs availability.
(b) Redundant components multiply their unavailabilities. The tier is down only if both nodes are down:
Two 99% nodes give 99.99%, assuming independent failures and instant, correct failover. Both assumptions are optimistic: shared power, shared software and imperfect failover detection all make the real number lower.
(c) Lag times rate. Up to acknowledged writes may exist only on the failed primary. If losing an acknowledged order is unacceptable, use synchronous replication to at least one standby and accept the extra write latency (one round trip, about 0.5 ms in the same datacentre).
Knowledge check
A service runs at 4,000 requests/s with an average latency of 25 ms. On average, how many requests are in flight?
Knowledge check
A cache shard pool uses hash(key) % N. You add one node to 9. Roughly what fraction of keys now map to a different node, and what fraction would move with consistent hashing?
Knowledge check
During a traffic spike, a service's latency rises, clients time out and retry immediately, and the service collapses. Which change most directly addresses the cause?
Key takeaways
- Scale vertically until a requirement forces horizontal scaling; stateless tiers scale out easily, state needs partitioning and replication.
- Little's law sizes pools and queues.
- Use consistent hashing for key-based routing so adding a node moves about of keys, not almost all of them.
- Cache value comes from the high end of the hit rate; plan for invalidation, stampedes and cold starts.
- Serial availabilities multiply; redundant unavailabilities multiply. Redundancy does not protect against correlated failures.
- State SLOs with numbers, convert them to error budgets, and state RTO and RPO for failover.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).