15. Reliability, Security & Observability

Big picture: A reliable system assumes things will break and plans for it โ€” like airplanes with redundant hydraulics. Security controls who gets in and what they can do. Observability is the cockpit dashboard: without it, you're flying blind.


Learning goals

After this chapter you should be able to:

  • Adopt a "everything fails" mindset in every design
  • Apply redundancy, timeouts, retries, circuit breakers, and graceful degradation
  • Explain RPO/RTO and basic backup/disaster recovery
  • Place rate limiting and basic authn/authz in an HLD
  • Describe logs, metrics, and traces โ€” and when to use each
  • Define an SLO and connect it to user-visible pain
  • Write a "Failure modes" and "Security" section in a design doc

Prerequisites: 07-load-balancing.md, 09-replication-sharding.md, 14-monolith-microservices.md


Everyday analogy: airplane redundancy

Commercial airplanes are designed knowing components fail:

Airplane ideaSystem design equivalent
Two (or three) hydraulic systemsMulti-AZ deployment, redundant instances
Cockpit alarmsAlerting on SLO breaches
Checklists before takeoffHealth checks, readiness probes
Pilots trained for engine-outRunbooks, game days, chaos testing
Black box recorderLogs, traces, audit trails
Oxygen masks drop before pilot speechGraceful degradation โ€” core survival first

No one says "engines never fail, so one is enough." Your API's dependency on a flaky recommendation service shouldn't crash checkout.


Reliability mindset

Reliability = the system works correctly even when parts break.

Everything fails eventually:

  • Disks corrupt
  • Networks partition
  • Deploys introduce bugs
  • Dependencies (Stripe, S3, DNS) have outages
  • Traffic spikes overwhelm capacity

Design for a loop:

PhaseQuestionExample
DetectHow do we know it's broken?Error rate alert, health check fails
MitigateHow do we limit damage?Circuit breaker, serve cached feed
RecoverHow do we return to healthy?Failover to replica, rollback deploy
LearnHow do we prevent repeat?Postmortem, add retry budget, fix root cause

High availability patterns

Redundancy

Never run one of anything that matters in production.

Bad:  1 app server, 1 DB instance
Good: 3+ app servers behind LB, DB with standby replica in another AZ
LayerRedundancy pattern
App serversN instances across AZs behind load balancer
DatabasePrimary + synchronous/async replica, automatic failover
CacheRedis Cluster or replica with sentinel
Object storageBuilt-in (S3 replicates across AZs)
DNSMultiple NS records, health-checked endpoints

Analogy: Two engines on a plane โ€” either alone can land safely.

Health checks + auto replacement

Load balancers ping /health every few seconds. Unhealthy instances stop receiving traffic; orchestrator (Kubernetes, ASG) replaces them.

GET /health โ†’ 200 { "db": "ok", "cache": "ok" }
GET /health โ†’ 503 { "db": "timeout" }  โ†’ removed from rotation

Timeouts

Never wait forever for a dependency.

Without timeoutWith timeout (e.g., 2s)
Thread blocked indefinitelyThread freed; return error or fallback
Retry storms amplify outageFail fast; circuit breaker opens
User sees spinning loaderUser sees error or degraded response in 2s
HTTP client config:
  connect_timeout: 500ms
  read_timeout: 2000ms

Golden rule: Set timeouts shorter than client-facing timeouts. If the user waits 5s max, internal calls should fail at 2s to leave room for retries/fallbacks.

Retries with exponential backoff

Transient failures (blip, TCP reset) often succeed on retry.

attempt 1: fail โ†’ wait 100ms
attempt 2: fail โ†’ wait 200ms
attempt 3: fail โ†’ wait 400ms
attempt 4: fail โ†’ give up, return error
Retry safely whenDon't retry when
GET (idempotent read)Non-idempotent POST without idempotency key
Transient 503/timeout400 Bad Request (client error)
Idempotent PUT with same bodyPayment already charged

Add jitter (random ยฑ20%) so all clients don't retry in sync ("thundering herd").

