RecapsKayavak

Kayavak / Recaps / Distributed Systems

Recaps · Volume 5

Distributed Systems

The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.

Open the volume

65

Foundations of Distributed Systems

Key ideas

  • Why distribute: scale, availability, latency to users, organisational independence; each adds partial failure and coordination costs.
  • Fallacies of distributed computing: reliable network, zero latency, infinite bandwidth, secure network, fixed topology, one administrator, zero transport cost, homogeneous network.
  • System models: synchronous, asynchronous, partially synchronous timing; crash-stop, crash-recovery and Byzantine failures; FLP impossibility (no deterministic consensus in a fully asynchronous system with one crash).
  • Latency: numbers by distance; tail latency; fan-out amplification; hedged and tied requests; deadlines and propagation.
  • Partial failure and timeouts: ambiguous outcomes; timeouts as guesses; retries need idempotency; backoff with jitter.
  • Ordering: per-connection and per-partition order only; sequence numbers, versions, commutative operations.
  • Partitioning and replication: the two ways to spread data; consistency questions follow from replication.
  • Distribution in code: RPC frameworks (gRPC), the "remote call looks local" trap, explicit failure types.

Numbers to remember

  • Lab: function call 0.04 µs vs localhost HTTP 0.68 ms; with 100-way fan-out 63% of pages hit a backend's p99; hedging cut p99 from 203 ms to 14 ms; 4 connections reordered 75% of messages.
  • Rough latencies: same zone 0.1–0.5 ms, cross-zone ~1 ms, cross-region 30–150 ms; light in fibre ~200 km/ms.

Pitfalls

  • Remote calls without timeouts; sequential remote calls where batching or parallelism fits.
  • Judging services by average latency; ignoring fan-out.
  • Assuming message order across connections, threads, partitions or retries.
  • Treating a timeout as a failure of the operation; retrying non-idempotent operations.
  • Hedging non-idempotent requests or hedging without a budget.

Glossary

  • Tail latency: the high percentiles (p99, p99.9) of response time.
  • Fan-out: one request triggering many downstream requests.
  • Hedged request: a duplicate request sent after a delay to cut tail latency.
  • Partial synchrony: a model where timing bounds hold eventually, but not always.
  • Crash-recovery failure: a node that stops and later restarts with its durable state.
  • FLP result: the impossibility of deterministic consensus under full asynchrony with one faulty process.

66

Messaging Systems

Key ideas

  • Why messaging: temporal, load and knowledge decoupling; buffering bursts; fan-out to many consumers; integration between teams.
  • Vocabulary: producer, consumer, broker, topic/subject, queue, partition, offset, consumer group, acknowledgement, prefetch, retention, dead-letter queue.
  • Queues: competing consumers, ack/nack, visibility timeouts (SQS), prefetch (RabbitMQ), exchanges and routing (direct, topic, fanout, headers), priority and delayed messages, quorum queues.
  • Logs: append-only partitions, offsets per consumer group, retention by time/size, compaction, replay, high throughput through sequential I/O and batching.
  • Delivery: at-least-once by default; redelivery after missing acks; idempotent consumers; acknowledging after processing.
  • Ordering: per queue or partition; broken by competing consumers, retries and redelivery; preserved by keys and single-active consumers.
  • Backpressure: prefetch/max in-flight limits, pull consumers, bounded queues, lag monitoring.
  • Patterns: work queues, pub/sub, request/reply, outbox, retry topics with delays, DLQs, claim check (large payloads in object storage).
  • Systems: RabbitMQ, SQS/SNS, Azure Service Bus, Google Pub/Sub, Kafka, Pulsar, Redpanda, NATS JetStream, Redis Streams.

Numbers to remember

  • Lab: durable publishing with async acks 4× slower than fire-and-forget, waiting for each ack 32× slower; 4 competing workers 2.6× faster; key-based routing eliminated 48 out-of-order events.

Pitfalls

  • Acknowledging before processing; processing without idempotency.
  • No max_deliver/redrive policy; DLQs nobody watches.
  • Competing consumers on events that must stay ordered.
  • Synchronous per-message publishing on hot paths.
  • Unbounded prefetch; consumers holding thousands of unacked messages.
  • Huge messages instead of references; no schema for message contracts.

