The user wants a multi-region leader election system.
Key components required:
Multi-region: Needs to handle latency and partitions to some degree, or at least simulate multiple clients acting as if they are in different regions. A true multi-region consensus algorithm (like Raft or Paxos) is very complex to implement from scratch in a single script, so I should aim for a practical, simulated example using a database that supports global consistency or a consensus store like etcd/Zookeeper/Consul. However, usually, when people ask for code "build this," they want a self-contained, runnable example in Python/Go/Java.
Leader Election: One leader, multiple followers.
Fencing Tokens: This is crucial for "Split Brain" scenarios. If an old leader thinks it's still the leader and talks to a shared resource (like a database), the fencing token ensures the resource rejects the old request if a new leader with a higher token exists.
Leases: The leader holds the lock for a specific duration. If the leader crashes or network partitions, the lease expires, and a new leader can be elected.
Design Choice:
Language: Python is easy to read and simulate concurrency.
Storage Backend: To keep it runnable without external infrastructure (like a real Zookeeper cluster), I will simulate a distributed storage backend using a simple threading server with a key-value store that supports atomic Compare-And-Swap (CAS). This simulates the behavior of etcd, Consul, or Redis with RedLock.
Architecture:
StorageServer: A central authority (simulating the consistent store) that holds the lease information.
Node: Represents a participant in the election.
Resource: A simulated external resource that checks fencing tokens.
Key Logic:
Lease Acquisition: A node tries to create/update a key (e.g., /leader) with its ID and a fencing token (monotonically increasing).
Fencing Token: Must be strictly increasing. The storage mechanism needs to enforce this.
Keep-Alive (Heartbeat): The leader must periodically update the TTL (Time To Live) of the key.
Failover: If the TTL expires, other nodes try to acquire the lease.
Fencing Implementation:
When Node A becomes leader, it gets Token 1.
Node A gets stuck (GC pause/long GC).
Lease expires.
Node B becomes leader, gets Token 2.
Node A wakes up, tries to write to DB. It sends Token 1.
DB checks: "I last saw Token 2. Token 1 < Token 2. Reject."
Refining the Fencing Token approach:
There are two common ways to do fencing tokens:
Storage-generated: The storage system increments a counter every time the lock key changes owners. This is how Zookeeper zxid or etcd revision works.
Client-generated: The client proposes a timestamp (unlikely to be strictly monotonic across regions without clock sync) or a UUID (no ordering).
Decision: I will use Storage-generated monotonic counters. It's the robust way.
Node 1 wakes up (unpaused). It still thinks it is leader. Tries to write (Token 1).
Resource rejects Token 1 because it has seen Token 2.
Code Structure:
FencingToken: Class/Int.
DistributedLockService: The "Store". Supports try_acquire(node_id, ttl) and renew(node_id).
ProtectedResource: Accepts write(data, token).
Node: The main logic loop.
Let's write this in Python using threading and socketserver or just in-memory objects with locks for simplicity if strictly local simulation, but socket-based is better to simulate "regions". Actually, standard threading with shared memory is fine if we abstract it well enough to look like a network call, but let's go with multiprocessing or just classes to keep it understandable. Let's stick to a clear class structure where the Store is a separate entity.
Walkthrough: Explain the specific part of the code that handles the fencing.
Self-Correction during drafting:
Is it enough to just show the code? I should explain why this is needed. The classic "Zookeeper/Chubby" recipe.
The code should be copy-paste runnable.
Features to include in the code:
LeaseStore: The central coordination point.
ProtectedResource: The thing being protected.
Worker: The client node.
A scenario runner that introduces a failure (pause) to demonstrate fencing.
Let's refine the LeaseStore. It needs to increment the token only when the leader changes or the lease is newly acquired? If the same leader renews, the token shouldn't necessarily change unless we want to invalidate in-flight requests from the previous valid session?
Standard pattern: The fencing token is bound to the epoch of the leadership.
Leader A acquires lease -> Token 1.
Leader A renews lease -> Still Token 1.
Leader A loses lease.
Leader B acquires lease -> Token 2.
Leader A (zombie) writes with Token 1 -> Rejected.
Okay, the logic is:
Store holds (leader_id, expiry, token).
acquire(id):
If expired:
clear leader
If leader is None:
set leader = id
set expiry = now + ttl
increment token
return token
If leader == id:
set expiry = now + ttl
return token
If leader != id:
return fail
This looks correct.
Let's write the code.
Step 1: The Storage Service (Coordinator)
Simulates etcd/Consul. Thread-safe.
Step 2: The Fenced Resource
Simulates a database or file storage that prevents split-brain writes.
Step 3: The Client (Node)
Runs in a thread. Simulates a server in a specific region.
Step 4: The Demonstration
Node A starts. Becomes leader. Token 1. Writes successfully.
Node A "pauses" (simulation of GC or network partition).
Lease expires.
Node B starts. Becomes leader. Token 2. Writes successfully.
Node A wakes up. Tries to write with Token 1.
Resource rejects Node A.
This covers all requirements.
One detail: "Multi-region". In a single script, I can simulate this by passing a latency parameter to the "network" calls.
Let's polish the Python code. Use threading for concurrency.
Structure:
python
import threading
import time
import random
# ... Classes ...
if __name__ == "__main__":
# Setup
# Run
I will add comments explaining the "Fencing Token" mechanism specifically, as that's the most "interview-senior-engineer" part of this prompt.
Wait, is there a specific constraint on "Multi-region"?
Usually, this implies the storage backend itself is distributed, or we are building the client logic to handle it. Building a multi-region consensus store (like Spanner) is too big. I will assume the prompt asks for the pattern of using leader election with fencing, likely targeting a system like Cassandra (which supports lightweight transactions/leases) or just general architectural patterns. I will focus on the interaction pattern.
Final check on Fencing Tokens:
The resource must strictly check token > current_max_token.
The store must strictly increase token on new leadership acquisition.
Let's go.
This solution implements a robust Leader Election pattern using Leases for time-bound authority and Fencing Tokens to prevent "Split-Brain" scenarios (where a paused leader wakes up and writes to the resource).
We will build this in Python, simulating a distributed environment with threading.
Key Concepts
Lease: A time-limited lock. The leader must renew the lease periodically (heartbeats). If the leader crashes or the network partitions, the lease expires, allowing a new leader to take over.
Fencing Token: A monotonically increasing number (e.g., from a database sequence or a consensus store like Zookeeper/etcd). Every time a leader acquires a lease, it gets a new, higher token.
The Resource (Fencing Logic): The shared resource (e.g., a database or file) tracks the highest token it has seen. If a request arrives with a token lower than or equal to the stored one, it is rejected.
Implementation
We will create three components:
LeaseStore: Simulates a consensus store (like etcd/Redis/Zookeeper).
SharedResource: The critical section that accepts writes only from the valid leader.
Node: The worker that attempts to become leader and do work.
python
Detailed Walkthrough
1. The Fencing Mechanism (Why it works)
Look at the SharedResource.write method. It maintains a simple state: highest_token_seen.
Node-US-East acquires the lease. The store gives it Token 1.
Node-US-East enters a long GC pause (simulated by time.sleep).
The Lease Store sees that Node-US-East did not renew within TTL. It invalidates the lease.
Node-EU-West requests the lease. The store grants it Token 2.
Node-EU-West writes to the resource. The resource sees Token 2 > 0. It sets highest_token_seen = 2.
Node-US-East wakes up. It still thinks it is the leader (it has Token 1 in memory). It tries to write to the resource.
Rejection: The resource checks Token 1 <= Highest 2. The request is rejected.
This solves the Split-Brain problem without requiring complex checks on the leader side. The leader can be brain-dead, but the resource is safe.
2. The Lease Logic
The LeaseStore is the source of truth.
TTL (Time To Live): A lease is only valid for a few seconds.
Heartbeats: The leader must call try_acquire_lease repeatedly to extend the expiry timestamp.
Token Monotonicity: The token counter self.fencing_token_counter only increases. It never decreases, even if the store restarts (in a real system, this would be persisted or generated via a timestamp/epoch mechanism).
How to run this
This script requires standard Python 3 libraries (threading, time, random). No pip install is needed.
Save the code to leader_election.py.
Run python leader_election.py.
Observe the logs. You will see nodes successfully writing, and occasionally, a "RESUMED" node trying to write with an old token and getting REJECTED.
Production Considerations
If you are building this for a real production system (e.g., Kubernetes, distributed databases):
Consensus Store: Do not implement your own LeaseStore. Use etcd, Consul, or Zookeeper. They handle the distributed consensus (Raft/ZAB) for you.
Etcd Example: Use a key with a lease (TTL). The revision of the key creation serves as the fencing token.
Redis Example: Use RedLock. Be careful with Redis time drift; fencing tokens are harder to implement strictly in Redis without Lua scripts or strict monotonic counters.
Clock Skew: This solution does not rely on synchronized clocks for correctness (only for TTL duration estimation, which is safe). Fencing tokens rely on counters, not timestamps.
Database Support: Modern databases often support fencing natively.
HBase/Bigtable: Check-and-Put operations based on a timestamp or version.
import threading
import time
import uuid
import random
from dataclasses import dataclass
from typing import Optional
# ==========================================
# 1. Infrastructure Simulation
# ==========================================
@dataclass
class Lease:
holder_id: str
expiry: float
fencing_token: int
class LeaseStore:
"""
Simulates a distributed consensus store (e.g., etcd, Zookeeper, Consul).
It manages the lease and generates strictly increasing fencing tokens.
"""
def __init__(self):
self.lock = threading.Lock()
self.current_lease: Optional[Lease] = None
self.fencing_token_counter = 0
def try_acquire_lease(self, node_id: str, ttl_seconds: float) -> Optional[int]:
"""
Atomically attempts to acquire or renew the lease.
Returns the new Fencing Token if successful, None otherwise.
"""
with self.lock:
now = time.time()
# Check if lease is expired or held by the requester
if self.current_lease is None or self.current_lease.expiry < now:
# Generate new token
self.fencing_token_counter += 1
new_token = self.fencing_token_counter
# Create new lease
self.current_lease = Lease(
holder_id=node_id,
expiry=now + ttl_seconds,
fencing_token=new_token
)
return new_token
# If held by same node (renewal), keep token but extend expiry
# Note: Some implementations return a new token on every renewal.
# Here we keep it simple: Token only changes on Leadership change.
if self.current_lease.holder_id == node_id:
self.current_lease.expiry = now + ttl_seconds
return self.current_lease.fencing_token
# Held by someone else
return None
def get_current_info(self):
with self.lock:
if self.current_lease and self.current_lease.expiry > time.time():
return self.current_lease.holder_id, self.current_lease.fencing_token
return None, 0
class SharedResource:
"""
Represents the protected resource (e.g., a Database, Message Queue, or File).
It enforces the Fencing Token logic.
"""
def __init__(self, name: str):
self.name = name
self.lock = threading.Lock()
self.highest_token_seen = 0
self.last_writer = "None"
def write(self, data: str, fencing_token: int, writer_id: str):
"""
Writes data ONLY if the fencing token is strictly greater
than the highest token seen so far.
"""
with self.lock:
print(f"[{self.name}] Write Req: Node={writer_id}, Token={fencing_token} (Highest: {self.highest_token_seen})")
if fencing_token <= self.highest_token_seen:
print(f" ❌ REJECTED! Stale token. Node {writer_id} is a zombie leader.")
return False
# Accept the write
self.highest_token_seen = fencing_token
self.last_writer = writer_id
print(f" ✅ SUCCESS! Data written by {writer_id}.")
return True
# ==========================================
# 2. The Node Logic
# ==========================================
class Node(threading.Thread):
def __init__(self, node_id: str, store: LeaseStore, resource: SharedResource, region: str):
super().__init__(daemon=True)
self.node_id = node_id
self.store = store
self.resource = resource
self.region = region
self.running = True
# Lease management
self.lease_ttl = 2.0
self.current_token = 0
# Simulation specific
self.processing_delay = random.uniform(0.1, 0.3) # Simulate network/processing latency
def run(self):
print(f"[{self.node_id}] Started in {self.region}")
while self.running:
# 1. Attempt to acquire/renew lease
token = self.store.try_acquire_lease(self.node_id, self.lease_ttl)
if token:
# We are the leader (or renewed)
self.current_token = token
self.do_leader_work()
else:
# We are a follower
self.do_follower_work()
time.sleep(self.lease_ttl / 3) # Heartbeat loop
def do_leader_work(self):
# Simulate a "Stop-The-World" GC pause or network partition
# This creates the Zombie Leader scenario
if random.random() < 0.05: # 5% chance to glitch
print(f"[{self.node_id}] ⚠️ LEADER PAUSED (Simulated GC/Partition)...")
time.sleep(self.lease_ttl * 2.5) # Sleep longer than TTL
print(f"[{self.node_id}] 🤖 LEADER RESUMED (Unaware of eviction)")
# Attempt to write to resource
self.resource.write(f"Payload from {self.node_id}", self.current_token, self.node_id)
def do_follower_work(self):
# Just waiting
pass
# ==========================================
# 3. Running the Simulation
# ==========================================
def run_simulation():
print("=== Starting Multi-Region Leader Election Simulation ===")
# Shared Infrastructure
store = LeaseStore()
resource = SharedResource("Global-DB")
# Nodes in different "Regions"
nodes = [
Node("Node-US-East", store, resource, "US-East"),
Node("Node-EU-West", store, resource, "EU-West"),
Node("Node-AP-South", store, resource, "AP-South")
]
for n in nodes:
n.start()
# Let it run for a bit
time.sleep(10)
print("\n=== Simulation Ended ===")
if __name__ == "__main__":
run_simulation()