Reliability, Resiliency and Security (System Design #17)
Two failure stories. In the first, a database replica dies at 2 a.m.; the system fails over automatically and nobody notices. In the second, one slow dependency causes a thread pool to fill, then the whole service to stall, then its callers, then theirs — a cascade that takes down everything and takes forty minutes to recover. Both are failures. The difference is resiliency: the system’s ability to absorb a fault and keep going.
This chapter covers the patterns that make failure boring, and then the patterns that keep attackers out. They belong together because both are about assuming something will go wrong and designing so it does not become an incident.
Reliability vs resiliency
- Reliability — the probability the system works correctly over time (the inverse of failure rate). Chapter 5’s availability is reliability under a target.
- Resiliency — the ability to recover from, and keep working through, failures. A resilient system degrades gracefully instead of collapsing.
The key mental shift: stop designing for “no failures” and design for “failures are normal”. Disks fail, networks partition, instances die, dependencies slow down. A reliable system assumes this and isolates the damage.
Isolation: bulkheads
A bulkhead partitions resources so a failure in one part cannot sink the whole. Like a ship’s watertight compartments: one flooded compartment does not flood the ship.
- Per-tenant resource pools, so one noisy customer cannot exhaust everyone’s connections.
- Separate thread pools per dependency, so one slow downstream does not consume all threads.
- Separate clusters or cells per region/workload.
Without bulkheads, a single shared resource pool lets one failure spread. With them, a failure is contained to one compartment and the rest of the system keeps serving.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.5cm, minimum height=0.68cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=green!12] (p1) at (-3.0,0) {pool A};
\node[b, fill=green!12] (p2) at (-1.2,0) {pool B};
\node[b, fill=red!12] (p3) at (0.6,0) {pool C (failing)};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (-1.2,-0.7) {one bulkhead flooded, the rest keep serving};
\end{tikzpicture}
The circuit breaker
When a dependency starts failing, continuing to call it makes everything worse: callers block, retries pile on, and the failure cascades (the retry storm from Chapter 15). A circuit breaker stops calling a failing dependency for a while, spending one failure instead of thousands.
It has three states:
- Closed — calls flow normally. Count failures.
- Open — too many failures; reject calls immediately (fail fast) without touching the dependency. Start a timer.
- Half-open — after the timer, allow a few trial calls. If they succeed, close; if they fail, open again.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, rounded corners=4pt, minimum width=1.9cm, minimum height=0.75cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[c, fill=green!12] (closed) at (-3.0,0) {closed};
\node[c, fill=red!12] (open) at (0.2,0) {open};
\node[c, fill=orange!16] (half) at (3.2,0) {half-open};
\draw[a] (closed) -- node[above, font=\scriptsize] {failures} (open);
\draw[a] (open) -- node[above, font=\scriptsize] {timeout} (half);
\draw[a] (half) to[bend left=32] node[below, font=\scriptsize] {success} (closed);
\draw[a] (half) to[bend left=32] node[above, font=\scriptsize] {fail} (open);
\end{tikzpicture}
class Breaker:
def __init__(self, threshold=5, reset_s=30):
self.failures, self.state, self.opened_at = 0, "closed", 0
self.threshold, self.reset_s = threshold, reset_s
def call(self, fn):
import time
if self.state == "open":
if time.time() - self.opened_at < self.reset_s:
raise RuntimeError("circuit open: failing fast")
self.state = "half-open"
try:
result = fn()
self.failures, self.state = 0, "closed" # success -> heal
return result
except Exception:
self.failures += 1
if self.failures >= self.threshold:
self.state, self.opened_at = "open", time.time()
raise
The important detail: when open, the breaker fails fast rather than waiting for a timeout. That frees the caller’s resources and gives the dependency room to recover.
Other resiliency patterns
- Retry (with backoff + jitter). Recover transient failures without amplifying them (Chapter 14).
- Compensating Transaction. Undo a completed step when a later step fails, so the system returns to a consistent state (the saga from Chapter 9).
- Throttling / Rate Limiting. Limit how much any client can consume, protecting the system and enforcing fairness. Returns 429 and lets clients back off.
- Health Endpoint Monitoring. A
/healthzendpoint that checks dependencies, used by load balancers and orchestrators to route away from sick instances. - Deployment Stamps / Geodes. Deploy identical, independent copies of the whole stack (per region or per shard) so one stamp’s failure is isolated. Geodes are geographically distributed stamps for latency and disaster recovery.
- Queue-Based Load Leveling. A queue protects a fragile backend by absorbing spikes (Chapter 13).
- Leader Election. One instance coordinates a task, avoiding duplicate work (Chapter 16).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=2.05cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=green!12] (us) at (-3.2,0) {US stamp};
\node[b, fill=green!12] (eu) at (0,0) {EU stamp};
\node[b, fill=red!12] (ap) at (3.2,0) {APAC stamp (degraded)};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-0.7) {isolated deployment stamps: one region's bad day is not everyone's};
\end{tikzpicture}
Security: assume breach
Security for system design is not a checklist at the end; it is a property of the architecture. The guiding principle is defense in depth: assume any single layer can fail, and put controls at every layer. The companion principle is least privilege: every component gets the minimum access it needs.
- Authentication vs authorization. Authn is who are you (login, tokens, OAuth/OIDC). Authz is what may you do (roles, policies, per-resource checks). They are separate and both required.
- Federated identity. Delegate identity to a trusted provider (OAuth2/OIDC, SAML) instead of storing passwords yourself. Users authenticate once; services trust signed tokens.
- Gatekeeper. Put a dedicated component in front of services to validate and sanitize requests (auth, schema, rate limits) so services can assume well-formed, authenticated input.
- Valet key. Grant clients a short-lived, narrowly scoped credential to access one resource directly (e.g. a pre-signed upload URL), avoiding a proxy through your service.
- Encryption. TLS in transit everywhere (including service-to-service); encryption at rest for data stores; secret management for keys and credentials (never in code or config files).
- Input validation and least privilege for data. Validate and bound all input; enforce tenant isolation in every query (the missing tenant filter is a classic breach, Chapters 9 and 12).
- Zero trust. Do not assume the internal network is safe. Authenticate and authorize every call, even between internal services.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.7cm, minimum height=0.66cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=gray!10] (u) at (-4.4,0) {user};
\node[b, fill=blue!10] (waf) at (-2.6,0) {WAF/edge};
\node[b, fill=orange!16] (gate) at (-0.6,0) {gatekeeper};
\node[b, fill=green!12] (svc) at (1.6,0) {service};
\node[b, fill=yellow!22] (db) at (3.6,0) {data};
\draw[a] (u) -- (waf); \draw[a] (waf) -- (gate); \draw[a] (gate) -- (svc); \draw[a] (svc) -- (db);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (-0.4,-0.7) {layered controls; compromise of one layer is not the system};
\end{tikzpicture}
Failure planning: the postmortem mindset
Resiliency is validated, not assumed. Mature teams deliberately inject failure (chaos engineering) to find weak points before users do:
- Game days — take down a dependency or a zone in production (or staging) and watch the system react.
- Blameless postmortems — after every incident, document the timeline, contributing causes, and the systemic fix. The goal is learning, not blame.
- Runbooks — written recovery steps for known failure modes, so 3 a.m. recovery does not depend on one person’s memory.
An incident that produces a permanent systemic improvement is a success. An incident that is “fixed” by restarting a service and forgotten will recur.
Pitfalls
- Retries without a breaker. The retry storm kills the dependency. Add a circuit breaker.
- No bulkheads. One slow dependency consumes all shared threads/connections and takes down everything.
- Failing slowly. An open circuit must fail fast; waiting on timeouts ties up callers.
- Trusting the internal network. Flat networks let one compromised service reach everything. Use zero trust and least privilege.
- No encryption or secret management. Keys in code or unencrypted traffic are breaches waiting to be found.
- No failure drills. Untested failover and recovery logic does not work when it matters. Practice.
What are the three states of a circuit breaker, and why does it fail fast? What does defense in depth assume?
ASolution
Closed (calls pass, failures counted), open (calls rejected immediately while a timer runs), and half-open (a few trial calls decide whether to heal). Failing fast avoids tying up the caller’s resources on a dependency that is known to be down. Defense in depth assumes any single control can fail, so it places independent controls at every layer and grants least privilege.
Next: Capstone: Design a System End-to-End (System Design #18) — putting all seventeen chapters to work.