Go deeper: 16. Retries, Timeouts & Resilience โ€” backoff formulas, idempotency + retry, retry budgets, hedging, and a full checkout walkthrough.

Circuit breaker

Stop calling a dependency that is clearly sick.

StateBehavior
ClosedNormal calls
OpenFail immediately (fast fallback); don't hammer sick service
Half-openAllow one probe request to test recovery

Analogy: Breaker switch trips when wiring overheats โ€” stops damage until electrician checks.

Bulkhead

Isolate resource pools so one slow dependency doesn't exhaust all threads.

Thread pool for payments: 50 threads
Thread pool for recommendations: 20 threads
โ†’ Slow recommendations can't starve payments

Kubernetes: separate deployments. JVM: separate connection pools.

Graceful degradation

When non-critical parts fail, core features still work.

FailureDegraded behaviorCore preserved
Recommendation service downFeed without "Suggested for you"User still sees friends' posts
Analytics pipeline laggingSkip real-time view countsRedirects still work
Cache downRead from DB (slower)Data still correct
CDN miss stormHigher origin latencyContent still loads

Interview phrase:

"Recommendations are best-effort. If the service times out after 200ms, we render the feed without that block."


Backups & disaster recovery

Key terms

TermMeaningExample
RPO (Recovery Point Objective)Max data loss acceptable"Lose at most 5 minutes of writes"
RTO (Recovery Time Objective)Max downtime acceptable"Back online within 1 hour"
BackupPoint-in-time copy of dataNightly DB snapshot + WAL archiving
FailoverSwitch to standby when primary diesPromote read replica to primary
Multi-AZSame region, multiple data centersSurvives one AZ fire
Multi-regionCopies in distant regionsSurvives entire region outage

When to use what

RequirementPatternCost/complexity
Survive server crashMulti-instance + auto-restartLow
Survive AZ failureMulti-AZ DB, LB across AZsMedium
Survive region disasterMulti-region active-passive or active-activeHigh
Accidental delete recoveryBackups + PITR (point-in-time restore)Medium

Beginner rule: Multi-AZ for most production apps. Multi-region only when business truly requires it (global SLA, regulatory, massive scale).

Restore drills

Backups you never tested are wishful thinking. Schedule quarterly restore to staging.


Rate limiting & abuse protection

Public APIs attract bots, scrapers, accidental infinite loops, and DDoS.

Common strategies

StrategyHowUse
Fixed window100 req/min per IPSimple, edge-friendly
Token bucketBurst allowed, steady rate over timeAPIs with burst tolerance
Sliding windowSmoother than fixed windowFairer limiting
Per-user limitsBy API key / user IDPrevent one account abusing
Per-endpoint limitsStricter on POST /urls vs GET /r/:codeProtect expensive writes

Response when limited

HTTP/1.1 429 Too Many Requests
Retry-After: 60
X-RateLimit-Remaining: 0

Where to enforce: Edge (Cloudflare), API gateway, or app middleware โ€” often layered.


Security basics for HLD/LLD

Security is not a separate chapter at the end โ€” weave it into every design.

Authentication vs authorization

TermQuestionMechanisms
Authn (authentication)Who are you?Login/password, OAuth (Google), JWT, session cookie, API keys
Authz (authorization)What may you do?RBAC (roles), ACLs, resource ownership checks
Authn: JWT says user_id=42
Authz: Can user 42 DELETE /posts/99? โ†’ only if owner or admin

Analogy: Authn = showing ID at building entrance. Authz = your badge only opens certain doors.

Go deeper: 17. Authentication & Authorization โ€” sessions vs JWT, OAuth/OIDC flows, RBAC + ownership, gateway placement, and service-to-service auth.

Security checklist for designs

