Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 05 · Distributed Systems & ConsensusChapter 24 of 33
23.
Phase 05Read time ~33 minDifficulty advanced

Distributed Systems Fundamentals

In this chapter
  • 01Introduction
  • 02What Is a Distributed System?
  • 03Centralized vs Distributed
  • 04Centralized
  • 05Distributed
  • 06Why Do We Build Distributed Systems?
  • 07Scalability
  • 08Availability
  • 09Geographic Distribution
  • 10Specialized Components
  • 11The Most Important Mental Model
  • 12Network Is Not Reliable
  • 13Partial Failure
  • 14Failure Detection Is Difficult
  • 15Timeouts
  • 16Timeout Does Not Mean Failure
  • 17Retries
  • 18Exponential Backoff
  • 19Retry Storm
  • 20Jitter
  • 21Cascading Failure
  • 22Defensive Techniques
  • 23Circuit Breaker
  • 24Closed
  • 25Open
  • 26Half-open
  • 27Why Circuit Breakers Help
  • 28Bulkheads
  • 29Load Shedding
  • 30Backpressure
  • 31Nodes
  • 32Network Partitions
  • 33Partition Problem
  • 34Split Brain
  • 35Quorum
  • 36Why Majority Matters
  • 37Replication
  • 38Leader-Based Replication
  • 39Leader Election
  • 40Why Leader Election Is Hard
  • 41Consensus Intuition
  • 42Replication vs Consensus
  • 43Clock Problems
  • 44Why Clock Skew Matters
  • 45Wall Clock vs Monotonic Time
  • 46Logical Clocks
  • 47Causality
  • 48Availability
  • 49Availability Calculation
  • 50Reliability
  • 51Fault Tolerance
  • 52High Availability vs Fault Tolerance
  • 53Scalability
  • 54Latency
  • 55Tail Latency
  • 56The Tail at Scale Problem
  • 57Distributed Locks
  • 58Lock Lease
  • 59Stale Lock Holder
  • 60Fencing Tokens
  • 61Failure Detector Intuition
  • 62Heartbeats
  • 63Health Checks
  • 64Liveness
  • 65Readiness
  • 66Dependency health
  • 67Graceful Degradation
  • 68Fallbacks
  • 69Distributed State
  • 70Strong Consistency
  • 71Eventual Consistency
  • 72Consistency Is a Spectrum
  • 73Availability vs Consistency
  • 74Distributed Transactions
  • 75Exactly-Once Is Difficult
  • 76Distributed System Design Principles
  • 77Expect failure
  • 78Use timeouts
  • 79Make retries safe
  • 80Control retries
  • 81Isolate failures
  • 82Define consistency
  • 83Minimize coordination
  • 84Observe the system
  • 85Coordination Has a Cost
  • 86Distributed System Example — Payment
  • 87Case 1
  • 88Case 2
  • 89Case 3
  • 90Distributed System Example — URL Shortener
  • 91Distributed System Example — Notification
  • 92Failure Matrix
  • 93Failure-Oriented Design
  • 94Recovery
  • 95Disaster Recovery
  • 96RPO
  • 97RTO
  • 98Reliability Budget
  • 99Common Distributed-System Fallacies
  • 100The Network Is Reliable — False
  • 101Latency Is Zero — False
  • 102Bandwidth Is Infinite — False
  • 103The Network Is Secure — False
  • 104Topology Never Changes — False
  • 105One Administrator — False
  • 106Transport Cost Is Zero — False
  • 107The Network Is Homogeneous — False
  • 108Distributed System Trade-Off Triangle
  • 109Synchronous vs Asynchronous
  • 110Stateless vs Stateful
  • 111Why Stateless Services Are Popular
  • 112Distributed Cache Example
  • 113Failure Domains
  • 114Redundancy
  • 115Independence Matters
  • 116Distributed Systems and CAP Preview
  • 117Common Mistakes
  • 118Mistake 1
  • 119Mistake 2
  • 120Mistake 3
  • 121Mistake 4
  • 122Mistake 5
  • 123Mistake 6
  • 124Mistake 7
  • 125Mistake 8
  • 126Mistake 9
  • 127Mistake 10
  • 128Mistake 11
  • 129Mistake 12
  • 130Mistake 13
  • 131Mistake 14
  • 132Interview Framework
  • 133Step 1 — Scale
  • 134Step 2 — State
  • 135Step 3 — Communication
  • 136Step 4 — Failure
  • 137Step 5 — Consistency
  • 138Step 6 — Availability
  • 139Step 7 — Recovery
  • 140Step 8 — Observability
  • 141Interview Question: What Is Partial Failure?
  • 142Interview Question: Why Are Timeouts Important?
  • 143Interview Question: Why Can Retries Be Dangerous?
  • 144Interview Question: What Is Split Brain?
  • 145Interview Question: What Is Quorum?
  • 146Interview Question: Replication vs Consensus
  • 147Interview Question: Why Is Tail Latency Important?
  • 148Mini Project
  • 149Architecture
  • 150Failure Simulation
  • 151Advanced Mini Project
  • 152Production Checklist
  • 153Key Mental Model
  • 154Chapter Summary
  • 155Interview Revision Checklist
  • 156Next Chapter
  • 157Chapter 23 — CAP Theorem
