System Design Exercises
Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare with the "Expected" lines. Open the solution only after a real attempt.
| # | Exercise | Topics |
|---|---|---|
| 1 | QPS and storage estimator | Back-of-the-envelope estimation |
| 2 | Availability of a deployment | Serial and parallel availability |
| 3 | Quorum checker | Replication, R + W > N |
| 4 | LRU cache with hit ratio | Caching, eviction |
| 5 | Token bucket limiter | Rate limiting |
| 6 | Consistent hashing ring | Partitioning |
| 7 | Retry with backoff and idempotency | Reliability |
| 8 | Design review checklist | Putting it together |
1. QPS and storage estimator
Write estimate(dau, writes_per_user, reads_per_user, bytes_per_write, years) that returns average write QPS, average read QPS and total storage in TB (1 TB = 10^12 bytes, 86,400 s per day, 365 days per year). Print them rounded as shown.
Expected for a social app with 10 M DAU, 2 writes and 100 reads per user, 1 KB per write, 3 years:
writes 231/s, reads 11574/s, storage 21.9 TB
def estimate(dau, writes_per_user, reads_per_user, bytes_per_write, years):
# TODO: compute the three numbers
return 0, 0, 0.0
w, r, tb = estimate(10_000_000, 2, 100, 1_000, 3)
print(f"writes {w:.0f}/s, reads {r:.0f}/s, storage {tb:.1f} TB")writes 0/s, reads 0/s, storage 0.0 TB
Show solution
def estimate(dau, writes_per_user, reads_per_user, bytes_per_write, years):
write_qps = dau * writes_per_user / 86_400
read_qps = dau * reads_per_user / 86_400
storage_tb = dau * writes_per_user * bytes_per_write * 365 * years / 1e12
return write_qps, read_qps, storage_tb
w, r, tb = estimate(10_000_000, 2, 100, 1_000, 3)
print(f"writes {w:.0f}/s, reads {r:.0f}/s, storage {tb:.1f} TB")
# writes 231/s, reads 11574/s, storage 21.9 TB2. Availability of a deployment
A request passes through a load balancer tier, an app tier and a database tier in series. Each tier has several identical replicas in parallel. Write tier(a, n) (availability of n parallel replicas of availability a) and system(tiers) (product over tiers).
Expected: single replicas: 99.2017% and redundant: 99.9995%.
def tier(a, n):
return a # TODO: n parallel replicas
def system(tiers):
return 1.0 # TODO: multiply the tiers
single = system([tier(0.999, 1), tier(0.995, 1), tier(0.998, 1)])
redundant = system([tier(0.999, 2), tier(0.995, 3), tier(0.998, 2)])
print(f"single replicas: {single:.4%}")
print(f"redundant: {redundant:.4%}")single replicas: 100.0000%
redundant: 100.0000%
Show solution
from math import prod
def tier(a, n):
return 1 - (1 - a) ** n
def system(tiers):
return prod(tiers)
single = system([tier(0.999, 1), tier(0.995, 1), tier(0.998, 1)])
redundant = system([tier(0.999, 2), tier(0.995, 3), tier(0.998, 2)])
print(f"single replicas: {single:.4%}") # 99.2017%
print(f"redundant: {redundant:.4%}") # 99.9995%3. Quorum checker
For a leaderless store with N replicas, write describe(n, w, r) that returns a string saying whether reads are guaranteed to see the latest write (R + W > N), and how many nodes may be down for writes (N - W) and for reads (N - R) to still succeed.
Expected:
N=3 W=2 R=2: strong reads, writes survive 1 down, reads survive 1 down
N=3 W=1 R=1: may read stale, writes survive 2 down, reads survive 2 down
N=5 W=4 R=2: strong reads, writes survive 1 down, reads survive 3 downdef describe(n, w, r):
# TODO
return f"N={n} W={w} R={r}: ?"
for n, w, r in [(3, 2, 2), (3, 1, 1), (5, 4, 2)]:
print(describe(n, w, r))N=3 W=2 R=2: ?
N=3 W=1 R=1: ?
N=5 W=4 R=2: ?
Show solution
def describe(n, w, r):
reads = "strong reads" if r + w > n else "may read stale"
return f"N={n} W={w} R={r}: {reads}, writes survive {n - w} down, reads survive {n - r} down"
for n, w, r in [(3, 2, 2), (3, 1, 1), (5, 4, 2)]:
print(describe(n, w, r))4. LRU cache with hit ratio
Complete the LRUCache so that get returns None on a miss and counts hits and misses, and put evicts the least recently used key when full. Use collections.OrderedDict.
Expected: hits 1, misses 7, keys ['b', 'c', 'a']. (Only one hit! Trace it by hand to see why: this access pattern cycles through four keys with room for three, the worst case for LRU.)
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity, self.items = capacity, OrderedDict()
self.hits = self.misses = 0
def get(self, key):
# TODO: count hits/misses, move hits to the end
return None
def put(self, key, value):
# TODO: insert/update and evict the oldest when over capacity
pass
cache = LRUCache(3)
for key in ["a", "b", "c", "a", "d", "b", "c", "a"]:
if cache.get(key) is None:
cache.put(key, key.upper())
print(f"hits {cache.hits}, misses {cache.misses}, keys {list(cache.items)}")hits 0, misses 0, keys []
Show solution
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity, self.items = capacity, OrderedDict()
self.hits = self.misses = 0
def get(self, key):
if key not in self.items:
self.misses += 1
return None
self.hits += 1
self.items.move_to_end(key)
return self.items[key]
def put(self, key, value):
self.items[key] = value
self.items.move_to_end(key)
if len(self.items) > self.capacity:
self.items.popitem(last=False)
cache = LRUCache(3)
for key in ["a", "b", "c", "a", "d", "b", "c", "a"]:
if cache.get(key) is None:
cache.put(key, key.upper())
print(f"hits {cache.hits}, misses {cache.misses}, keys {list(cache.items)}")Trace: a, b, c miss; a hits; d misses and evicts b; b misses and evicts c; c misses and evicts a; a misses and evicts d. A cache one slot bigger would have hit on b, c and a.
5. Token bucket limiter
Implement TokenBucket(capacity, rate) with allow(now): refill rate tokens per second since the last call (never above capacity), then take one token if available.
Expected: allowed: [0, 0.1, 0.2, 1.5, 3.0, 3.1].
class TokenBucket:
def __init__(self, capacity, rate):
self.capacity, self.rate = capacity, rate
self.tokens, self.last = capacity, 0.0
def allow(self, now):
# TODO: refill, then try to take a token
return True
bucket = TokenBucket(capacity=3, rate=1)
times = [0, 0.1, 0.2, 0.3, 0.9, 1.5, 1.6, 3.0, 3.1, 3.2]
print("allowed:", [t for t in times if bucket.allow(t)])allowed: [0, 0.1, 0.2, 0.3, 0.9, 1.5, 1.6, 3.0, 3.1, 3.2]
Show solution
class TokenBucket:
def __init__(self, capacity, rate):
self.capacity, self.rate = capacity, rate
self.tokens, self.last = capacity, 0.0
def allow(self, now):
self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
bucket = TokenBucket(capacity=3, rate=1)
times = [0, 0.1, 0.2, 0.3, 0.9, 1.5, 1.6, 3.0, 3.1, 3.2]
print("allowed:", [t for t in times if bucket.allow(t)])
# allowed: [0, 0.1, 0.2, 1.5, 3.0, 3.1]6. Consistent hashing ring
Build a ring where each node has vnodes points at md5(f"{node}#{i}"). node_for(key) returns the first point clockwise from md5(key) (wrapping around). Then count how many of 10,000 keys move when n4 joins a ring of n1-n3 with 100 virtual nodes each.
Expected: moved 27.1%, all to n4: True: every moved key moves to n4, and the share is close to the ideal 25%.
import bisect
import hashlib
def h(s):
return int(hashlib.md5(s.encode()).hexdigest(), 16)
class Ring:
def __init__(self, nodes, vnodes=100):
self.points = [] # TODO: sorted (hash, node) pairs
self.hashes = []
def node_for(self, key):
return "n1" # TODO: bisect + wrap around
keys = [f"key-{i}" for i in range(10_000)]
old, new = Ring(["n1", "n2", "n3"]), Ring(["n1", "n2", "n3", "n4"])
moved = [k for k in keys if old.node_for(k) != new.node_for(k)]
print(f"moved {len(moved) / len(keys):.1%}, all to n4: {all(new.node_for(k) == 'n4' for k in moved)}")moved 0.0%, all to n4: True
Show solution
import bisect
import hashlib
def h(s):
return int(hashlib.md5(s.encode()).hexdigest(), 16)
class Ring:
def __init__(self, nodes, vnodes=100):
self.points = sorted((h(f"{n}#{i}"), n) for n in nodes for i in range(vnodes))
self.hashes = [p for p, _ in self.points]
def node_for(self, key):
i = bisect.bisect_right(self.hashes, h(key)) % len(self.points)
return self.points[i][1]
keys = [f"key-{i}" for i in range(10_000)]
old, new = Ring(["n1", "n2", "n3"]), Ring(["n1", "n2", "n3", "n4"])
moved = [k for k in keys if old.node_for(k) != new.node_for(k)]
print(f"moved {len(moved) / len(keys):.1%}, all to n4: {all(new.node_for(k) == 'n4' for k in moved)}")7. Retry with backoff and idempotency
flaky_charge(key, attempt) charges the card and then, on the first two attempts, loses the response (a timeout). Write charge_with_retries(key) that retries up to 5 times with backoff delays 100 * 2**attempt ms (attempt starting at 0), and make flaky_charge idempotent: if the key was already processed, return the stored result without charging again.
Expected: ok after 2 attempts, waited 100 ms, charges: 1. The second attempt finds the stored result of the first one, so the customer is charged exactly once.
charges = []
processed = {}
def flaky_charge(key, attempt):
# TODO: if key was already processed, return the stored result without charging again
charges.append(key)
processed[key] = "ok"
if attempt < 2:
raise TimeoutError("response lost")
return "ok"
def charge_with_retries(key):
waited = 0
# TODO: retry with backoff
return flaky_charge(key, 0), 1, waited
try:
result, attempts, waited = charge_with_retries("order-1")
print(f"{result} after {attempts} attempts, waited {waited} ms, charges: {len(charges)}")
except TimeoutError as e:
print("failed:", e, "| charges:", len(charges))failed: response lost | charges: 1
Show solution
charges = []
processed = {}
def flaky_charge(key, attempt):
if key in processed:
return processed[key]
charges.append(key)
processed[key] = "ok"
if attempt < 2:
raise TimeoutError("response lost")
return "ok"
def charge_with_retries(key, max_attempts=5):
waited = 0
for attempt in range(max_attempts):
try:
return flaky_charge(key, attempt), attempt + 1, waited
except TimeoutError:
waited += 100 * 2 ** attempt
raise TimeoutError("gave up")
result, attempts, waited = charge_with_retries("order-1")
print(f"{result} after {attempts} attempts, waited {waited} ms, charges: {len(charges)}")8. Design review checklist
Given a design as a dictionary of components with replica counts, write review(design) that prints a warning for every single point of failure (replicas < 2), and for every datastore without a backup ("backup": False).
Expected:
WARN load-balancer: single point of failure
WARN postgres: single point of failure
WARN redis: no backup (ok for a pure cache?)
2 SPOFs, 1 missing backupsdesign = {
"load-balancer": {"replicas": 1},
"api": {"replicas": 4},
"postgres": {"replicas": 1, "datastore": True, "backup": True},
"redis": {"replicas": 2, "datastore": True, "backup": False},
"s3": {"replicas": 3, "datastore": True, "backup": True},
}
def review(design):
spofs = backups = 0
# TODO: loop over components and print warnings
print(f"{spofs} SPOFs, {backups} missing backups")
review(design)0 SPOFs, 0 missing backups
Show solution
def review(design):
spofs = backups = 0
for name, c in design.items():
if c["replicas"] < 2:
spofs += 1
print(f"WARN {name}: single point of failure")
if c.get("datastore") and not c.get("backup"):
backups += 1
print(f"WARN {name}: no backup (ok for a pure cache?)")
print(f"{spofs} SPOFs, {backups} missing backups")
review(design)Test yourself
An app has 5 million DAU, each making 20 requests per day. Roughly what is the average QPS?
- About 12
- About 116
- About 1,160
- About 11,600
Which change removes a single point of failure?
- Doubling the RAM of the only database server
- Adding a second load balancer with failover
- Adding an index
- Increasing the cache TTL