ControlHLD mentionExample
TLS everywhereClient โ†’ LB โ†’ internalHTTPS only; no plaintext passwords
Secrets managementNot in gitAWS Secrets Manager, Vault
Input validationSize limits, schemaMax 10 MB upload; reject SQL in fields
Least privilege IAMS3/DB credentials scopedApp can write uploads/ only, not delete bucket
Encryption at restSensitive PII, health dataDB encryption, S3 SSE
Encryption in transitTLS + mTLS for service-to-service (at scale)gRPC with certs
Audit logsAdmin actions, paymentsImmutable log: who refunded order X
Signed URLsPrivate mediaShort-lived CDN URLs after authz
CORS / CSRFWeb appsSameSite cookies, CSRF tokens

Common security mistakes

MistakeFix
Secrets in GitHub repoSecrets manager, rotate keys
Public S3 bucketPrivate + signed URLs
Trust client-sent user_idDerive identity from validated token server-side
No rate limits on loginBrute-force protection, CAPTCHA
Logging full credit card numbersPCI violation; log last 4 digits only

Observability: logs, metrics, traces

You cannot operate what you cannot see. Observability answers: "Why is it slow/broken for user 42's request?"

The three pillars

PillarWhat it isBest forExample
LogsDiscrete events with contextDebugging specific failuresERROR order_id=abc payment declined code=insufficient_funds
MetricsAggregated numbers over timeTrends, alerting, capacityredirect_latency_p99 = 45ms, error_rate = 0.1%
TracesRequest journey across servicesLatency breakdown in microservicesSpan: API 120ms โ†’ Payment 80ms โ†’ DB 15ms

Logs โ€” structured beats printf

{
  "level": "info",
  "msg": "redirect",
  "short_code": "aZ9kQ2",
  "latency_ms": 12,
  "cache_hit": true,
  "request_id": "req-uuid-123"
}

Correlate with request_id across services.

Metrics โ€” the four golden signals

From Google SRE:

SignalMeasuresAlert example
LatencyTime to serve requestp99 > 500ms for 5 min
TrafficDemand (QPS, bandwidth)Capacity planning
ErrorsFailed requests5xx rate > 1%
SaturationHow full resources areCPU > 80%, DB connections maxed

Plus USE for resources: Utilization, Saturation, Errors.

Traces โ€” follow one request

Trace id: abc123
โ”œโ”€ span: API Gateway        12ms
โ”œโ”€ span: URL Service        85ms
โ”‚  โ”œโ”€ span: Redis GET       2ms  (cache hit)
โ”‚  โ””โ”€ span: enqueue click   3ms
โ””โ”€ total: 97ms

Tools: Jaeger, Zipkin, Datadog APM, AWS X-Ray.

When critical: Microservices with 5+ hops. Monoliths benefit too but logs may suffice early.

Dashboards vs alerts

DashboardsAlerts
Human explores trendsWakes engineer on-call
"What's normal?""Users are hurting NOW"

Alert on symptoms (error rate, SLO burn), not only causes (CPU 90% โ€” might be fine).


SLOs, SLAs, and error budgets

TermDefinition
SLI (Indicator)Measurable aspect of service
SLO (Objective)Target for SLI
SLA (Agreement)Contract with customers
Error budgetAllowed unreliability

Example SLO for URL shortener

SLI: proportion of GET /r/:code returning 302 within 100ms
SLO: 99.9% over 30-day rolling window
Error budget: 0.1% โ‰ˆ 43 minutes of bad minutes/month

When budget is burned:

  • Stop shipping risky features
  • Focus on reliability work
  • Improve tests, canaries, rollback

Interview tip: Mention one SLO tied to user experience, not "CPU under 70%."


Putting it together in a design doc

Strong designs end with explicit failure and security sections.

Example: social feed service

Failure modes:
- Redis cache down     โ†’ read Postgres directly; latency +50ms; alert ops
- Recommendation timeout โ†’ omit recommendations block; core feed loads
- Primary DB failure   โ†’ automatic failover to replica; ~30s blip
- Queue backlog        โ†’ notifications delayed; post creation unaffected

Security:
- Auth: OAuth + JWT on all write APIs
- Authz: users edit only own posts; admin role for moderation
- Rate limit: 100 posts/hour/user; 1000 req/min/IP at edge
- Media: private bucket; CloudFront signed URLs after ownership check
- Secrets: DB creds in Vault; rotated quarterly