In this chapter (157 sections)
01Introduction02What Is a Distributed System?03Centralized vs Distributed04Centralized05Distributed06Why Do We Build Distributed Systems?07Scalability08Availability09Geographic Distribution10Specialized Components11The Most Important Mental Model12Network Is Not Reliable13Partial Failure14Failure Detection Is Difficult15Timeouts16Timeout Does Not Mean Failure17Retries18Exponential Backoff19Retry Storm20Jitter21Cascading Failure22Defensive Techniques23Circuit Breaker24Closed25Open26Half-open27Why Circuit Breakers Help28Bulkheads29Load Shedding30Backpressure31Nodes32Network Partitions33Partition Problem34Split Brain35Quorum36Why Majority Matters37Replication38Leader-Based Replication39Leader Election40Why Leader Election Is Hard41Consensus Intuition42Replication vs Consensus43Clock Problems44Why Clock Skew Matters45Wall Clock vs Monotonic Time46Logical Clocks47Causality48Availability49Availability Calculation50Reliability51Fault Tolerance52High Availability vs Fault Tolerance53Scalability54Latency55Tail Latency56The Tail at Scale Problem57Distributed Locks58Lock Lease59Stale Lock Holder60Fencing Tokens61Failure Detector Intuition62Heartbeats63Health Checks64Liveness65Readiness66Dependency health67Graceful Degradation68Fallbacks69Distributed State70Strong Consistency71Eventual Consistency72Consistency Is a Spectrum73Availability vs Consistency74Distributed Transactions75Exactly-Once Is Difficult76Distributed System Design Principles77Expect failure78Use timeouts79Make retries safe80Control retries81Isolate failures82Define consistency83Minimize coordination84Observe the system85Coordination Has a Cost86Distributed System Example — Payment87Case 188Case 289Case 390Distributed System Example — URL Shortener91Distributed System Example — Notification92Failure Matrix93Failure-Oriented Design94Recovery95Disaster Recovery96RPO97RTO98Reliability Budget99Common Distributed-System Fallacies100The Network Is Reliable — False101Latency Is Zero — False102Bandwidth Is Infinite — False103The Network Is Secure — False104Topology Never Changes — False105One Administrator — False106Transport Cost Is Zero — False107The Network Is Homogeneous — False108Distributed System Trade-Off Triangle109Synchronous vs Asynchronous110Stateless vs Stateful111Why Stateless Services Are Popular112Distributed Cache Example113Failure Domains114Redundancy115Independence Matters116Distributed Systems and CAP Preview117Common Mistakes118Mistake 1119Mistake 2120Mistake 3121Mistake 4122Mistake 5123Mistake 6124Mistake 7125Mistake 8126Mistake 9127Mistake 10128Mistake 11129Mistake 12130Mistake 13131Mistake 14132Interview Framework133Step 1 — Scale134Step 2 — State135Step 3 — Communication136Step 4 — Failure137Step 5 — Consistency138Step 6 — Availability139Step 7 — Recovery140Step 8 — Observability141Interview Question: What Is Partial Failure?142Interview Question: Why Are Timeouts Important?143Interview Question: Why Can Retries Be Dangerous?144Interview Question: What Is Split Brain?145Interview Question: What Is Quorum?146Interview Question: Replication vs Consensus147Interview Question: Why Is Tail Latency Important?148Mini Project149Architecture150Failure Simulation151Advanced Mini Project152Production Checklist153Key Mental Model154Chapter Summary155Interview Revision Checklist156Next Chapter157Chapter 23 — CAP Theorem

1. Introduction#

A distributed system is a collection of independent computers that work together to provide a larger system.

A simple system might be:

Client
  |
  v
Server

A distributed system might look like:

                Load Balancer
                      |
          +-----------+-----------+
          |           |           |
          v           v           v
       Server A    Server B    Server C
          |           |           |
          +-----------+-----------+
                      |
                Database Cluster

At first glance, this looks like:

More servers = more power.

But distributed systems are difficult because those computers communicate over networks that can fail.

A server can be alive while another server cannot reach it.

A message can be delayed.

A response can be lost even though the operation succeeded.

Two nodes can temporarily disagree about state.

A clock on one machine can differ from another machine's clock.

This chapter builds the foundation needed to reason about these problems.


2. What Is a Distributed System?#

A distributed system is a system in which multiple independent computing nodes cooperate to perform work or provide a shared service.

Examples include:

  • distributed databases
  • cloud applications
  • microservices
  • Kafka clusters
  • Kubernetes clusters
  • CDN networks
  • payment systems
  • search systems
  • distributed caches

A typical architecture:

                Internet
                    |
                    v
              Load Balancer
                    |
        +-----------+-----------+
        |           |           |
        v           v           v
      Node A      Node B      Node C
        |           |           |
        +-----------+-----------+
                    |
              Shared Services

The nodes do not share one CPU or one memory space.

They communicate through networks.

That distinction creates most of the complexity.


3. Centralized vs Distributed#

Centralized#

             Server
            /  |  \
           /   |   \
        Client Client Client

One main server owns the computation/state.

Distributed#

        Node A ←→ Node B
          ↕          ↕
        Node C ←→ Node D

Multiple nodes participate.

Distributed architecture can improve:

  • scalability
  • availability
  • fault tolerance
  • geographic reach
  • throughput

But introduces:

  • network failures
  • coordination problems
  • consistency challenges
  • operational complexity
  • partial failures

4. Why Do We Build Distributed Systems?#

There are several major reasons.

4.1 Scalability#

One server may not handle:

1 million requests/sec

Multiple servers can distribute the load.

4.2 Availability#

If one server fails:

Server A ✗
Server B ✓
Server C ✓

traffic can continue.

4.3 Geographic Distribution#

Users may be located worldwide.

India → India region
Europe → Europe region
US → US region

This can reduce latency.

4.4 Specialized Components#

Different services can specialize:

API
Search
Payments
Notifications
Analytics

