Cluster Operations & Multi-DC Replication
Module Duration: 8-10 hours
Learning Style: Deep Technical + Hands-On Operations + Production Scenarios
Outcome: Understand how Cassandra maintains cluster health, detects failures, and operates across datacenters
Introduction: The Challenge of Distributed Coordination
In a distributed database like Cassandra with potentially hundreds of nodes spread across multiple datacenters, how do nodes:- Discover each other and know who’s in the cluster?
- Detect when a node fails or becomes unreachable?
- Ensure data remains consistent across replicas?
- Handle network partitions gracefully?
- Replicate data across geographic regions?
Part 1: The Gossip Protocol
What is Gossip?
Gossip is a peer-to-peer communication protocol inspired by how rumors spread in social networks or diseases spread through populations. In Cassandra, nodes exchange information about themselves and other nodes they know about. Key Characteristics:- Decentralized: No master node orchestrating communication
- Eventually Consistent: Information propagates gradually
- Fault Tolerant: Works even when some nodes are down
- Scalable: Overhead doesn’t increase linearly with cluster size
The Gossip Mechanism
Every 1 second, each node:- Increments its heartbeat counter (local version number)
- Selects 1-3 random nodes to gossip with
- Sends a GossipDigestSyn message containing:
- Endpoint states for all known nodes
- Generation numbers (when node was started)
- Heartbeat versions (how recently we heard from each node)
- Receives GossipDigestAck with updates
- Applies newer information to its local state
Gossip Data Structures
Gossip Round Example
Let’s trace a gossip round between three nodes: Initial State:Gossip Propagation Speed
How quickly does information spread through gossip? Mathematical Model:- Cluster size: N nodes
- Gossip fanout: f nodes per round (typically 3)
- Gossip interval: 1 second
- Round 1: ~4 nodes know
- Round 2: ~16 nodes know
- Round 3: ~64 nodes know
- Round 4: ~256 nodes know
- Round 5: ~1000 nodes know (full propagation)
Seed Nodes
Problem: When a new node joins, how does it know who to gossip with initially? Solution: Seed nodes - well-known nodes that new nodes contact first.- Seeds are not special after bootstrap - just initial contact points
- Every datacenter should have at least one seed
- A node should not list itself as a seed
- Seeds don’t form a special “seed cluster” - they’re regular nodes
- Seeds just need to be reliable and long-lived
Monitoring Gossip
You can observe gossip in action:Part 2: Failure Detection
The Challenge
How do you determine if a node is down vs. just slow or experiencing network delays? Naive Approach: Use a fixed timeout (e.g., “no response in 5 seconds = dead”) Problems:- Too short: false positives during network hiccups
- Too long: slow to detect real failures
- Network latency varies over time
- Different nodes have different performance characteristics
Phi Accrual Failure Detector
Cassandra uses the Phi (Φ) Accrual Failure Detector, which provides a suspicion level rather than a binary up/down decision. Key Idea: Instead of “is this node down?”, ask “how confident am I that this node is down?” The Algorithm:- Track Arrival Times: Record when gossip heartbeats arrive from each node
- Build a Statistical Model: Use a sliding window (default: last 1000 heartbeats) to model the expected inter-arrival time
- Calculate Phi (Φ): When a heartbeat is late, calculate how suspicious this is:
t= time since last heartbeatP(T > t)= probability that inter-arrival time exceedst- Φ = suspicion level
- Make Decision: If Φ exceeds threshold (default: 8), mark node as down
Understanding Phi Values
Phi = 8 means: “There’s a 0.00001% chance I’m wrong about this node being down”
Phi Calculation Example
Let’s trace a failure detection scenario: Setup:- Node A monitoring Node B
- Historical heartbeat intervals: 1.0s, 1.1s, 0.9s, 1.2s, 1.0s (mean ≈ 1.04s, σ ≈ 0.11s)
Implementation Details
Configuring Failure Detection
- High-latency networks (cross-region): Increase to 10-12
- Low-latency networks (single DC): Can decrease to 6-7
- Flaky networks: Increase to avoid false positives
- Mission-critical availability: Decrease for faster failover
Observing Failure Detection
Part 3: Hinted Handoff (Detailed)
We introduced hinted handoff in the write path module. Let’s dive deeper into its implementation and edge cases.The Detailed Write Flow with Hints
Hint Storage Format
Hints are stored locally on the coordinator node in a special system table:Hint Replay
The coordinator continuously tries to replay hints:Hint Lifecycle Timeline
Hint Configuration
When Hints Are NOT Enough
Hints are best-effort only. They fail in these scenarios: Scenario 1: Max Hint Window ExceededMonitoring Hints
Part 4: Read Repair
The Problem
Even with hinted handoff, replicas can diverge:- Hints were dropped (too old)
- Coordinator crashed before replaying hints
- Network partitions prevented writes from reaching some replicas
Read Repair Types
Cassandra has two types of read repair:- Blocking Read Repair (Foreground)
- Background Read Repair
1. Blocking Read Repair (Foreground)
Happens automatically when you read with a consistency level that queries multiple replicas. Example: Read withCL=QUORUM (RF=3)
- Repair happens synchronously (blocks the read)
- Client gets the newest data
- Divergent replicas are fixed immediately
- Only repairs data actually requested in the query
Read Repair Probability
Not every read triggers repair! There’s a configurable probability:- Performance: Full comparison on every read is expensive
- Traffic: Increases network and CPU overhead
- Tunable: Higher for critical data, lower for less important data
read_repair_chance = 0.0(disabled)dclocal_read_repair_chance = 0.1(10%)
read_repair_chance = 0.0.
Read Repair Algorithm
2. Background Read Repair
Purpose: Repair data that wasn’t queried in the read request. Example:name and email columns.
Background read repair compares and repairs all columns, running asynchronously:
Read Repair Monitoring
Part 5: Anti-Entropy Repair (The Big One)
Why We Need Repair
Neither hinted handoff nor read repair is sufficient:- Hints: Expire after max_hint_window, lost if coordinator crashes
- Read repair: Only fixes data that’s queried
The Repair Process Overview
Merkle Trees Explained
A Merkle tree (hash tree) allows efficient comparison of large datasets. Structure:- Divide token range into segments (default: 2^15 = 32,768 segments)
- Hash each segment’s data (all rows in that token range)
- Build tree by hashing pairs of hashes upward
- Compare trees from root down
- Root hashes differ → trees are different
- Left subtree hashes match → left half is identical (skip!)
- Right subtree hashes differ → need to check further
- Leaf hashes 0xCCCC vs 0xXXXX differ → stream segment 3
- Leaf hashes 0xDDDD vs 0xYYYY differ → stream segment 4
Merkle Tree Building
Running Repair
Full Repair (all data):Repair Output Example
Full vs. Incremental Repair
Full Repair:- Compares all data every time
- Expensive for large datasets
- Use when: major inconsistency suspected
- Marks SSTables as “repaired” after successful repair
- Only repairs unrepaired SSTables on subsequent runs
- Much faster for ongoing maintenance
- Requires special compaction strategy
Repair Scheduling
Best Practice: Run repair withingc_grace_seconds (default: 10 days)
Why? Cassandra uses tombstones to mark deleted data. If a replica is down longer than gc_grace_seconds, tombstones can be garbage collected, and deleted data might “resurrect.”
Timeline:
cassandra-reaper (open source tool):
Repair Performance Impact
Repair is resource-intensive:
Mitigation Strategies:
- Repair During Off-Peak Hours
- Limit Repair Parallelism
- Throttle Streaming
- Use Sub-Range Repair
Part 6: Multi-Datacenter Replication
Why Multiple Datacenters?
- Geographic Distribution: Serve users with low latency worldwide
- Disaster Recovery: Survive datacenter failures
- Compliance: Keep data in specific regions (GDPR, etc.)
- Read Scalability: Read from local DC, reduce cross-DC traffic
Network Topology
Cassandra models datacenters and racks:Configuring Datacenters
1. Define Topology (cassandra-rackdc.properties):Multi-DC Replica Placement
WithNetworkTopologyStrategy, Cassandra ensures:
- Replicas are spread across different racks within a DC
- Each DC gets the specified number of replicas
[0, 100) with RF={us-east:3, eu-west:2}
Multi-DC Consistency Levels
New consistency levels for multi-DC:
Example: Keyspace with RF={us-east:3, eu-west:3}
Multi-DC Write Flow
Scenario: Client in us-east writes withCL=LOCAL_QUORUM, RF={us-east:3, eu-west:2}
- Local writes are fast (no cross-DC latency in critical path)
- Remote writes happen asynchronously
- Eventual consistency across DCs
Multi-DC Read Flow
Scenario: Client in eu-west reads withCL=LOCAL_QUORUM, RF={us-east:3, eu-west:2}
LOCAL_* consistency!
Multi-DC Repair
Repair operates per-DC by default:Monitoring Multi-DC Clusters
Part 7: Cluster Management Operations
Adding a Node (Bootstrap)
Process:- Install Cassandra on new node
-
Configure cassandra.yaml:
-
Start Cassandra:
-
Bootstrap Process:
Decommissioning a Node
Purpose: Safely remove a node from the cluster Process:Replacing a Dead Node
Scenario: Node crashed and can’t be recovered (hardware failure) Process:-
Prepare new node with same IP (or use
replace_address) -
Configure cassandra.yaml:
-
Start new node:
-
Streaming:
-
Remove replace_address and restart:
Monitoring Cluster Health
Real-time Status:Part 8: Hands-On Exercises
Exercise 1: Observe Gossip Propagation
Setup: 3-node cluster Task:- Monitor gossip on Node A:
watch -n 1 nodetool gossipinfo - On Node B, change schema:
ALTER TABLE users ADD phone text; - Observe SCHEMA state propagate through gossip
- Measure propagation time
Exercise 2: Test Failure Detection
Task:- Monitor failure detector:
watch -n 1 nodetool failuredetector - Pause Node B:
nodetool pausehandoff - Simulate network delay:
sudo tc qdisc add dev eth0 root netem delay 500ms - Watch Phi values rise
- Remove delay:
sudo tc qdisc del dev eth0 root - Watch Phi values drop
Exercise 3: Hinted Handoff
Scenario: Test hint storage and replay Steps:Exercise 4: Read Repair in Action
Setup:Exercise 5: Run Repair and Analyze
Task:- How long did Merkle tree building take?
- How much data was streamed?
- Which token ranges had differences?
Exercise 6: Multi-DC Consistency
Setup: 2-DC cluster Create Keyspace:Exercise 7: Simulate Node Failure and Recovery
Scenario: Test complete failure recovery workflow Steps:-
Create baseline data:
-
Stop Node C:
-
Continue writes (hints accumulate):
-
Restart Node C after 5 hours (exceeds hint window):
-
Check for missing data:
-
Run repair:
-
Verify consistency:
Part 9: Production Best Practices
Repair Schedules
Recommendation: Repair every 7 days (within gc_grace_seconds) Strategy 1: Full Cluster Repair (Small Clusters)Gossip Tuning
High Latency Networks (cross-region):Multi-DC Best Practices
1. Use LOCAL Consistency LevelsMonitoring Checklist
Part 10: Common Issues and Debugging
Issue 1: Gossip Not Propagating
Symptoms:- Nodes don’t see schema changes
nodetool describeclustershows different schema versions
Issue 2: False Failure Detection
Symptoms:- Nodes marked as DOWN when actually healthy
- Logs show:
FatClient ... has been silent for 30000ms, removing from gossip
Issue 3: Hints Accumulating
Symptoms:- Disk space filling up
/var/lib/cassandra/hints/directory growing
Issue 4: Repair Taking Too Long
Symptoms:- Repair runs for days
- High CPU and disk I/O
Summary & Key Takeaways
Gossip Protocol:- Peer-to-peer state propagation
- Exponential spread: log(N) rounds to full propagation
- Seeds are just initial contact points
- Runs every 1 second
- Phi Accrual: suspicion level, not binary
- Phi = 8 (default) = 99.999% confidence node is down
- Adapts to network conditions
- Configurable via
phi_convict_threshold
- Temporary solution for node failures
- Stored locally on coordinator
- Max window: 3 hours (default)
- Not a replacement for repair!
- Fixes data queried in reads
- Foreground (blocking) + Background (async)
- Probabilistic (10% by default)
- Limited scope
- Compares all data using Merkle trees
- Essential for consistency
- Must run within
gc_grace_seconds - Resource-intensive
NetworkTopologyStrategyfor replicationLOCAL_*consistency for low latency- Asynchronous cross-DC replication
- Per-DC repair recommended
- Bootstrap: Automated, streams data
- Decommission: Safe node removal
- Replace: For dead node recovery
- Never just kill nodes!
What’s Next?
Module 6: Performance Tuning & Production Operations
JVM tuning, monitoring, troubleshooting, and running Cassandra in production at scale