Glossary

  • Competing consumers: several consumers sharing a queue, each message to one.
  • Consumer group: consumers sharing a log's partitions with a shared offset.
  • Ack wait / visibility timeout: time before an unacknowledged message is redelivered.
  • Prefetch / max ack pending: limit on unacknowledged messages per consumer.
  • Dead-letter queue: where messages go after too many failed deliveries.
  • Retention: how long a log keeps messages regardless of consumption.

67

Kafka in Depth

Key ideas

  • Model: distributed, partitioned, replicated commit log; records are key, value, headers and timestamp at an offset.
  • Storage: partitions are segment files with offset and time indexes; sequential I/O, page cache and zero-copy make it fast.
  • Replication: leader and followers per partition; the ISR; acks=all with min.insync.replicas=2 and RF 3 for durability; the high watermark limits what consumers see; unclean leader election trades data for availability.
  • KRaft: the metadata quorum replaces ZooKeeper (Kafka 4.0 removed ZooKeeper entirely).
  • Producers: partitioner (murmur2 of key, sticky for null keys), batching (linger.ms, batch.size), compression, idempotence (producer ID + epoch + sequence), retries and delivery.timeout.ms, transactions.
  • Consumers: groups, assignment strategies, eager vs cooperative rebalancing, KIP-848 protocol, static membership, offset commits, auto.offset.reset, max.poll.interval.ms, lag.
  • Share groups (KIP-932): queue semantics on topics, with per-record acknowledgement and several consumers per partition.
  • EOS: idempotent producer + transactions + read_committed consumers for read-process-write within Kafka.
  • Retention: delete by time/size, compaction by key (latest value per key, tombstones), tiered storage for cheap long retention.
  • Ecosystem: Schema Registry with compatibility modes, Kafka Connect (source/sink, Debezium CDC), Kafka Streams, Flink, MirrorMaker 2.

Numbers to remember

  • RF 3, min.insync.replicas=2, acks=all is the standard durable setting.
  • Lab: linger 5 ms cut produce requests 3×, 50 ms cut them 37×; idempotence turned 11 records into 6 after a lost response; committing every 20 records redid 17 after a crash; cooperative rebalancing revoked 3 partitions instead of 12; growing 6→8 partitions moved 74% of keys.

Pitfalls

  • Too few partitions for future consumers, or growing a keyed topic in place.
  • Hot keys and skewed partitions.
  • acks=1 or min.insync.replicas=1 in production; unclean leader election enabled.
  • Auto-commit with asynchronous processing, losing records on crash.
  • Slow processing exceeding max.poll.interval.ms, causing rebalance storms.
  • No schema contract, so producers break consumers.
  • Assuming exactly-once covers side effects outside Kafka.

Glossary

  • ISR: in-sync replicas, the followers caught up with the leader.
  • High watermark: highest offset replicated to all ISR; consumers read up to it.
  • Consumer group: consumers sharing partitions with common committed offsets.
  • Rebalance: reassignment of partitions when membership changes.
  • Compaction: retention keeping only the latest record per key.
  • Tombstone: a null-value record that deletes a key under compaction.

68

Delivery Semantics

Key ideas

  • The three guarantees come from the order of "do the work" and "acknowledge/commit": ack first is at-most-once, work first is at-least-once.
  • Exactly-once delivery is impossible over unreliable networks (two generals; the FLP-style uncertainty of a timeout). Exactly-once processing is achievable: at-least-once delivery plus idempotent, atomic effects.
  • Producer side: idempotent producers (Kafka PID + sequence), dedup windows (JetStream, SQS FIFO, Service Bus), business IDs.
  • Consumer side: dedup tables in the same transaction, unique constraints, natural idempotence (SET status = 'PAID'), conditional updates with versions, idempotency keys for external APIs.
  • Kafka EOS: transactional producer + sendOffsetsToTransaction + read_committed; it covers Kafka-to-Kafka only.
  • Outbox and inbox: outbox avoids dual writes on the producer; inbox (dedup table) on the consumer; CDC relays.
  • Side effects outside a transaction (email, SMS, third-party calls) need provider idempotency keys, intent records and reconciliation.

Numbers to remember

  • Lab: dedup window 2,000→1,000 stored; check-then-act doubled 497 of 500 payments, a unique constraint 0; dual writes lost 23 events or invented 27, the outbox 0; a dedup insert added 0.07 ms (14%) per message.