5. The Most Important Mental Model#

In a single machine:

function call

is usually fast and predictable.

In a distributed system:

Service A → Network → Service B

has uncertainty.

The network can:

  • delay
  • duplicate
  • reorder
  • drop
  • partially fail
  • disconnect

Therefore:

A remote call is fundamentally different from a local function call.

This is one of the most important system-design principles.


6. Network Is Not Reliable#

Suppose:

Client
  |
  | request
  v
Server

The client sends:

Charge ₹1000

The server processes it successfully.

But the response is lost:

Server → Client
         X

The client sees:

timeout

What does the client know?

It does not know whether:

operation failed

or:

operation succeeded but response was lost

This ambiguity is fundamental.


7. Partial Failure#

A partial failure occurs when some components fail while others continue working.

Example:

Node A ✓
Node B ✓
Node C ✗
Node D ✓

The system as a whole may continue.

This differs from a single-machine failure where the whole process may simply stop.

Distributed systems must reason about:

Who failed?
Who can still communicate?
Who knows who failed?

8. Failure Detection Is Difficult#

Suppose:

Node A → Node B

A sends a request.

No response.

Possible explanations:

  1. B crashed.
  2. B is overloaded.
  3. Network is slow.
  4. Network packet was lost.
  5. B processed the request but response was lost.
  6. A itself has a network problem.

A cannot always distinguish these cases immediately.

Therefore:

A timeout is evidence of uncertainty, not proof that the remote operation never happened.


9. Timeouts#

Every distributed call should have an appropriate timeout.

Without a timeout:

Service A
   |
   v
Service B
   |
   | hangs
   v
Service A waits forever

Threads/connections can accumulate.

With a timeout:

request
   |
   v
wait
   |
 timeout
   v
fallback/error/retry

Timeouts prevent indefinite waiting.


10. Timeout Does Not Mean Failure#

This distinction is extremely important.

Suppose:

Client → Payment Service

Payment processing takes:

5 seconds

Client timeout:

2 seconds

The client sees:

timeout

But the payment may still succeed at:

5 seconds

Therefore:

timeout ≠ operation definitely failed

This is why retrying non-idempotent operations can be dangerous.


11. Retries#

Retries can recover from transient failures.

Example:

Request
   |
   X timeout
   |
   v
Retry
   |
   v
Success

But retries introduce a new problem:

duplicate operations

Example:

Charge ₹1000
   |
   v
payment succeeds
   |
   X response lost
   |
   v
client retries

The payment might happen twice.

Therefore:

retry
+
idempotency

must be considered together.


12. Exponential Backoff#

Never blindly retry immediately:

retry
retry
retry
retry

Instead:

1s
2s
4s
8s
16s

This gives the dependency time to recover.

Use a maximum retry limit.


13. Retry Storm#

Suppose:

10,000 clients

all experience a timeout.

If all retry immediately:

10,000 retries

The already-failing service receives even more traffic.

This can make the failure worse.

This is a retry storm.

Use:

exponential backoff
+
jitter
+
retry limits

14. Jitter#

Jitter adds randomness to retry delays.

Instead of:

all retry at 4 seconds

you may get:

3.7s
4.2s
4.8s
5.1s

This spreads load over time.


15. Cascading Failure#

Consider:

API
 |
 v
Service A
 |
 v
Service B
 |
 v
Database

Database becomes slow.

Then:

Service B slows
      ↓
Service A waits
      ↓
API requests wait
      ↓
connections increase
      ↓
memory increases
      ↓
API becomes unhealthy

One dependency failure can cascade through the system.


16. Defensive Techniques#

Common techniques include:

timeouts
retries
circuit breakers
bulkheads
rate limiting
backpressure
load shedding
caching
fallbacks

These mechanisms protect services from downstream failures.


17. Circuit Breaker#

A circuit breaker monitors failures.

Conceptual states:

CLOSED
   |
many failures
   v
OPEN
   |
wait
   v
HALF-OPEN
   |
success → CLOSED
failure → OPEN

Closed#

Requests flow normally.

Open#

Requests are rejected or failed quickly.

Half-open#

A limited number of test requests are allowed.


18. Why Circuit Breakers Help#

Without one:

Service A
   |
   +→ B
   +→ B
   +→ B
   +→ B

If B is down, A wastes resources repeatedly trying.

With a circuit breaker:

A
|
X
B unavailable

A can fail fast.

This protects resources.


19. Bulkheads#

Bulkheads isolate resources.

Suppose one service has:

100 connection slots

Do not allow one dependency to consume all 100.

Instead:

Payment → 30
Search  → 30
Other   → 40

If Search fails, it cannot consume all resources.

This is analogous to compartments in a ship.


20. Load Shedding#

When the system is overloaded, it may deliberately reject lower-priority work.

Example:

High priority:
payments
 
Low priority:
recommendations

During extreme load:

accept payments
reject/defer recommendations

This preserves critical functionality.


21. Backpressure#

Backpressure means controlling incoming work when processing capacity is limited.

Example:

Producer
   |
   v
Queue
   |
   v
Workers

If workers are overloaded:

slow producer
or
buffer work
or
reject work

Backpressure prevents unbounded resource consumption.


22. Nodes#

A distributed system consists of nodes.

A node may be:

  • virtual machine
  • physical server
  • container
  • pod
  • database replica
  • broker

Example:

Node A
Node B
Node C

Nodes communicate over a network.


23. Network Partitions#

A network partition occurs when groups of nodes cannot communicate.

Example:

Node A ←→ Node B
 
        X
 
Node C ←→ Node D

The nodes may all still be running.

But:

