Heartbeat Mechanism
Heartbeat Mechanism
Heartbeats are periodic signals indicating a node is alive and functioning.
How Heartbeats Work
Leader → Heartbeat → Follower
Leader ← Ack ← Follower
If no heartbeat within timeout:
- Node considered dead
- Trigger failover/re-election
Implementation
import threading
import time
class HeartbeatSender:
def __init__(self, interval=5):
self.interval = interval
self.running = False
def start(self, callback):
self.running = True
def loop():
while self.running:
callback()
time.sleep(self.interval)
thread = threading.Thread(target=loop, daemon=True)
thread.start()
def stop(self):
self.running = False
class HeartbeatReceiver:
def __init__(self, timeout=15):
self.timeout = timeout
self.last_heartbeat = time.time()
self.lock = threading.Lock()
def receive(self):
with self.lock:
self.last_heartbeat = time.time()
def is_alive(self):
with self.lock:
return (time.time() - self.last_heartbeat) < self.timeout
Heartbeat Patterns
| Pattern | Description | Use Case |
|---|---|---|
| Ping-Pong | Request-response | Simple health check |
| One-way | Unidirectional | Low overhead |
| Gossip | Peer-to-peer | Large clusters |
| Centralized | To coordinator | Simple topology |
Failure Detection
Failure Detection
Detection Methods
1. Timeout-based:
- Miss N heartbeats = failure
- Simple, common
2. Quorum-based:
- Multiple nodes agree
- More accurate
3. Phi Accrual:
- Probabilistic detection
- Adaptive threshold
Implementation
class FailureDetector:
def __init__(self, phi_threshold=8):
self.phi_threshold = phi_threshold
self.heartbeats = []
def heartbeat(self):
self.heartbeats.append(time.time())
# Keep last 100 heartbeats
if len(self.heartbeats) > 100:
self.heartbeats.pop(0)
def phi(self):
"""Calculate phi (probability of failure)"""
if len(self.heartbeats) < 2:
return 0
# Calculate inter-arrival times
intervals = [
self.heartbeats[i+1] - self.heartbeats[i]
for i in range(len(self.heartbeats) - 1)
]
# Mean interval
mean = sum(intervals) / len(intervals)
# Time since last heartbeat
elapsed = time.time() - self.heartbeats[-1]
# Phi = -log10(P_later)
# P_later = e^(-elapsed/mean)
p_later = math.exp(-elapsed / mean)
phi = -math.log10(p_later)
return phi
def is_failed(self):
return self.phi() > self.phi_threshold
Detection Accuracy
| Method | False Positives | False Negatives | Complexity |
|---|---|---|---|
| Timeout | High | Low | Low |
| Quorum | Low | Low | Medium |
| Phi Accrual | Low | Low | High |
Timeout Configuration
Timeout Configuration
Configuration Parameters
1. Heartbeat Interval:
- How often to send heartbeat
- Typical: 1-5 seconds
2. Failure Timeout:
- How long to wait before declaring dead
- Typical: 10-30 seconds
3. Retry Interval:
- How often to retry failed nodes
- Typical: 5-10 seconds
Configuration Example
heartbeat:
interval: 3s # Send every 3 seconds
timeout: 15s # Declare dead after 15s
retry_interval: 5s # Retry every 5 seconds
max_missed: 5 # Miss 5 = failure
Timing Diagram
Sender: |--H--|--H--|--H--|--H--|--H--|--X--|--X--
Receiver: |--R--|--R--|--R--|--R--| | |
↑ ↑ ↑
Start Last OK Timeout
(dead)
Guidelines
| Scenario | Interval | Timeout |
|---|---|---|
| LAN | 1s | 5-10s |
| WAN | 3-5s | 15-30s |
| Cloud | 1-3s | 10-20s |
| High-latency | 5-10s | 30-60s |
Best Practices
- Interval < Timeout/3 (detect before timeout)
- Account for network latency
- Use phi accrual for adaptive detection
- Monitor false positive rate
- Adjust based on conditions
Practice Problems
Design a scalable Heartbeats system. Cover high-level architecture, data model, and API design.
Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliabilityHow would you scale Heartbeats to handle 10x the current load? Identify bottlenecks and solutions.
Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decompositionAnalyze potential failure modes for Heartbeats and design mitigation strategies.
Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradationQuiz
1. What is the purpose of heartbeats?
2. When is a node considered failed?
3. What is Phi Accrual failure detection?
4. What is the guideline for heartbeat interval vs timeout?
5. Why use heartbeats in leader election?
Flashcards
Question
What are heartbeats?
Click to reveal answer
Answer
Periodic signals from a node indicating it is alive and functioning properly
Question
When is node considered failed?
Click to reveal answer
Answer
After missing heartbeats within configured timeout period (e.g., 5 missed × 3s = 15s timeout)
Question
What is Phi Accrual detection?
Click to reveal answer
Answer
Probabilistic failure detection that calculates phi (probability of failure) with adaptive threshold
Question
Heartbeat interval vs timeout?
Click to reveal answer
Answer
Interval < Timeout/3 to detect failure before timeout expires
Question
Heartbeat pattern for large clusters?
Click to reveal answer
Answer
Gossip protocol - peer-to-peer heartbeats that propagate through the cluster
Revision Notes
Key Takeaways
- 1.Heartbeats indicate node is alive and functioning
- 2.Node considered failed after missing heartbeats within timeout
- 3.Phi Accrual provides probabilistic detection
- 4.Interval should be less than Timeout/3
- 5.Heartbeats trigger leader re-election on failure
Interview Tips
- •Explain heartbeat mechanism and timeout
- •Discuss Phi Accrual vs simple timeout
- •Give guidelines for interval/timeout configuration
- •Mention heartbeat role in leader election
Cheat Sheet
Cheat Sheet: Heartbeats
Mechanism
- Periodic alive signals
- Detect node failure
- Trigger failover
Detection Methods
- Timeout: Simple, binary
- Quorum: Multiple agree
- Phi Accrual: Probabilistic
Configuration
- Interval: 1-5s
- Timeout: 10-30s
- Interval < Timeout/3
Patterns
- Ping-Pong
- One-way
- Gossip (large clusters)
- Centralized