Pitfalls

  • Believing a broker's "exactly-once" flag covers your database or emails.
  • Deduplicating with SELECT-then-INSERT.
  • Dedup marker and effect in separate transactions.
  • Unbounded dedup tables; windows shorter than redelivery delays.
  • Dual writes to a database and a broker.
  • New message IDs generated on each retry.

Glossary

  • Effectively-once: each message's effect happens once despite repeated delivery.
  • Idempotent: applying an operation twice has the same effect as once.
  • Idempotency key: client-supplied ID a server uses to deduplicate requests.
  • Dual write: updating two systems without a shared transaction.
  • Transactional outbox: events stored in the same transaction as state, published later.
  • Inbox: consumer-side table of processed message IDs.

69

Consistency Models

Key ideas

  • A consistency model defines which histories of reads and writes are allowed.
  • Linearizable: a single copy in real time; composable per object; costs coordination (quorums, ReadIndex, leases).
  • Sequential: one total order consistent with each client's program order, not real time.
  • Causal: causally related operations seen in order by all; concurrent ones may differ. The strongest model that stays available under partition.
  • Session guarantees: read-your-writes, monotonic reads, monotonic writes, writes-follow-reads.
  • Eventual / strong eventual: convergence when writes stop; CRDTs give convergence without coordination.
  • Isolation is different: serializability is about transactions over many objects; strict serializability = serializable + linearizable.
  • Real systems: etcd and ZooKeeper (linearizable writes), Spanner (external consistency via TrueTime), CockroachDB (serializable, near-linearizable), DynamoDB (eventually or strongly consistent reads), Cassandra (tunable quorum), MongoDB (read/write concerns, causal sessions), Cosmos DB (five levels).
  • Testing: record histories and check them (Jepsen, Knossos, Porcupine, Elle).

Numbers to remember

  • Lab: a 3 ms replica link made 10,000/10,000 immediate replica reads stale; etcd linearizable reads ~1.7× serializable on one machine; a session token removed 201 time-travel reads; 989/1,000 replies were seen without their post across two replicas; a 50 ms sticky window fixed read-your-writes with 10% of reads on the primary.

Pitfalls

  • Reading from replicas right after writing.
  • Load balancers spreading one user's reads across replicas of different lag.
  • Assuming "strong consistency" in marketing means linearizable.
  • Confusing etcd's "serializable" reads with serializable isolation.
  • WAIT n with n smaller than the replica you read from.

Glossary

  • Linearizability: operations appear atomic at a point between invocation and response.
  • ReadIndex: Raft read protocol confirming leadership before serving.
  • Session token: a client-held position (revision, LSN, timestamp) used to reject older replicas.
  • Bounded staleness: reads at most X seconds or versions behind.
  • Causal order: happened-before relationship between operations.

70

CAP and PACELC

Key ideas

  • CAP (Brewer 2000, Gilbert–Lynch 2002): under a partition, a system can't be both linearizable and available to every non-failed node.
  • Precise terms: C = linearizability; A = every request to a live node eventually gets a non-error answer; P = arbitrary message loss between groups.
  • Not "pick two": partitions aren't optional; the choice is per operation and only applies during partitions (Brewer's 2012 retrospective).
  • CP: majority quorums (Raft, Paxos), minority sides refuse; AP: all sides answer, reconcile later (last-writer-wins, vector clocks, CRDTs, read repair).
  • PACELC (Abadi 2010): else, latency vs consistency. PA/EL (Cassandra, DynamoDB defaults, Riak), PC/EC (Spanner, etcd, ZooKeeper, CockroachDB), PA/EC and PC/EL mixes exist (MongoDB defaults are often described as PA/EC).
  • Beyond CAP: harvest and yield (Fox and Brewer), degraded modes, bounded staleness, fencing tokens to stop split brain.
  • Failover is a CAP decision: promoting an async replica trades lost writes for availability.

Numbers to remember

  • etcd default heartbeat 100 ms, election timeout 1,000 ms.
  • Lab: waiting for a 3 ms replica took writes from 0.12 to 4.09 ms; Redis refused writes 1.7 s after its replica went silent; leader loss stopped writes for 1.4–2.0 s; minority-side writes 0 of 2.