A/B cannot reach C/D

This is different from node failure.


24. Partition Problem#

Suppose all nodes believe they are healthy.

Group 1:

A
B

Group 2:

C
D

If both sides accept writes independently, the system may create conflicting state.

Example:

Account balance
Group 1 → ₹500
Group 2 → ₹300

After connectivity returns:

Which value is correct?

Distributed systems need explicit consistency and conflict-resolution strategies.


25. Split Brain#

Split brain occurs when multiple nodes or groups incorrectly believe they are authoritative.

Example:

Cluster
  |
  +---- Group A → Leader A
  |
  +---- Group B → Leader B

Both leaders may accept writes.

This can corrupt state.

Avoiding split brain is a major reason distributed coordination and quorum mechanisms exist.


26. Quorum#

A quorum is a minimum number of nodes required for an operation or decision.

Suppose:

5 nodes

A majority quorum is:

3

If a decision requires 3 nodes:

A ✓
B ✓
C ✓
D ✗
E ✗

the system can still make progress if its protocol permits it.


27. Why Majority Matters#

Suppose:

N = 5
quorum = 3

Two separate groups cannot both have a majority:

Group A = 3
Group B = 3

because that would require 6 distinct nodes.

Majority overlap helps prevent conflicting decisions.

The exact protocol matters, but this is the intuition behind quorum systems.


28. Replication#

Replication means keeping copies of data or state on multiple nodes.

Example:

Primary
   |
   +---- Replica 1
   |
   +---- Replica 2

Benefits:

  • availability
  • read scaling
  • fault tolerance
  • geographic distribution

Costs:

  • replication lag
  • storage
  • network traffic
  • consistency complexity

29. Leader-Based Replication#

A common model:

        Leader
       /      \
      v        v
 Replica A   Replica B

Writes go to the leader.

Followers replicate.

If leader fails:

Replica A
   |
   v
New Leader

Leader election is then required.


30. Leader Election#

Leader election is the process of choosing one node to coordinate or act as leader.

Conceptually:

Node A
Node B
Node C

One becomes:

Leader

The others become:

Followers

If the leader fails, another eligible node can be elected.


31. Why Leader Election Is Hard#

The cluster needs to answer:

Who is the leader?

while dealing with:

  • network delays
  • node failures
  • partitions
  • stale information
  • simultaneous elections

Two nodes must not incorrectly act as leader at the same time.

This is why consensus algorithms are important.


32. Consensus Intuition#

Consensus means a group of nodes agrees on a value or sequence of decisions despite failures.

Examples of consensus algorithms include:

Raft
Paxos

At this stage, focus on the intuition:

nodes
  ↓
communicate
  ↓
agree
  ↓
commit decision

Consensus is much more than simple replication.


33. Replication vs Consensus#

These are not the same.

Replication:

copy data

Consensus:

agree on authoritative decisions/order

A replicated system may use consensus to decide:

which write is committed
who is leader
what log entry comes next

34. Clock Problems#

Distributed nodes have separate clocks.

Example:

Node A: 10:00:00.100
Node B: 10:00:00.300

They differ by:

200 ms

This is clock skew.

Clock synchronization is never perfectly guaranteed.


35. Why Clock Skew Matters#

Suppose:

Node A says:
event happened at 10:00:01
 
Node B says:
event happened at 09:59:59

Sorting events purely by local timestamps can be incorrect.

This affects:

  • distributed logs
  • TTL
  • leases
  • ordering
  • conflict resolution
  • security tokens

36. Wall Clock vs Monotonic Time#

Wall clock:

2026-10-01 10:00:00

can move forward or backward due to synchronization adjustments.

Monotonic clocks are useful for measuring durations:

start
  |
  v
operation
  |
  v
end
 
duration = end - start

For timeouts and elapsed time, monotonic time is generally safer than relying on wall-clock timestamps.


37. Logical Clocks#

Distributed systems sometimes use logical clocks to reason about event ordering without relying entirely on physical clocks.

One example is:

Lamport clock

Basic idea:

event → logical counter

If A sends a message to B:

A event = 5
B receives → counter becomes at least 6

This can represent causal ordering.


38. Causality#

Suppose:

A creates order
   |
   v
B processes payment
   |
   v
C creates shipment

There is a causal relationship:

OrderCreated
      →
PaymentCompleted
      →
ShipmentCreated

Causality matters when events can arrive out of order.


39. Availability#

Availability describes how often a system is operational and able to serve requests.

Common targets:

99%
99.9%
99.99%
99.999%

Higher availability usually requires more infrastructure and careful failure handling.


40. Availability Calculation#

Conceptually:

Availability =
uptime / total time

For example:

99.9%

means approximately:

0.1%

of the measurement period is unavailable.

Availability targets must be associated with a defined measurement window and service scope.


41. Reliability#

Reliability is broader than availability.

A system can be:

available

but still return incorrect results.

Reliability includes the probability that the system performs its intended function correctly over time.

Examples:

correct payment
correct balance
correct order state

42. Fault Tolerance#

Fault tolerance means the system continues operating correctly despite certain failures.

Example:

3 replicas
 
Replica A ✗
Replica B ✓
Replica C ✓

The service can continue.

Fault tolerance requires knowing:

which failures are tolerated?
how many?
under what assumptions?

43. High Availability vs Fault Tolerance#

High availability:

Keep the service accessible.

Fault tolerance:

Continue correct operation despite specified failures.

They overlap but are not identical.

A system may remain reachable while producing incorrect results, which is not acceptable fault tolerance.


44. Scalability#

Scalability describes how a system handles increased workload.

Horizontal scaling:

