Sub topic 11
Deep dive into the riskiest component
This chapter assumes you can produce a high-level design from requirements and capacity estimates, as covered in earlier chapters. You should also be comfortable with caches, replicas, and partitioned databases, and with reading short Python snippets.
A high-level diagram shows that a design is plausible. It does not show that the design works. The deep dive is where you pick the one or two components most likely to fail the requirements and examine them until you can say how they behave under load and failure.
Why one component, not all of them
You have limited time and attention, whether the design is for an interview, a design review, or a planning document. Spreading it evenly across every box produces a shallow treatment of everything. A deep dive concentrates it where a wrong decision costs the most.
Two mistakes are common:
- Picking the component you know best instead of the riskiest one. A familiar cache layer is comfortable to discuss, but it may not be where the design breaks.
- Treating every box as equally uncertain. Some boxes, such as a load balancer or object storage, are well-understood products with predictable limits. They rarely need a deep dive.
Choose the riskiest component
Risk is a product of how likely a component is to fail the requirements and how bad the failure would be. Use these filters to find candidates.
- Closest to its limit. Compare each component's peak load from your capacity estimate with what one instance can do. The component with the smallest margin is a candidate.
- Holds state. Stateless services scale by adding copies. Databases, caches, and queues hold data, so they need partitioning, replication, and recovery plans.
- On the critical path of the hardest requirement. If the main non-functional requirement is low read latency, the read path deserves more scrutiny than the write path.
- Hard to change later. A partition key or a data model is expensive to change once data exists. A choice of web framework is not.
- Where your assumptions are weakest. If the design only works when the cache hit ratio is 95%, the cache is a risk even if it is simple.
Work from the numbers
Return to the capacity estimate from earlier in the tutorial: about 579 average write QPS, 11,574 average read QPS, and a peak factor of 2. Peak reads are about 23,148 per second. Suppose a single database node can sustain about 5,000 reads per second for this query shape. That limit is an assumption, so state it as one. A cache in front of the database changes the load the database sees. The script below shows how sensitive that is to the cache hit ratio.
PEAK_READ_QPS = 23_148
DB_READ_LIMIT = 5_000
for hit_ratio in (0.95, 0.90, 0.70, 0.50):
db_reads = PEAK_READ_QPS * (1 - hit_ratio)
headroom = DB_READ_LIMIT / db_reads
status = "ok" if headroom >= 1 else "OVERLOADED"
print(f"hit ratio {hit_ratio:.0%}: database sees {db_reads:7.0f} reads/s, "
f"headroom {headroom:4.2f}x {status}")At a 90% hit ratio the database sees about 2,315 reads per second and has roughly 2x headroom. At 70% it sees about 6,944 and is overloaded. This turns a vague worry ("what if the cache is cold?") into a specific finding: the design depends on the hit ratio staying above roughly 78%, and a cache restart or a deploy that flushes keys can push it below that line.
That finding is what the deep dive acts on. You can now ask concrete questions. How do we warm the cache before sending traffic? Do we need request coalescing so one missing key triggers one database read, not thousands? Should the database have read replicas as a backstop?
Look at four angles
For the chosen component, walk through the same four angles each time. A fixed checklist keeps you from only examining what is easy to think about.
Load and data distribution
Average load hides imbalance. If you partition by a key, ask whether the keys are evenly used. One celebrity account or one viral item can send a large share of traffic to a single shard. The snippet below uses the hash partitioning function from the building-blocks material and feeds it a skewed workload.
import hashlib
from collections import Counter
def shard_for(key: str, shard_count: int) -> int:
digest = hashlib.md5(key.encode("utf-8")).digest()
return int.from_bytes(digest[:8], "big") % shard_count
requests = ["user:1"] * 5_000 + [f"user:{i}" for i in range(2, 5_002)]
load = Counter(shard_for(key, 4) for key in requests)
for shard in range(4):
print(f"shard {shard}: {load[shard]} requests")There are 10,000 requests and 4 shards, so a perfect split would be 2,500 each. Because 5,000 requests share one key, whichever shard owns user:1 receives at least 5,000, which is at least half the traffic. Hashing spreads distinct keys evenly. It cannot split a single hot key. Mitigations include caching the hot key in front of the shard, replicating that key's data to several nodes, or splitting the key (for example, appending a small random suffix to counters and summing them on read). Each has a cost: extra memory, staleness, or a more complex read path.
Failure behavior
For each dependency of the component, ask what happens when it is slow, down, or returning errors. Slow is often worse than down, because callers wait, hold connections, and exhaust their own pools. Decide on timeouts, retries with backoff and jitter, and what the caller returns when the dependency is unavailable. Retries multiply load on a struggling component, so budget them.
Consistency and correctness
Identify what must be right and what can be slightly wrong. A like counter that is off by a few for a few seconds is acceptable. A payment recorded twice is not. Check for operations that can be retried and so need idempotency (a key that makes a repeated request safe). Check for read-after-write expectations when reads go to replicas, since replicas lag the primary.
Operations and growth
Ask how you would know the component is in trouble: which metrics, alerts, and dashboards. Ask what happens at 10x the load, and what the migration path is. Changing the number of shards with simple modulo hashing remaps most keys, as the shard_for function shows when shard_count changes. Consistent hashing or a directory of key ranges reduces that movement.
Present mitigations with costs
A mitigation without a stated cost is a claim, not a decision. Use a consistent format: problem, option, what it fixes, what it costs.
| Problem | Mitigation | What it fixes | What it costs |
|---|---|---|---|
| Cold cache overloads database | Pre-warm cache, coalesce misses | Load spike after restart | Slower deploys, extra code |
| Hot key on one shard | Cache or replicate the key | Skewed shard load | Staleness, more memory |
| Retries amplify an outage | Backoff with jitter, retry budget | Cascading overload | Some requests fail sooner |
| Replica lag breaks read-after-write | Read own writes from primary | Stale reads for the writer | More load on the primary |
| Modulo sharding remaps keys on resize | Consistent hashing or range directory | Data movement during growth | More complex routing |
Choose the mitigation that addresses the measured risk at the smallest complexity. If a 2x headroom margin is enough for the stated requirements, adding a second cache tier is over-engineering.
Common errors
- Diving into a component before establishing it is the riskiest. State why you chose it, using the numbers or the requirement it threatens.
- Reciting product features. "Kafka is durable and scalable" explains nothing. Explain which property of the component addresses which failure in this design.
- Solving only the average case. Peak load, hot keys, and cold starts are where designs fail.
- Adding mitigations without removing the cause. A cache in front of a slow query hides the problem until the cache misses.
- Stopping at the first fix. After applying a mitigation, check what new failure it introduces. A cache adds invalidation and staleness. Replication adds lag.
- Forgetting to go back. After the deep dive, confirm that the component still meets the requirements and that your changes did not break assumptions elsewhere in the design.
Exercise
Your design has a cache with a 90% hit ratio in front of a database that handles 5,000 reads per second. Peak read traffic is 23,148 requests per second. A deploy restarts the cache and the hit ratio falls to 60% for several minutes. What load does the database see, what happens, and name two mitigations with one cost each.
Show answer
The database sees 23,148 × 0.40 ≈ 9,259 reads per second, which is about 1.85 times its 5,000 limit, so it is overloaded and latency and errors rise. Mitigation 1: pre-warm the cache before routing traffic to it, which costs slower deploys and extra tooling. Mitigation 2: coalesce concurrent misses for the same key so one database read serves many requests, which costs added code and a short wait for callers. Rolling restarts that replace one cache node at a time are a third option, at the cost of a longer deploy.
Exercise
A sharded store uses hash(key) % 4. One key receives 50% of all traffic. Explain why adding more shards does not fix the imbalance, and give one mitigation and its cost.
Show answer
Hashing assigns a given key to exactly one shard, so the hot key's traffic still lands on a single shard no matter how many shards exist. More shards only spread the other keys. One mitigation is to cache the hot key's value in front of the shard, which costs memory and allows stale reads until the entry expires or is invalidated. Replicating the key across several nodes, or splitting it into sub-keys, also works at the cost of more complex reads and writes.