Pitfalls

  • Calling a single-node database "CA".
  • Async failover without fencing (two primaries).
  • Ignoring the everyday latency cost while debating partitions.
  • Clients pinned to one endpoint, so a minority partition becomes an outage.
  • Election timeouts shorter than real network jitter.

Glossary

  • Partition: loss of communication between groups of nodes.
  • Split brain: two nodes both acting as leader/primary.
  • Quorum: a majority (or configured subset) whose agreement is required.
  • Fencing token: increasing number that lets resources reject stale leaders.
  • Harvest / yield: completeness of an answer / fraction of requests answered.

71

Replication

Key ideas

  • Goals: availability, durability, read scaling, locality.
  • Single leader: synchronous, semi-synchronous or asynchronous followers; log shipping (statement, WAL, logical/row); failover (detection, election, reconfiguration) and its dangers (lost async writes, split brain, fencing).
  • Lag anomalies: read-your-writes, monotonic reads, consistent prefix; fixes from chapter 69.
  • Multi-leader: per-region leaders, offline clients and collaborative editing; conflicts handled by avoidance (home region per key), LWW, merge functions, CRDTs or user resolution; replication topologies (all-to-all, ring, star).
  • Leaderless: N, W, R; R + W > N overlap; sloppy quorums and hinted handoff; read repair; anti-entropy with Merkle trees; tombstones and gc grace.
  • Conflict detection: version vectors and dotted version vectors; siblings.
  • CRDTs: state-based (merge is commutative, associative, idempotent) and operation-based; G-counter, PN-counter, LWW-register, MV-register, OR-set, RGA/sequence CRDTs (Automerge, Yjs).

Numbers to remember

  • Lab: R+W>N gave 0 stale reads, W=1/R=1 up to 10%; read repair left 26% of keys stale on a returning replica; 5 ms clock skew lost 25% of near-simultaneous LWW updates; Redis replicas ran 47–92 KB behind under load.

Pitfalls

  • Assuming quorum reads are linearizable (sloppy quorums, concurrent writes and partial failures break it).
  • LWW on wall clocks for data that matters.
  • Never running anti-entropy repair; resurrected deletes.
  • Failing over to an async replica without measuring what's lost.
  • Multi-leader without a conflict policy.

Glossary

  • Replication lag: delay between a write on the leader and on a follower.
  • Quorum: minimum replicas that must respond (W for writes, R for reads).
  • Hinted handoff: temporary storage of writes for an unavailable replica.
  • Read repair: fixing stale replicas during reads.
  • Version vector: per-replica counters detecting concurrent updates.
  • CRDT: replicated type with conflict-free merge.

72

Consensus

Key ideas

  • Consensus: agreement, validity, integrity (safety) and termination (liveness); state machine replication through a replicated log.
  • FLP (1985): no deterministic algorithm guarantees consensus in a fully asynchronous system with even one crash; real systems use timeouts (partial synchrony) and keep safety always, liveness when the network behaves.
  • Quorums: majorities intersect; N = 2f + 1 tolerates f crashes.
  • Paxos: proposers, acceptors, learners; prepare/promise and accept/accepted with ballot numbers; Multi-Paxos with a stable leader.
  • Raft: leader election with randomised timeouts and terms; log replication with consistency checks; commit on majority in current term; election restriction; membership changes (joint consensus or single-server changes); snapshots; ReadIndex and lease reads.
  • Others: Zab (ZooKeeper), Viewstamped Replication, EPaxos and flexible quorums.
  • Byzantine: PBFT and descendants need 3f + 1 nodes; used in blockchains and some aerospace systems.
  • Practice: use etcd, ZooKeeper, Consul or an embedded Raft library; keep consensus state small; fsync latency and network RTT bound performance.

Numbers to remember

  • 3 members tolerate 1 failure, 5 tolerate 2; BFT needs 3f + 1.
  • etcd defaults: heartbeat 100 ms, election 1,000 ms; recommended keyspace under 8 GB (default quota 2 GB).
  • Lab: puts 1.10 ms (1 member), 1.76 ms (3), 2.26 ms (5), 1.15 ms without fsync; batching took 520 to 1,687 writes/s; read-then-put lost 627 of 800 increments; tuned timeouts cut failover from 1–1.8 s to 0.4–0.6 s.