1 server
   ↓
10 servers

Vertical scaling:

4 CPU
   ↓
32 CPU

Distributed systems commonly favor horizontal scaling.


45. Latency#

Latency is the time taken for an operation.

Example:

request → response = 100 ms

In distributed systems, latency accumulates across network hops.

Example:

API
 ↓ 20ms
Service A
 ↓ 30ms
Service B
 ↓ 50ms
Database

Total may approach:

100ms+

depending on concurrency and overhead.


46. Tail Latency#

Average latency can hide bad experiences.

Suppose:

99 requests → 50 ms
1 request → 5 seconds

Average may not look terrible.

But the 99th percentile:

P99 ≈ 5 seconds

reveals the problem.

Important metrics include:

P50
P90
P95
P99
P99.9

47. The Tail at Scale Problem#

Suppose one request calls:

10 downstream services

Each service has a small chance of being slow.

The probability that at least one dependency is slow increases.

Therefore fan-out can increase tail latency.

Architecture should minimize unnecessary synchronous fan-out.


48. Distributed Locks#

Sometimes multiple nodes need exclusive access to a resource.

Example:

Job Scheduler

Two workers should not both process the same singleton job.

A distributed lock can coordinate ownership.

Conceptually:

Worker A
   |
   v
Lock
   |
   X
Worker B

Distributed locks are tricky because leases can expire and network partitions can occur.


49. Lock Lease#

A distributed lock may have an expiration.

Example:

lock owner = Worker A
lease = 30 seconds

If Worker A stops renewing:

lease expires

Another worker may acquire the lock.

But this creates a subtle danger.


50. Stale Lock Holder#

Suppose:

Worker A
acquires lock

Then the network isolates A.

The lock expires.

Worker B
acquires lock

Now A may still continue executing.

A thinks it owns lock
B thinks it owns lock

This is why robust distributed locking sometimes requires fencing tokens.


51. Fencing Tokens#

A coordination service can issue increasing tokens:

Worker A → token 10
Worker B → token 11

The protected resource accepts only the newest valid token.

If A continues after its lease expires:

A → token 10 → reject
B → token 11 → accept

This prevents stale owners from performing protected operations.


52. Failure Detector Intuition#

A distributed system often needs to suspect failed nodes.

But remember:

no response

does not prove:

node crashed

The system therefore uses timeouts and health signals to make a best-effort failure suspicion.

False suspicions are possible.


53. Heartbeats#

Nodes may send heartbeats:

A → "I am alive"
B → "I am alive"
C → "I am alive"

If a node stops sending heartbeats:

suspect node

Heartbeats are useful but not proof of global health.

A node may be alive but unable to serve requests.


54. Health Checks#

Different health checks can answer different questions.

Liveness#

Is the process alive?

Readiness#

Can the instance serve traffic?

Dependency health#

Can it reach required dependencies?

Do not blindly restart a healthy application because a temporary downstream dependency is unavailable.


55. Graceful Degradation#

When a dependency fails, return reduced functionality when possible.

Example:

Recommendation Service ✗

Main product page can still work:

Product ✓
Price ✓
Cart ✓
Recommendations unavailable

This is often better than failing the entire request.


56. Fallbacks#

A fallback can use:

cache
default response
stale data
simplified computation

Example:

Recommendation API
      |
      X
      |
      v
Cached recommendations

Fallbacks should be deliberate.

Serving incorrect data can be worse than returning an error.


57. Distributed State#

State may be spread across nodes.

Example:

Node A → state X
Node B → state X
Node C → state X

Keeping replicas consistent is difficult.

Questions include:

Who can write?
Who can read?
When do replicas update?
What if one is unavailable?
What if writes conflict?

58. Strong Consistency#

A strong consistency model aims to make successful reads observe the latest committed state according to the system's consistency definition.

Example:

Write X
   |
   v
Read
   |
   v
X

This can require coordination.


59. Eventual Consistency#

With eventual consistency:

Write X
   |
   +→ Replica A = X
   |
   +→ Replica B = old value

After propagation:

Replica A = X
Replica B = X

Temporary divergence is accepted.


60. Consistency Is a Spectrum#

Real systems may choose different guarantees:

strong
session/read-your-writes
causal
eventual

The exact semantics matter.

Do not simply label a system:

consistent

without specifying what reads are guaranteed to observe.


61. Availability vs Consistency#

During a network partition, a distributed system may have to choose how it behaves.

For some operations:

continue accepting writes

may produce divergent state.

For others:

reject writes

may preserve consistency but reduce availability.

This is the foundation for the CAP theorem, which we will study in depth in Chapter 23.


62. Distributed Transactions#

A transaction across multiple independent systems is difficult.

Example:

Service A DB
Service B DB
Service C DB

A single local transaction cannot normally atomically cover all three.

Approaches include:

  • Saga
  • outbox
  • idempotency
  • compensation
  • consensus-based coordination
  • distributed transaction protocols in specific environments

The right choice depends on requirements.


63. Exactly-Once Is Difficult#

Suppose:

Client → Server

Server performs operation.

Response is lost.

Client retries.

Now the system must determine:

Did the first operation happen?

Without an idempotency mechanism, exactly-once business behavior is difficult.

This is a recurring distributed-systems theme:

Ambiguous outcomes require explicit protocol design.


64. Distributed System Design Principles#

Important principles:

1. Expect failure#

Do not assume nodes are always healthy.

2. Use timeouts#

Never wait forever.

3. Make retries safe#

Use idempotency.

4. Control retries#

Use backoff and jitter.

5. Isolate failures#

Use bulkheads and circuit breakers.

