Distributed Coordination
Coordination services are the backbone of distributed systems, providing primitives for leader election, configuration management, service discovery, and distributed locking. If consensus protocols (Paxos, Raft) are the engine, coordination services are the car — they package that engine into something application developers can actually use without needing a PhD in distributed systems theory.Module Duration: 12-16 hours
Key Topics: Zookeeper, etcd, Consul, Service Discovery, Leader Election, Distributed Locks
Interview Focus: Zookeeper recipes, leader election algorithms, lock safety
Key Topics: Zookeeper, etcd, Consul, Service Discovery, Leader Election, Distributed Locks
Interview Focus: Zookeeper recipes, leader election algorithms, lock safety
Why Coordination is Hard
Zookeeper
Architecture
Zookeeper Guarantees
ZAB Protocol (Zookeeper Atomic Broadcast)
etcd
Modern Coordination Service
etcd API Examples
Leader Election Patterns
Zookeeper Recipe
Implementation
Distributed Locks
Lock Recipes
Redis Distributed Locks (Redlock)
Advanced: Distributed Coordination Patterns
1. Barrier Synchronization
In parallel computing and distributed data processing (like MPI or Apache Spark), you often need to ensure that no node starts Step 2 until all nodes have finished Step 1.The Distributed Barrier Algorithm (Zookeeper Recipe)
- Barrier Creation: A designated node creates a znode
/barrier. - Entering the Barrier:
- Each participant node creates an ephemeral znode under
/barrier/node_i. - Nodes call
getChildren("/barrier", watch=True). - If the number of children is less than (the threshold), they wait for the watch to trigger.
- Once the -th node joins, the watch triggers, and all nodes proceed.
- Each participant node creates an ephemeral znode under
- Exiting the Barrier:
- Similar to entering, nodes wait until all nodes have finished their work before deleting their ephemeral znodes.
2. Distributed Phasers
A Phaser is a more advanced synchronization primitive that combines aspects of a Barrier and a CountDownLatch.Why Phasers?
Static barriers require a fixed number of participants (). Distributed phasers allow:- Dynamic Registration: Nodes can join or leave the coordination group mid-flight.
- Hierarchical Phasers: To avoid the bottleneck of a single coordination znode, phasers can be arranged in a tree. A parent phaser only moves to the next phase once all its child phasers have signaled.
- Tiered Wait: Some nodes can “signal” they are done but not “wait” for others (useful for pipelining).
3. Distributed Lock-Free Patterns
At Staff/Principal level, you must understand when locks (even distributed ones) are too expensive and how to move toward Lock-Free progress. In single-node systems, we useCAS (Compare-And-Swap) instructions. In distributed systems, we use Optimistic Concurrency Control (OCC) and Wait-Free Data Structures.
Hazard Pointers (Distributed Context)
Hazard pointers are used to safely manage memory in lock-free data structures by ensuring that a node is not deleted while another thread (or node) is still accessing it. In a distributed environment (e.g., a shared-memory distributed graph or a distributed cache like Pelikan), hazard pointers can be implemented using a Lease-based Central Registry:- Before a node reads a shared object, it publishes a “Hazard Lease” (short TTL).
- The “Owner” of the object cannot reclaim or reuse that memory address until all hazard leases have expired or been revoked.
RCU (Read-Copy-Update) at Scale
RCU allows multiple readers to access data while a single writer updates it without any locks.- Read: Readers access the current version of the data without any overhead.
- Update: The writer creates a new copy, updates it, and atomically swaps the pointer.
- Reclaim: The writer waits for a “Grace Period” (where all pre-existing readers have finished) before deleting the old copy.
- Writer: Publishes a new configuration version and records the timestamp .
- Readers: Report their “Highest Observed Version” periodically.
- Reclaim: Once all active readers report a version , the writer safely deletes .
4. Comparison of Progress Guarantees
Staff Tip: Moving from Lock-based to Lock-Free coordination (using OCC or RCU) is the primary way to achieve linear scalability in high-throughput control planes.
Load Balancing Algorithms
Power of Two Choices (P2C)
For Staff-level engineering, you must understand why simple “Least Connections” or “Round Robin” can fail in large-scale distributed systems. The Problem: Herd Effect In a traditional “Least Connections” load balancer, if one server becomes slightly faster, all clients might simultaneously see it as the “least loaded” and overwhelm it (the thundering herd). The Solution: P2C Introduced by Michael Mitzenmacher, the Power of Two Choices algorithm is elegantly simple:- Pick two random nodes from the pool.
- Choose the one with the least load (e.g., fewest active requests).
- Exponential Improvement: Choosing the best of two random samples provides an exponential improvement over choosing one random sample. It performs almost as well as “Least Loaded” across the entire pool but with complexity instead of .
- Avoids Hotspots: Because it’s stochastic, it prevents all clients from converging on the same “best” node at the exact same micro-second.
Service Discovery
Patterns
Consul Service Discovery
Implementation Example
Configuration Management
Dynamic Configuration
Advanced Design Scenarios
Scenario 1: Highly Available Control Plane with etcd
You are building a control plane (like Kubernetes API + controllers) that must never have two leaders and must tolerate node and zone failures. Design:- etcd cluster:
- 3 or 5 nodes spread across failure domains (AZs).
- Use Raft (already built into etcd) for linearizable writes.
- Control-plane components (e.g., schedulers, controllers):
- Each instance registers its lease and identity under a prefix, e.g.,
/controllers/scheduler/instances/<id>. - Leader election implemented using compare-and-swap + leases:
- Each instance registers its lease and identity under a prefix, e.g.,
- If the leader crashes or loses connectivity, its lease expires → key deleted → another instance wins via CAS.
- Network partition:
- Only the majority side of etcd can make progress (Raft quorum).
- Minority side cannot renew its lease; it loses leadership and should demote itself.
- etcd’s leases, transactions, and watch APIs.
- Quorum-based leader election to avoid split-brain in coordination-critical components.
Scenario 2: Distributed Lock with Fencing for a Financial System
You need a lock to guard access to a payment ledger so that no two writers interleave operations on the same account, even in the presence of pauses and network glitches. Design:- Use Zookeeper or etcd to implement a FIFO lock with monotonic fencing tokens.
- On acquiring the lock, the client gets a token that increases over time.
- Downstream resources (e.g., database, Kafka consumer) validate tokens and reject stale ones.
- Even if a GC pause or network glitch causes the old lock holder to “wake up” after losing the lock, its token is smaller, so its write fails.
- The lock service enforces mutual exclusion at the coordination layer; fencing tokens extend that guarantee all the way to the storage layer.
Scenario 3: Multi-Region Service Discovery and Configuration
You operate services in multiple regions with independent Consul/etcd clusters, but want a consistent way to discover services and roll out configuration. Design:- Per-region registry:
- Each region runs its own Consul or etcd cluster for low-latency discovery.
- Services register only in their local registry under paths like
/services/apiand/config/....
- Global view:
- A small control-plane service aggregates per-region registry data into a read-only global catalog (for dashboards, tooling).
- Traffic routing:
- Clients prefer local region endpoints discovered from the local registry.
- For failover, they can fall back to remote region instances using a secondary discovery path.
- Store global config under a versioned key, e.g.,
/config/feature-flags/v42. - Each service:
- Watches
/config/feature-flags/current(a pointer to the active version). - On change, fetches the new version document and swaps it in-memory.
- Watches
- Can prepare new configs at
/v43in all regions, validate them, and then atomically switchcurrent→v43. - During regional partitions, each region keeps using its last known
currentversion; when connectivity restores, they converge.
- Service discovery patterns, dynamic configuration, and watch-based updates into a multi-region, fault-tolerant design.
Interview Practice
Q1: Design a distributed lock service
Q1: Design a distributed lock service
Question: Design a distributed lock service for a payment system.Requirements:
- Mutual exclusion (only one holder)
- Deadlock prevention (timeouts)
- Fault tolerance (handle crashes)
- Fairness (FIFO ordering)
Q2: Handle split-brain in leader election
Q2: Handle split-brain in leader election
Question: How do you prevent split-brain during leader election?Answer:The Problem:Solutions:
-
Quorum requirement
- Need majority (N/2 + 1) to elect leader
- 3 nodes → need 2
- Partition with minority cannot elect leader
-
Fencing
- Each leader gets epoch number
- Resources only accept from current epoch
- Old leader’s requests rejected
-
Lease-based leadership
- Leader holds lease with TTL
- Must renew before expiry
- On partition, lease expires → no leader in minority
Q3: Implement service discovery
Q3: Implement service discovery
Question: Design service discovery for a microservices platform.Components:Failure Handling:
- Service crashes → ephemeral entry deleted
- Registry partitioned → use cached instances
- All instances down → return error, trigger alerts
Key Takeaways
Use Proven Coordination Services
Zookeeper, etcd, Consul are battle-tested. Don’t reinvent distributed consensus.
Ephemeral Nodes are Powerful
Automatic cleanup on session end enables leader election, locks, and service discovery.
Fencing Tokens Prevent Stale Operations
Always use monotonic tokens with locks to prevent split-brain safety violations.
Watch, Don't Poll
Coordination services provide watch/subscribe for efficient change detection.
Next Steps
Consensus Protocols
Understand Raft and Paxos that power coordination services
Messaging Systems
Learn Kafka and message queues for async coordination