Pitfalls

  • Even-sized clusters; clusters stretched over high-latency links without tuning.
  • Slow or shared disks under consensus members.
  • Storing large or high-churn data in etcd/ZooKeeper.
  • Read-modify-write without compare-and-swap.
  • Changing membership of a cluster that has lost quorum (needs disaster recovery, not an add).

Glossary

  • Replicated state machine: identical deterministic machines applying the same log.
  • Term / ballot / epoch: monotonically increasing leadership number.
  • Commit index: highest log entry known to be committed.
  • Election timeout: silence after which a follower campaigns.
  • Joint consensus: Raft's two-phase configuration change.
  • Lease read: leader serves reads without a round, relying on bounded clock drift.

73

Distributed Transactions

Key ideas

  • The problem: atomic change across independent resources; local transactions alone can't provide it.
  • 2PC: prepare (vote, durable, locks held) and commit/abort; blocking on coordinator failure; XA standard; 3PC isn't used in practice; Paxos/Raft-replicated coordinators (Spanner, CockroachDB parallel commits).
  • Sagas (Garcia-Molina and Salem, 1987): sequence of local transactions with compensations; forward recovery (retry) and backward recovery (compensate); pivot transactions.
  • Orchestration vs choreography: central coordinator with explicit state, or services reacting to events; orchestration is easier to observe and change.
  • Missing isolation countermeasures: semantic locks, commutative updates, pessimistic ordering, reread values, version files.
  • Infrastructure: outbox for reliable step events, idempotent steps, persisted saga state, durable execution engines.
  • CDC feeds events from databases without dual writes.

Numbers to remember

  • Lab: 2PC 1.08 ms vs 0.38 ms local; prepared transactions survived a restart with locks; no saga state left 78 units stranded after 27 crashes, persisted state left 0; missing isolation turned away 20 customers while 8 units went unsold.

Pitfalls

  • Enabling prepared transactions without monitoring pg_prepared_xacts.
  • 2PC across services owned by different teams.
  • Compensations that can fail or aren't idempotent.
  • Saga state only in memory.
  • Ignoring the visibility of intermediate states in the UX.

Glossary

  • Coordinator / participant: 2PC roles.
  • In-doubt transaction: prepared but not yet told the outcome.
  • Compensating transaction: semantic undo of a committed step.
  • Pivot transaction: the saga step after which it must go forward.
  • Orchestrator: component directing a saga's steps.
  • Choreography: services coordinating through events.

74

Idempotency

Key ideas

  • Idempotence: f(f(x)) = f(x); for systems, repeating a request has no extra effect. Safety (no side effects) is stronger.
  • HTTP (RFC 9110): GET, HEAD, OPTIONS, TRACE safe; PUT and DELETE idempotent; POST and PATCH not.
  • Why it matters: retries on timeouts, at-least-once queues, proxies and load balancers, double clicks, mobile networks.
  • Idempotency keys: client-generated per intended operation; server stores key, request fingerprint, status and response; replay, 409 for in-progress, 422 for mismatched body; expiry (often 24 h); scoped per account.
  • Natural idempotence: PUT with full state, conditional updates (If-Match/ETags, version columns), upserts, set semantics, unique constraints on business IDs.
  • Dedup techniques: unique constraints, inbox tables, broker windows, bloom filters for large streams (with false positives), TTL caches.
  • Third parties: forward your key, use their idempotency features, record intent and reconcile.
  • Crash safety: atomic phases, recovery points, expiry of in-progress keys.

Numbers to remember

  • Lab: 46 of 200 payments doubled without keys under timeouts; 0 with keys; concurrent duplicates gave 50 × 201 and 50 × 409 with 50 charges; key handling cost about 1 ms per request; 1,000 keys took 384 kB.

Pitfalls

  • Generating a new key on each retry (it must be per intended operation).
  • Storing "seen" without the response.
  • SELECT-then-INSERT key checks.
  • Keys never expiring, or expiring before clients stop retrying.
  • Unscoped keys shared across accounts.
  • Assuming PUT is idempotent when the handler appends or increments.

Glossary

  • Idempotent: repeated application has the same effect as one.
  • Safe method: has no side effects on the server.
  • Idempotency key: client-chosen operation identifier.
  • Request fingerprint: hash of the request body used to detect key reuse.
  • Recovery point: stored progress marker for a multi-step request.
  • Replay: returning a stored response for a duplicate request.