6. Define consistency#

Do not leave it implicit.

7. Minimize coordination#

Coordination adds latency and failure dependencies.

8. Observe the system#

Logs, metrics, traces, events.


65. Coordination Has a Cost#

Suppose every request requires:

A → B
B → C
C → D

The system now depends on all of them.

More coordination means:

more latency
+
more failure points
+
more operational complexity

Asynchronous communication can reduce some dependencies but introduces eventual consistency.

System design is therefore a trade-off.


66. Distributed System Example — Payment#

Consider:

Client
  |
  v
Payment API
  |
  v
Payment Service
  |
  v
Bank

Failure cases:

Case 1#

Bank rejects payment.

Simple failure.

Case 2#

Bank succeeds but response is lost.

Ambiguous result.

Case 3#

Payment API times out but bank is still processing.

Retry could create duplicate payment.

Solution:

idempotency key
+
payment status lookup
+
safe retry

67. Distributed System Example — URL Shortener#

Architecture:

Client
  |
  v
Load Balancer
  |
  +---- App A
  +---- App B
  +---- App C
           |
           v
        Database

Scaling introduces:

shared state

If URL mappings are cached:

App A → Cache
App B → Cache
App C → Cache

cache consistency becomes relevant.

If the database is replicated:

Primary
  |
  +→ Replica A
  +→ Replica B

read-after-write behavior becomes relevant.

One simple application now becomes a distributed system with multiple failure modes.


68. Distributed System Example — Notification#

Notification API
      |
      v
Queue
      |
      +---- Worker A
      +---- Worker B
      +---- Worker C

Failures include:

worker crash
queue delay
provider outage
duplicate message
rate limit

Design:

retry
+
backoff
+
idempotency
+
DLQ
+
provider rate limiting

69. Failure Matrix#

A useful design exercise is to list:

Component Failure Effect Mitigation
API server crash traffic lost load balancing
Database unavailable writes fail replication/failover
Network partition nodes cannot communicate quorum/fallback
Queue unavailable async work delayed durable HA deployment
Worker crash job incomplete retry
External API timeout uncertain result idempotency
Cache failure slower requests DB fallback
Region outage regional traffic lost multi-region

This is a powerful system-design interview technique.


70. Failure-Oriented Design#

Instead of asking only:

How does the system work when everything is healthy?

also ask:

What happens when each component fails?

For every dependency:

What if it is slow?
What if it is unavailable?
What if response is lost?
What if it returns an error?
What if it returns stale data?
What if it recovers?

This mindset separates robust distributed designs from happy-path designs.


71. Recovery#

Failure handling is incomplete without recovery.

Ask:

How does the system return to normal?

Examples:

failed replica
→ rebuild
 
consumer crash
→ restart and resume offset
 
database failure
→ failover
 
network partition
→ reconnect
 
queue backlog
→ scale consumers and drain

Recovery should be part of the design.


72. Disaster Recovery#

Some failures are larger:

entire region unavailable

Possible strategies:

backup
replication
multi-region
warm standby
active-active

Important metrics:

RPO
RTO

We will revisit these in the High Availability and Disaster Recovery chapters.


73. RPO#

Recovery Point Objective answers:

How much data loss can the business tolerate?

Example:

RPO = 5 minutes

means the recovery strategy should aim to lose no more than approximately five minutes of data under the defined disaster scenario.


74. RTO#

Recovery Time Objective answers:

How quickly must the service recover?

Example:

RTO = 30 minutes

means the business requires restoration within approximately 30 minutes for the defined scenario.


75. Reliability Budget#

A service with:

99.99% availability target

has a finite error budget.

The exact allowed downtime depends on the measurement period.

This concept helps teams balance:

feature delivery
vs
reliability work

We will study operational reliability more deeply later.


76. Common Distributed-System Fallacies#

Classic assumptions that often cause problems include:

  1. The network is reliable.
  2. Latency is zero.
  3. Bandwidth is infinite.
  4. The network is secure.
  5. Topology does not change.
  6. There is one administrator.
  7. Transport cost is zero.
  8. The network is homogeneous.

These assumptions are dangerous.


77. The Network Is Reliable — False#

Packets can be:

lost
duplicated
delayed
reordered

Applications need appropriate protocols.


78. Latency Is Zero — False#

Every network hop costs time.

Across regions:

Mumbai → Singapore

is not equivalent to:

process within one machine

Architecture must account for network distance.


79. Bandwidth Is Infinite — False#

Large payloads consume:

network
CPU
memory
storage

Prefer:

compression
caching
CDNs
object storage
pagination
streaming

where appropriate.


80. The Network Is Secure — False#

Traffic can be intercepted or manipulated without proper security controls.

Use:

TLS
authentication
authorization
network isolation
secrets management

81. Topology Never Changes — False#

Cloud systems constantly change:

instances start
instances stop
pods move
IPs change
regions fail
load balancers reroute

Service discovery and dynamic configuration are important.


82. One Administrator — False#

Modern systems involve:

cloud provider
database team
platform team
application team
third-party services

Different components may have different ownership and failure domains.


83. Transport Cost Is Zero — False#

Every byte has a cost in:

latency
bandwidth
CPU
cloud billing

Large-scale system design must consider data movement.


84. The Network Is Homogeneous — False#

Different paths may have different:

latency
bandwidth
packet loss
routing
security
availability

Design for variability.


85. Distributed System Trade-Off Triangle#

When designing a system, repeatedly evaluate:

Consistency
Availability
Latency

Increasing coordination for stronger consistency may increase latency or reduce availability during failures.

Reducing coordination may improve latency and availability but introduce stale data.

