Skip to content
LeetQuant
QD10 System Design and Code Review

QD10 · System Design and Code Review · Lesson 2 of 5

Scalability and Reliability

Vertical and horizontal scaling, load balancing and consistent hashing, caching, replication, failure modes and SLOs, with the availability and latency arithmetic interviewers expect you to do on the spot.

20 min

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 LL, the throughput λ\lambda and the average time in the system WW satisfy

L=λW.L = \lambda W.

At 2,0002{,}000 requests/s with 5050 ms average latency, L=2,000×0.05=100L = 2{,}000 \times 0.05 = 100 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 NN 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 NN moves only about 1/(N+1)1/(N+1) 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 1/111/11 of keys, so about 10/11≈91%10/11 \approx 91\% move.

Caching

A cache trades freshness and memory for latency and back-end load. With hit rate pp, cache lookup time tct_c and back-end time tbt_b (paid on a miss after the lookup),

E[latency]=tc+(1−p) tb,back-end load=(1−p)×request rate.\mathbb E[\text{latency}] = t_c + (1 - p)\, t_b, \qquad \text{back-end load} = (1 - p) \times \text{request rate}.

With tc=1t_c = 1 ms and tb=20t_b = 20 ms: at p=0.90p = 0.90 the mean is 1+0.1×20=3.01 + 0.1 \times 20 = 3.0 ms; at p=0.99p = 0.99 it is 1.21.2 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 NN replicas, write to WW and read from RR. If R+W>NR + W > N, every read set overlaps every write set, so a read sees the latest acknowledged write (for example N=3N = 3, W=2W = 2, R=2R = 2).
  • 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

FailureWhat it looks likeStandard defence
CrashProcess or machine disappearsRedundant replicas, health checks, automatic failover
Slow node (gray failure)Still answers health checks but at 10× latencyTimeouts, hedged requests, outlier ejection
Network partitionTwo halves each think the other diedQuorums, fencing tokens so only one leader can write
OverloadQueues grow, latency explodes, timeouts trigger retries that add more loadAdmission control, load shedding, retries with backoff and jitter, retry budgets
Bad deploy or configEvery replica fails the same way at onceCanary releases, gradual rollout, fast rollback
Data corruptionWrong values served confidentlyChecksums, 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: 0.1%0.1\% of 30 days is 43.243.2 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.

AvailabilityDowntime per yearDowntime per 30 days
99%87.6 hours7.2 hours
99.9%8.76 hours43.2 minutes
99.99%52.6 minutes4.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 solution

(a) Serial components multiply. All three must be up:

0.9993=0.997003≈99.70%.0.999^3 = 0.997003 \approx 99.70\%.

Unavailability is about 0.3%0.3\%, roughly 2626 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:

1−(1−0.99)2=1−0.0001=0.9999.1 - (1 - 0.99)^2 = 1 - 0.0001 = 0.9999.

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 0.2×5,000=1,0000.2 \times 5{,}000 = 1{,}000 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 L=λWL = \lambda W sizes pools and queues.
  • Use consistent hashing for key-based routing so adding a node moves about 1/(N+1)1/(N+1) 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).