75

Time and Ordering

Key ideas

  • Physical clocks: quartz drift, NTP (ms over the internet), PTP (µs on LANs), steps vs slews, leap seconds and smearing, VM pauses.
  • Wall vs monotonic: wall for time of day (store UTC), monotonic for durations, timeouts, leases and rate limits.
  • Skew consequences: LWW losses, wrong ordering, expired-early leases, duplicate time-based IDs, broken TTLs.
  • Logical clocks: Lamport (happened-before ⇒ smaller), vector clocks (detect concurrency), version vectors and dotted version vectors for replicas.
  • Bounded uncertainty: TrueTime intervals and commit wait (Spanner); AWS ClockBound; HLC with max offset (CockroachDB).
  • Ordering without clocks: sequence numbers from a single leader, consensus logs, per-partition offsets, causal tokens.
  • Event time: event vs processing time, windows (tumbling, sliding, session), watermarks, allowed lateness, triggers.
  • IDs: Snowflake, ULID, UUIDv7 (RFC 9562) with monotonic guards.

Numbers to remember

  • NTP: a few ms over the internet; CockroachDB max offset 500 ms; Snowflake: 41-bit ms, 10-bit node, 12-bit sequence.
  • Lab: clock reads ~80 ns in Python; a wall-clock timeout fired after 0.31 s instead of 2 s; a 1 s backward step made 29 duplicate IDs; HLC 0 causality violations vs 1,509 with raw clocks; a 10 s watermark still left 1.2% late events.

Pitfalls

  • currentTimeMillis() for durations.
  • Local time zones in stored timestamps.
  • Ordering cross-server events by timestamp.
  • ID generators without a backwards-clock guard.
  • Lease logic assuming clocks agree.
  • Windows on processing time when results must reflect event time.

Glossary

  • Clock skew: difference between two clocks' readings.
  • Drift: rate at which a clock gains or loses time.
  • Monotonic clock: never decreases; for intervals.
  • Happened-before: Lamport's causal partial order.
  • Watermark: a stream's estimate that no earlier events remain.
  • HLC: hybrid logical clock (physical + logical components).

76

Rate Limiting and Traffic Control

Key ideas

  • Purposes: protect capacity, fairness between clients, cost control, abuse prevention, contractual quotas.
  • Algorithms: fixed window, sliding log, sliding window counter, token bucket (burst + rate), leaky bucket (smoothing, GCRA).
  • Implementation: atomic operations in a shared store (Lua, INCR), local buckets, hybrid sync, gateways (Envoy, Nginx limit_req, Kong), libraries (Bucket4j, Resilience4j, Guava RateLimiter).
  • Keys and tiers: per API key, user, IP, tenant, endpoint and cost (weighted requests); quotas per day/month.
  • Concurrency and adaptive limits: Little's law, in-flight caps, AIMD/gradient algorithms, bulkheads.
  • Load shedding and prioritisation: bounded queues, LIFO under overload, deadline propagation, criticality tiers, brownouts.
  • Client cooperation: 429/503, Retry-After, RateLimit headers, exponential backoff with jitter, retry budgets.
  • Where limits live: edge/CDN, API gateway, service mesh, in-process, database.

Numbers to remember

  • Little's law: concurrency = arrival rate × latency.
  • Lab: fixed window allowed 199 per 10 s against a limit of 100; sliding counter 111; client-side GET/SET allowed ~400 against 50; uneven local limits gave 353 of 400; a Redis check cost 0.11 ms; an unbounded queue at 1.5× capacity reached p99 9.5 s, a capped one 0.63 s.

Pitfalls

  • Fixed windows for strict limits.
  • Non-atomic distributed counters.
  • Unbounded queues ("we'll catch up").
  • Limits without headers, so clients can't adapt.
  • Retrying 429s immediately.
  • One global limit with no priorities, so health checks or checkout get shed with everything else.

Glossary

  • Token bucket: capacity + refill rate limiter.
  • GCRA: generic cell rate algorithm, a leaky bucket with one timestamp.
  • Load shedding: rejecting work to stay within capacity.
  • Bulkhead: isolated resource pools so one workload can't exhaust all.
  • Fail open / fail closed: allow or deny when the limiter itself is unavailable.
  • Retry budget: cap on retries as a fraction of requests.