There is no universal best configuration.


86. Synchronous vs Asynchronous#

Synchronous:

A → B
wait
response

Good when:

caller needs immediate answer

Asynchronous:

A → queue/event
      |
      v
      B

Good when:

work can happen later

But asynchronous architecture introduces:

eventual consistency

and additional operational complexity.


87. Stateless vs Stateful#

Stateless service:

Request 1 → Server A
Request 2 → Server B

No critical session state exists only in Server A.

This makes horizontal scaling easier.

Stateful systems maintain important state locally or on specific nodes.

They require additional mechanisms for:

  • replication
  • failover
  • ownership
  • recovery

88. Why Stateless Services Are Popular#

Stateless application servers can be:

added
removed
restarted
replaced

without losing important application state.

State is moved to shared systems:

Database
Cache
Object Storage
Queue

This improves horizontal scalability.


89. Distributed Cache Example#

App A ─┐
App B ─┼→ Redis Cluster
App C ─┘

The cache itself becomes distributed.

Now questions appear:

What if Redis node fails?
How is data partitioned?
How is replication handled?
What if cache is unavailable?

Every distributed dependency creates another failure domain.


90. Failure Domains#

A failure domain is a set of resources that can fail together.

Examples:

process
VM
rack
availability zone
region
cloud provider

Good high-availability designs spread replicas across independent failure domains.

Bad:

Replica A → same VM
Replica B → same VM
Replica C → same VM

One VM failure destroys all replicas.

Better:

AZ-A → Replica A
AZ-B → Replica B
AZ-C → Replica C

91. Redundancy#

Redundancy means having additional capacity or copies.

Examples:

3 application servers
3 database replicas
2 network paths
2 regions

But redundancy only helps if components fail independently enough.

Three replicas in one failure domain may not provide three independent failure protections.


92. Independence Matters#

Suppose:

Replica A → AZ-A
Replica B → AZ-A
Replica C → AZ-A

A whole availability-zone failure causes:

A ✗
B ✗
C ✗

Therefore redundancy must consider correlated failures.


93. Distributed Systems and CAP Preview#

CAP theorem will be covered in detail next.

The intuition is:

During a network partition, a distributed system cannot simultaneously guarantee both:

strong consistency

and:

full availability

under the standard CAP model.

The important point is that the network partition is the trigger.

CAP does not simply mean:

pick any two of C, A, P

We will examine the exact meaning in Chapter 23.


94. Common Mistakes#

Mistake 1#

Treating remote calls like local function calls.

Mistake 2#

No timeout.

Mistake 3#

Retrying without idempotency.

Mistake 4#

Retrying immediately.

Mistake 5#

Assuming timeout means operation failed.

Mistake 6#

Ignoring partial failure.

Mistake 7#

Assuming replicas automatically solve consistency.

Mistake 8#

Ignoring network partitions.

Mistake 9#

Using global locks unnecessarily.

Mistake 10#

Ignoring clock skew.

Mistake 11#

Scaling without considering failure domains.

Mistake 12#

Optimizing average latency while ignoring tail latency.

Mistake 13#

Using asynchronous processing without defining consistency expectations.

Mistake 14#

Having redundancy inside one failure domain.


95. Interview Framework#

When designing any distributed system, ask:

Step 1 — Scale#

Requests/sec?
Users?
Data volume?
Peak traffic?

Step 2 — State#

Where is state stored?
Who owns it?

Step 3 — Communication#

HTTP?
gRPC?
Queue?
Events?

Step 4 — Failure#

What if each dependency fails?
What if it becomes slow?
What if response is lost?

Step 5 — Consistency#

Strong?
Eventual?
Read-after-write?
Per-user?
Per-object?

Step 6 — Availability#

Single region?
Multi-AZ?
Multi-region?

Step 7 — Recovery#

Retry?
Failover?
Replay?
Rebuild?
Restore?

Step 8 — Observability#

Metrics?
Logs?
Traces?
Alerts?

96. Interview Question: What Is Partial Failure?#

Partial failure occurs when some components of a distributed system fail while other components continue operating. Because failures are not always globally visible, surviving nodes may have incomplete or stale information about the system's state.


97. Interview Question: Why Are Timeouts Important?#

A timeout prevents a caller from waiting indefinitely for a remote operation. However, a timeout only means the caller did not receive a response within the deadline; it does not prove that the remote operation did not succeed.


98. Interview Question: Why Can Retries Be Dangerous?#

A retry can repeat a business operation whose first attempt may already have succeeded but whose response was lost. Therefore retries should be bounded, use backoff and jitter, and be paired with idempotency for operations where duplicates are dangerous.


99. Interview Question: What Is Split Brain?#

Split brain occurs when multiple nodes or partitions of a distributed system independently believe they are authoritative and both make decisions that should have been made by a single leader or quorum.


100. Interview Question: What Is Quorum?#

A quorum is a sufficient subset of nodes required to make or accept a decision. Majority quorums are useful because two different majorities of the same fixed node set must overlap.


101. Interview Question: Replication vs Consensus#

Replication creates multiple copies of data or state. Consensus provides a protocol for nodes to agree on decisions or an ordered sequence despite certain failures. Replicated systems may use consensus to coordinate leaders and committed state.


102. Interview Question: Why Is Tail Latency Important?#

Averages can hide a small percentage of extremely slow requests. Percentiles such as P95 and P99 show the experience of slower requests and are especially important when a request depends on multiple downstream services.


103. Mini Project#

Build a fault-tolerant distributed API.