Observability:
- Metrics: feed_load_latency p50/p99, cache_hit_ratio, error_rate
- Logs: structured JSON with request_id, user_id
- Traces: feed read path across Feed + User + Recommendation services
- SLO: 99.5% feed loads < 500ms
- Alerts: 5xx > 0.5% for 5 min pages on-call

Pattern reference table

PatternProblem solvedOne-line description
RedundancySingle point of failureRun Nโ‰ฅ2 instances
Health checksRouting to dead nodesLB probes /health
TimeoutsHung threadsFail at 2s, not โˆž
Retries + backoffTransient blipsRetry 3x with increasing delay
Circuit breakerCascading failureStop calling sick dependency
BulkheadResource exhaustionIsolate thread pools
Graceful degradationPartial outageCore works without extras
Rate limitingAbuse / overload429 after threshold
Idempotency keysSafe retries on writesSame key โ†’ same result
Dead-letter queuePoison messagesFailed jobs go to DLQ for inspection

Common mistakes

MistakeConsequenceFix
No timeoutsCascading outageTimeout every outbound call
Unlimited retriesAmplify failureCap retries; exponential backoff
Alert on everythingAlert fatigueSLO-based alerts
Logs without request_idCan't trace user issuePropagate correlation ID
Security as afterthoughtBreachAuthn/authz in HLD from start
Multi-region "because scale"Cost, complexityMulti-AZ first; region when required
Monitoring only CPUMiss user painGolden signals + SLOs

Check your understanding (Q&A)

1. What is graceful degradation?

Answer

When non-essential components fail, the system continues delivering core functionality with reduced features rather than complete failure. Example: show feed without recommendations when the recommendation service is down.

2. Why are timeouts as important as retries?

Answer

Without timeouts, threads block forever waiting for dead dependencies. Retries on hung calls multiply blocked threads and can amplify an outage. Timeouts fail fast, freeing resources for fallbacks and preventing retry storms.

3. Name the three observability pillars.

Answer

Logs (discrete events), metrics (aggregated numbers over time), traces (end-to-end request paths across services).

4. What's the difference between authn and authz?

Answer

Authentication (authn) verifies identity โ€” who you are (login, JWT). Authorization (authz) verifies permissions โ€” what you're allowed to do (owner can delete post; stranger cannot).

5. When does a circuit breaker open?

Answer

When failure rate (or consecutive failures) exceeds a threshold. While open, calls fail immediately without hitting the sick dependency. After a cooldown, a probe request tests half-open state.

6. What are RPO and RTO?

Answer

RPO (Recovery Point Objective): maximum acceptable data loss measured in time (e.g., 5 minutes of writes). RTO (Recovery Time Objective): maximum acceptable downtime to restore service (e.g., 1 hour).

7. Why alert on error rate instead of only CPU?

Answer

CPU can be high while users are happy, or low while errors spike (e.g., dependency timeout). Symptom-based alerts (errors, latency SLO breaches) reflect user pain directly.

8. How does rate limiting help reliability?

Answer

It protects the system from overload โ€” accidental loops, scrapers, DDoS โ€” by rejecting excess requests with 429. This preserves capacity for legitimate users and prevents cascade failures from resource exhaustion.


Quick reference card

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  ASSUME FAILURE โ†’ detect, mitigate, recover                   โ”‚
โ”‚  TIMEOUTS + RETRIES + CIRCUIT BREAKERS on every dependency    โ”‚
โ”‚  DEGRADE gracefully โ€” core path first                         โ”‚
โ”‚  AUTHN (who) + AUTHZ (what) + TLS + secrets + least privilege โ”‚
โ”‚  OBSERVE: logs (why this request), metrics (trends), traces   โ”‚
โ”‚  SLO: user-visible target โ†’ alert when error budget burns     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Next: 16. Retries, Timeouts & Resilience โ€” deep dive on timeouts, backoff, circuit breakers, and bulkheads.