77

Coordination

Key ideas

  • Why careful: coordination is where partial failure, timing and process pauses meet; mistakes cause split brain and corrupted data.
  • Failure detection: heartbeats and timeouts, the completeness/accuracy trade-off, φ-accrual, SWIM gossip with indirect probes.
  • Membership and discovery: registries (Consul, etcd, ZooKeeper, Kubernetes Endpoints), health checks, gossip.
  • Leader election: create-if-absent with a lease; ZooKeeper ephemeral sequential nodes; Kubernetes Lease objects; clean resignation.
  • Distributed locks: for efficiency vs for correctness; fencing tokens checked by the resource; Redlock's timing assumptions.
  • Leases: time-bounded ownership; renewal; clock assumptions; minimum TTLs.
  • Coordination services: etcd (Raft, revisions, watches, leases, txns), ZooKeeper (Zab, znodes, sessions, watches), Consul (Raft + Serf); keep them small and low-churn.
  • Avoiding coordination: partition ownership, idempotent operations, CRDTs, deterministic assignment (consistent hashing).

Numbers to remember

  • Kubernetes leader election defaults: lease 15 s, renew deadline 10 s, retry 2 s.
  • Lab: failover = TTL + ≤0.5 s; timeouts of 0.25/0.5/1/2 s gave 42/11/4/1 false verdicts in 3 hours; 139 lock cycles per second; watches delivered changes in 4–9 ms.

Pitfalls

  • Locks for correctness without fencing.
  • Lease TTLs shorter than realistic pauses.
  • Fine-grained, per-request distributed locks.
  • Leaders that never resign on shutdown.
  • Watchers ignoring compaction or reconnect gaps.
  • Thundering herds on lock release.

Glossary

  • Lease: ownership that expires unless renewed.
  • Fencing token: increasing number that lets resources reject stale holders.
  • φ-accrual detector: outputs a suspicion level from heartbeat history.
  • Ephemeral node: ZooKeeper node deleted when its session ends.
  • Watch: subscription to changes on a key or prefix.
  • Herd effect: many clients reacting to one event at once.

78

Distributed Failure Modes

Key ideas

  • Network failures: partitions, packet loss, latency spikes, asymmetric reachability, DNS failures, MTU and TLS problems.
  • Data failures: corruption, lost writes, replication divergence, clock-driven anomalies, poison messages.
  • Dependency failures: slow dependencies, thread/connection pool exhaustion, cascades, retry storms, thundering herds and cache stampedes.
  • Systemic failures: metastable failures, overload and congestion collapse, correlated failures (same AZ, same deploy, same certificate expiry), gray failures.
  • Human and config failures: bad deploys and config pushes (the most common cause of outages), expired certificates, quota exhaustion, runbook errors.
  • Defences: timeouts, retries with backoff/jitter/budgets, idempotency, circuit breakers, bulkheads, load shedding, fallbacks, hedging, deadlines propagation, progressive delivery, feature flags.
  • Practice: fault injection (Toxiproxy, Chaos Mesh, AWS FIS, Gremlin), game days, Jepsen-style testing, blameless postmortems.

Numbers to remember

  • Fan-out tail: P(slow) = 1 − (1 − p)ⁿ; 1% per backend over 100 backends = 63%.
  • Lab: slow B blocked A's /health; timeout + bulkhead kept it instant; retries at two layers made 9 calls per request; a breaker cut B's calls from one per request to 10 in 6 s; a throttled link passed health checks while pages took 2.1 s; hedging cut 63% slow requests to 1.2%.

Pitfalls

  • Libraries with infinite or very long default timeouts.
  • Retries at every layer.
  • Health checks that don't exercise real dependencies, or that fail the whole instance because one optional dependency is down.
  • One shared pool for all dependencies.
  • Breakers with no fallback, or fallbacks that hit the same broken dependency.
  • Testing only crash failures, never slowness.

Glossary

  • Cascading failure: failure propagating through dependencies.
  • Metastable failure: a bad state sustained by its own effects (e.g. retries) after the trigger is gone.
  • Gray failure: partial failure visible to some observers but not others.
  • Bulkhead: resource isolation per dependency or tenant.
  • Hedged request: duplicate request sent after a delay to cut tail latency.
  • Game day: planned exercise injecting failures into a system.