Architecture#

                    Client
                      |
                      v
                Load Balancer
                      |
             +--------+--------+
             |        |        |
             v        v        v
           App A    App B    App C
             |        |        |
             +--------+--------+
                      |
                      v
                 Redis Cache
                      |
                      v
                Database

Add:

timeouts
retries
circuit breaker
rate limiting
health checks
metrics
distributed tracing

104. Failure Simulation#

Simulate:

App A crashes
Database becomes slow
Cache becomes unavailable
Network request times out
Database connection pool exhausts
One replica becomes stale
One service returns 500

Observe:

Does the system recover?
Does traffic move?
Does retry amplify load?
Does the user receive a safe response?

105. Advanced Mini Project#

Add:

3 application nodes
3 database replicas
leader election
health checks
automatic failover
distributed lock
idempotent requests
request tracing

Then simulate a network partition:

Node A/B
 
   X
 
Node C

Study what happens when nodes cannot communicate.

Do not attempt to implement a production consensus algorithm from scratch as a first exercise; focus first on understanding the failure model and protocol behavior.


106. Production Checklist#

[ ] Remote-call timeouts
[ ] Retry policy
[ ] Exponential backoff
[ ] Jitter
[ ] Retry limits
[ ] Idempotency
[ ] Circuit breakers
[ ] Bulkheads
[ ] Backpressure
[ ] Load shedding
[ ] Health checks
[ ] Graceful degradation
[ ] Replication
[ ] Failure domains
[ ] Quorum strategy
[ ] Leader election where required
[ ] Split-brain protection
[ ] Consistency model
[ ] Recovery strategy
[ ] Observability
[ ] Distributed tracing
[ ] Tail-latency monitoring
[ ] Disaster recovery

107. Key Mental Model#

The most important mental model from this chapter is:

Distributed System
       |
       +---- Network can fail
       |
       +---- Nodes can fail
       |
       +---- Messages can be delayed
       |
       +---- Responses can be lost
       |
       +---- Clocks can differ
       |
       +---- State can temporarily diverge
       |
       +---- Failures can be partial

Therefore:

Timeout
   +
Retry
   +
Idempotency
   +
Consistency
   +
Coordination
   +
Recovery
   +
Observability

are fundamental distributed-system tools.


108. Chapter Summary#

The most important concepts are:

  1. A distributed system contains multiple independent computing nodes.
  2. Networks introduce uncertainty.
  3. Remote calls are not equivalent to local function calls.
  4. Partial failure is a defining challenge.
  5. A timeout means the response was not received in time, not necessarily that the operation failed.
  6. Retries can create duplicate operations.
  7. Exponential backoff and jitter reduce retry storms.
  8. Circuit breakers prevent repeated calls to unhealthy dependencies.
  9. Bulkheads isolate resource consumption.
  10. Backpressure controls overload.
  11. Load shedding protects critical functionality.
  12. Network partitions can divide a cluster.
  13. Split brain can create multiple conflicting authorities.
  14. Quorum provides a basis for distributed decisions.
  15. Replication provides copies; consensus coordinates agreement.
  16. Leader election chooses an authoritative coordinator.
  17. Clock skew complicates distributed ordering.
  18. Logical clocks can represent causal relationships.
  19. Availability and reliability are related but different.
  20. Fault tolerance requires explicit failure assumptions.
  21. Tail latency matters in distributed request paths.
  22. Distributed locks require careful lease and stale-owner handling.
  23. Fencing tokens can protect against stale lock holders.
  24. Stateless application servers simplify horizontal scaling.
  25. Failure domains matter when placing replicas.
  26. Redundancy is only useful when failures are sufficiently independent.
  27. Consistency must be explicitly defined.
  28. Asynchronous architecture often introduces eventual consistency.
  29. Distributed transactions require specialized patterns.
  30. Recovery is part of reliability, not an afterthought.

The core principle is:

Assume the network will fail.
Assume components will fail.
Assume responses can be lost.
Design the protocol so the system
remains correct under those failures.

109. Interview Revision Checklist#

You should now be able to explain:

  • Distributed systems
  • Centralized vs distributed systems
  • Scalability
  • Availability
  • Reliability
  • Fault tolerance
  • Partial failure
  • Network failure
  • Network partition
  • Split brain
  • Timeout
  • Retry
  • Exponential backoff
  • Jitter
  • Retry storms
  • Cascading failures
  • Circuit breakers
  • Bulkheads
  • Backpressure
  • Load shedding
  • Quorum
  • Replication
  • Leader election
  • Consensus intuition
  • Clock skew
  • Logical clocks
  • Causality
  • Strong consistency
  • Eventual consistency
  • Distributed locks
  • Lock leases
  • Fencing tokens
  • Failure domains
  • Redundancy
  • Tail latency
  • P95/P99
  • Stateless services
  • Distributed transactions
  • RPO
  • RTO
  • Failure-oriented design

110. Next Chapter#

Chapter 23 — CAP Theorem#

In the next chapter we will deeply understand CAP rather than memorizing the phrase "pick two."

We will learn:

  • What consistency means in CAP
  • What availability means in CAP
  • What a network partition means
  • Why partitions are fundamentally important
  • CAP theorem precisely
  • Linearizability intuition
  • Partition tolerance
  • CP systems
  • AP systems
  • What CAP does and does not say
  • CAP vs ACID
  • CAP vs PACELC
  • Real database examples
  • Distributed database trade-offs
  • Quorum systems
  • Read/write quorums
  • Failure scenarios
  • Practical architecture decisions
  • Common CAP misconceptions
  • System-design interview questions

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 21 — Event-Driven ArchitectureNext ChapterChapter 23 — CAP Theorem
PrevNext