Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Distributed Systems Principles

34. CAP Theorem

Definition. Under network partition, a distributed system must trade off between consistency and availability; it cannot guarantee both.

Rationale. Partitions are inevitable, so the choice is which property to sacrifice. Understanding CAP prevents false expectations and guides deliberate design per use case.

Example. A shopping cart may favor availability (accept writes during partition) while inventory favors consistency (refuse conflicting updates).

Anti-pattern / failure mode. Assuming a distributed database gives strong consistency and high availability under partitions. Review signal: “we never lose data” claims without partition handling.

Related. PACELC (#35), Eventual Consistency (#36), Strong Consistency (#37).

35. PACELC Principle

Definition. Consider latency versus consistency during normal operation, alongside the partition trade-offs of CAP.

Rationale. Even without partitions, strong consistency costs latency. PACELC reminds designers to optimize the common case, not only failure modes.

Example. A read replica may serve slightly stale data to keep latency low, accepting occasional staleness.

Anti-pattern / failure mode. Tuning only for partition scenarios while ignoring everyday latency. Review signal: high p99 latency from synchronous consensus on every read.

Related. CAP (#34), Eventual Consistency (#36).

36. Eventual Consistency

Definition. Replicas converge when updates stop and communication resumes; temporary divergence is accepted.

Rationale. Strong consistency across partitions is expensive or impossible. Eventual consistency trades immediate correctness for availability and performance, suitable for many workloads.

Example. A user’s profile update appears on one server now and on others within seconds.

Anti-pattern / failure mode. Assuming “eventual” means “instant”; building features that require immediate global visibility on eventually consistent data. Review signal: race conditions and stale reads in critical paths.

Related. Strong Consistency (#37), Idempotency (#38).

37. Strong Consistency

Definition. Operations behave as if executed atomically in a globally consistent order; all observers see the same state.

Rationale. Some domains (money, inventory, rights) cannot tolerate divergence. Strong consistency provides a single source of truth at the cost of latency and availability under partitions.

Example. A bank transfer must reflect immediately across all accounts; stale reads are unacceptable.

Anti-pattern / failure mode. Using strong consistency everywhere, hurting performance and availability for data that doesn’t need it. Review signal: synchronous cross-region calls on every request.

Related. CAP (#34), Eventual Consistency (#36), Single Writer (#46).

38. Idempotency Principle

Definition. Repeating an operation produces the same effect as performing it once; design operations so retries are safe.

Rationale. Networks fail and clients retry; non-idempotent operations cause duplicates (double charges, duplicate messages). Idempotency makes retries safe and systems resilient.

Example. A payment API accepts an idempotency key; repeating the same request returns the original result instead of charging again.

Anti-pattern / failure mode. POST endpoints that create a new record on every call, including retries. Review signal: duplicate rows after network hiccups.

Related. At-Least-Once Delivery (#43), Exactly-Once Processing (#45).

39. Bulkhead Principle

Definition. Isolate failures to prevent cascading failures; partition resources so one failing part cannot exhaust the whole.

Rationale. Shared resource pools let one slow dependency starve others. Bulkheads contain the blast radius by giving each component its own limits.

Example. Separate thread pools per downstream service so a slow service doesn’t exhaust the pool used by others.

Anti-pattern / failure mode. A single shared thread/connection pool for all downstream calls. Review signal: one slow dependency takes down the whole service.

Related. Fault Isolation (#49), Circuit Breaker (#40).

40. Circuit Breaker Pattern

Definition. Stop repeatedly calling failing services; open the circuit after repeated failures and retry only after a cooldown.

Rationale. Hammering a failing dependency wastes resources and slows recovery. A circuit breaker fails fast, giving the dependency time to recover.

Example. After 5 consecutive failures, return a cached/fallback response for 30 seconds before probing again.

Anti-pattern / failure mode. Infinite retries with no backoff; or breakers that never reset. Review signal: retry storms during outages.

Related. Timeout (#41), Retry with Backoff (#42), Bulkhead (#39).

41. Timeout Principle

Definition. Every remote operation should have an appropriate timeout; bound waiting so a slow dependency cannot stall callers indefinitely.

Rationale. Unbounded waits tie up resources and cascade delays. Timeouts convert indefinite stalls into handled failures.

Example. Set a 2-second timeout on an HTTP call; on timeout, return a fallback or error.

Anti-pattern / failure mode. Default or no timeouts on HTTP/DB calls; timeouts longer than the user’s patience. Review signal: threads stuck in “waiting” state.

Related. Circuit Breaker (#40), Retry with Backoff (#42).

42. Retry with Backoff

Definition. Retry transient failures with increasing delays; add jitter to avoid thundering herds.

Rationale. Transient failures often resolve quickly; immediate retries can overwhelm a recovering service. Backoff gives time; jitter spreads load.

Example. Retry up to 3 times with exponential backoff (100ms, 400ms, 1600ms) plus random jitter.

Anti-pattern / failure mode. Tight retry loops with no delay; retrying non-transient errors. Review signal: load spikes after a brief outage.

Related. Timeout (#41), Idempotency (#38).

43. At-Least-Once Delivery

Definition. Messages are delivered one or more times; pair with idempotent consumers to handle duplicates safely.

Rationale. Guaranteeing exactly once is costly; at-least-once is achievable and sufficient if consumers are idempotent. It favors liveness over strict deduplication.

Example. A message queue redelivers unacked messages; the consumer dedupes by message id.

Anti-pattern / failure mode. Assuming at-least-once means exactly once, leading to duplicate processing. Review signal: side effects applied multiple times.

Related. Idempotency (#38), At-Most-Once (#44), Exactly-Once (#45).

44. At-Most-Once Delivery

Definition. Messages are delivered zero or one time; accept possible loss in exchange for no duplicates.

Rationale. Some workloads (metrics, best-effort notifications) prefer no duplicates over guaranteed delivery. At-most-once is simpler and cheaper.

Example. Fire-and-forget analytics events that may be dropped but never duplicated.

Anti-pattern / failure mode. Using at-most-once for critical data (orders, payments). Review signal: silent data loss in important flows.

Related. At-Least-Once (#43), Exactly-Once (#45).

45. Exactly-Once Processing Semantics

Definition. Ensure effects are applied once within a defined system boundary, usually via idempotency plus deduplication rather than true once-only delivery.

Rationale. True exactly-once delivery is generally impossible; exactly-once processing is achievable within a boundary using idempotent operations and transactional state. It matters for financial and inventory correctness.

Example. Process a payment within a transaction that records the processed message id; replaying the message is a no-op.

Anti-pattern / failure mode. Claiming “exactly once” from a broker alone without idempotent consumers. Review signal: duplicates after consumer restarts.

Related. Idempotency (#38), At-Least-Once (#43).

46. Single Writer Principle

Definition. Assign one authoritative writer for a given piece of state; avoid concurrent writes to the same data.

Rationale. Concurrent writers cause conflicts and require locking or merge logic. A single writer simplifies consistency and reasoning.

Example. Only the order service writes to the orders table; other services read replicas or events.

Anti-pattern / failure mode. Multiple services writing to the same table directly. Review signal: lock contention and lost updates.

Related. Strong Consistency (#37), Leader Election (#47).

47. Leader Election Principle

Definition. Select a coordinator to manage distributed operations; use consensus or a lock service to agree on the leader.

Rationale. Some tasks (scheduled jobs, partition assignment) need a single coordinator. Leader election provides that without manual assignment, with automatic failover.

Example. A cluster elects a leader to run a nightly reconciliation job; on failure, a new leader is elected.

Anti-pattern / failure mode. Hardcoding a primary node with no failover; split-brain leaders. Review signal: manual failover procedures or duplicate job runs.

Related. Single Writer (#46), Fault Isolation (#49).

48. Backpressure Principle

Definition. Control incoming workloads according to processing capacity; push back on producers instead of unbounded buffering.

Rationale. Unbounded queues grow until memory exhausts. Backpressure propagates capacity limits upstream, keeping the system stable under load.

Example. A stream consumer signals the producer to slow down when its buffer is full.

Anti-pattern / failure mode. Unbounded in-memory queues that grow until OOM. Review signal: memory growth under load, long queue latency.

Related. Bounded Resource (#58), Graceful Degradation (#50).

49. Fault Isolation Principle (Distributed Services)

Distributed-services scope — for process supervision see Fault Isolation (BEAM supervision).

Definition. Prevent failures in one component from propagating to others; contain errors within well-defined boundaries.

Rationale. A single failing component should not take down the system. Isolation limits impact and preserves partial functionality.

Example. A failing recommendation service returns defaults instead of failing the whole page.

Anti-pattern / failure mode. Shared process/crash domains where one bug kills everything. Review signal: full outages from minor component failures.

Related. Bulkhead (#39), Graceful Degradation (#50), Fault Isolation (BEAM) (#102).

50. Graceful Degradation

Definition. Maintain partial functionality when some components fail; serve what you can instead of failing entirely.

Rationale. Users prefer degraded service over total failure. Designing fallbacks keeps the system useful during incidents.

Example. When the search service is down, show cached results or a simplified list instead of an error page.

Anti-pattern / failure mode. All-or-nothing endpoints that fail the whole request if any dependency fails. Review signal: minor dependency outages cause full outages.

Related. Fault Isolation (#49), Circuit Breaker (#40).

51. Event Sourcing Principle

Canonical treatment: CQRS & Event Sourcing. This entry is a summary — see the canonical page for log design, projections, and trade-offs.

Definition. Store state changes as an append-only sequence of events; derive current state by replaying events.

Rationale. An event log provides a complete audit trail and lets you rebuild state, replay history, or create new projections. It shifts storage from “current state” to “what happened.”

Example. An account balance is computed by replaying deposit/withdrawal events.

Anti-pattern / failure mode. Mutating state in place with no history; or storing events without a clear schema/evolution plan. Review signal: inability to answer “how did we get here?”

Related. CQRS (#52), Single Source of Truth (#90), canonical CQRS & Event Sourcing.

52. CQRS (Command Query Responsibility Segregation)

Canonical treatment: CQRS & Event Sourcing. This entry is a summary — see the canonical page for read/write separation and when to combine with Event Sourcing.

Definition. Separate write and read models; optimize each side independently for its workload.

Rationale. Read and write workloads differ; a single model compromises both. Separation lets reads be fast/denormalized and writes be normalized/validated.

Example. Commands update a normalized write store; queries read from a denormalized read model updated via events.

Anti-pattern / failure mode. Applying CQRS to simple CRUD where one model suffices, adding complexity without benefit. Review signal: duplicated models with no performance or scaling need.

Related. Event Sourcing (#51), Separation of Concerns (#9), canonical CQRS & Event Sourcing.