Skip to main content

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?
The Cassandra Answer: A combination of gossip protocol (inspired by epidemiology), Phi Accrual Failure Detection, hinted handoff, read repair, anti-entropy repair, and sophisticated multi-DC replication strategies. This module explores each of these mechanisms in depth.

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:
  1. Increments its heartbeat counter (local version number)
  2. Selects 1-3 random nodes to gossip with
  3. 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)
  4. Receives GossipDigestAck with updates
  5. Applies newer information to its local state

Gossip Data Structures

Gossip Round Example

Let’s trace a gossip round between three nodes: Initial State:
Step 1: Node A increments its heartbeat and picks B to gossip with
Step 2: B compares with its state and responds
Step 3: A updates its state
Step 4: A sends GossipDigestAck2 with its newer info
Step 5: B updates its state
Result: After just one round, nodes A and B have converged on the latest information about A and B, and A learned newer info about C.

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
The number of nodes that know about a new piece of information grows exponentially:
General Formula: After r rounds, approximately min(f^r, N) nodes know the information. Example: In a 1000-node cluster with fanout=3:
  • 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)
So information propagates to all 1000 nodes in about 5 seconds (log₃(1000) rounds).

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.
Important Characteristics:
  • 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
Common Misconception: Seeds are masters or leaders. False! They’re just stable contact points for gossip initialization.

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:
  1. Track Arrival Times: Record when gossip heartbeats arrive from each node
  2. Build a Statistical Model: Use a sliding window (default: last 1000 heartbeats) to model the expected inter-arrival time
  3. Calculate Phi (Φ): When a heartbeat is late, calculate how suspicious this is:
Where:
  • t = time since last heartbeat
  • P(T > t) = probability that inter-arrival time exceeds t
  • Φ = suspicion level
  1. 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)
Timeline:

Implementation Details

Configuring Failure Detection

Tuning Advice:
  • 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:
Example Hint:

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 Exceeded
Scenario 2: Coordinator Crashes
Scenario 3: Hint Storage Full
Key Insight: Hints are a temporary bridge, not a replacement for repair!

Monitoring 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 fixes inconsistencies by comparing replicas during reads.

Read Repair Types

Cassandra has two types of read repair:
  1. Blocking Read Repair (Foreground)
  2. Background Read Repair

1. Blocking Read Repair (Foreground)

Happens automatically when you read with a consistency level that queries multiple replicas. Example: Read with CL=QUORUM (RF=3)
Key Points:
  • 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:
Why probabilistic?
  • Performance: Full comparison on every read is expensive
  • Traffic: Increases network and CPU overhead
  • Tunable: Higher for critical data, lower for less important data
Default Values (Cassandra 3.0+):
  • read_repair_chance = 0.0 (disabled)
  • dclocal_read_repair_chance = 0.1 (10%)
Modern Best Practice: Rely on repair, not read repair, for consistency. Use read_repair_chance = 0.0.

Read Repair Algorithm

2. Background Read Repair

Purpose: Repair data that wasn’t queried in the read request. Example:
Blocking read repair only compares and repairs name and email columns. Background read repair compares and repairs all columns, running asynchronously:
Configuration:

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
Problem: Unread data can drift indefinitely! Solution: Anti-entropy repair - actively compare all data across replicas.

The Repair Process Overview

Merkle Trees Explained

A Merkle tree (hash tree) allows efficient comparison of large datasets. Structure:
How It Works:
  1. Divide token range into segments (default: 2^15 = 32,768 segments)
  2. Hash each segment’s data (all rows in that token range)
  3. Build tree by hashing pairs of hashes upward
  4. Compare trees from root down
Example Comparison:
Analysis:
  • 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
Efficiency: Instead of comparing millions of rows, we compare ~30K hashes!

Merkle Tree Building

Running Repair

Full Repair (all data):
Repair Specific Keyspace:
Repair Specific Table:
Incremental Repair (only unrepaired data):
Repair Specific Token Range:

Repair Output Example

Full vs. Incremental Repair

Full Repair:
  • Compares all data every time
  • Expensive for large datasets
  • Use when: major inconsistency suspected
Incremental Repair (Cassandra 2.2+):
  • Marks SSTables as “repaired” after successful repair
  • Only repairs unrepaired SSTables on subsequent runs
  • Much faster for ongoing maintenance
  • Requires special compaction strategy
Enable Incremental Repair:

Repair Scheduling

Best Practice: Run repair within gc_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:
Bad Timeline:
Automated Scheduling: Use cassandra-reaper (open source tool):
Or simple cron:

Repair Performance Impact

Repair is resource-intensive: Mitigation Strategies:
  1. Repair During Off-Peak Hours
  1. Limit Repair Parallelism
  1. Throttle Streaming
  1. Use Sub-Range Repair

Part 6: Multi-Datacenter Replication

Why Multiple Datacenters?

  1. Geographic Distribution: Serve users with low latency worldwide
  2. Disaster Recovery: Survive datacenter failures
  3. Compliance: Keep data in specific regions (GDPR, etc.)
  4. 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):
2. Use NetworkTopologyStrategy:

Multi-DC Replica Placement

With NetworkTopologyStrategy, Cassandra ensures:
  • Replicas are spread across different racks within a DC
  • Each DC gets the specified number of replicas
Example: Token range [0, 100) with RF={us-east:3, eu-west:2}
Visual:

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 with CL=LOCAL_QUORUM, RF={us-east:3, eu-west:2}
Key Points:
  • 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 with CL=LOCAL_QUORUM, RF={us-east:3, eu-west:2}
No cross-DC communication for reads with LOCAL_* consistency!

Multi-DC Repair

Repair operates per-DC by default:
Best Practice: Run per-DC repairs regularly, cross-DC repairs less frequently.

Monitoring Multi-DC Clusters


Part 7: Cluster Management Operations

Adding a Node (Bootstrap)

Process:
  1. Install Cassandra on new node
  2. Configure cassandra.yaml:
  3. Start Cassandra:
  4. Bootstrap Process:
Timeline:
Monitor Bootstrap:

Decommissioning a Node

Purpose: Safely remove a node from the cluster Process:
What Happens:
Timeline:
Never Just Kill the Node! Decommission ensures data isn’t lost.

Replacing a Dead Node

Scenario: Node crashed and can’t be recovered (hardware failure) Process:
  1. Prepare new node with same IP (or use replace_address)
  2. Configure cassandra.yaml:
  3. Start new node:
  4. Streaming:
  5. Remove replace_address and restart:

Monitoring Cluster Health

Real-time Status:
Key Metrics to Monitor:

Part 8: Hands-On Exercises

Exercise 1: Observe Gossip Propagation

Setup: 3-node cluster Task:
  1. Monitor gossip on Node A: watch -n 1 nodetool gossipinfo
  2. On Node B, change schema: ALTER TABLE users ADD phone text;
  3. Observe SCHEMA state propagate through gossip
  4. Measure propagation time
Expected: Schema UUID updates across all nodes within 1-3 seconds

Exercise 2: Test Failure Detection

Task:
  1. Monitor failure detector: watch -n 1 nodetool failuredetector
  2. Pause Node B: nodetool pausehandoff
  3. Simulate network delay: sudo tc qdisc add dev eth0 root netem delay 500ms
  4. Watch Phi values rise
  5. Remove delay: sudo tc qdisc del dev eth0 root
  6. Watch Phi values drop
Question: At what Phi value did the node get marked as DOWN?

Exercise 3: Hinted Handoff

Scenario: Test hint storage and replay Steps:

Exercise 4: Read Repair in Action

Setup:
Create Inconsistency:
Trigger Read Repair:
Expected: Both nodes now have the same data (newest timestamp wins)

Exercise 5: Run Repair and Analyze

Task:
Questions:
  • 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:
Test Consistency Levels:
Question: Is the data visible in DC2 immediately? Why or why not? Test EACH_QUORUM:
Question: How does write latency compare to LOCAL_QUORUM?

Exercise 7: Simulate Node Failure and Recovery

Scenario: Test complete failure recovery workflow Steps:
  1. Create baseline data:
  2. Stop Node C:
  3. Continue writes (hints accumulate):
  4. Restart Node C after 5 hours (exceeds hint window):
  5. Check for missing data:
  6. Run repair:
  7. 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)
Strategy 2: Per-Node Repair (Large Clusters)
Strategy 3: Incremental Repair

Gossip Tuning

High Latency Networks (cross-region):
Very Large Clusters (500+ nodes):

Multi-DC Best Practices

1. Use LOCAL Consistency Levels
2. Configure Snitches Correctly
3. Set DC-Aware Load Balancing (driver config):
4. Separate Seeds Per DC

Monitoring Checklist


Part 10: Common Issues and Debugging

Issue 1: Gossip Not Propagating

Symptoms:
  • Nodes don’t see schema changes
  • nodetool describecluster shows different schema versions
Diagnosis:
Solutions:

Issue 2: False Failure Detection

Symptoms:
  • Nodes marked as DOWN when actually healthy
  • Logs show: FatClient ... has been silent for 30000ms, removing from gossip
Diagnosis:
Solutions:

Issue 3: Hints Accumulating

Symptoms:
  • Disk space filling up
  • /var/lib/cassandra/hints/ directory growing
Diagnosis:
Solutions:

Issue 4: Repair Taking Too Long

Symptoms:
  • Repair runs for days
  • High CPU and disk I/O
Diagnosis:
Solutions:

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
Failure Detection:
  • Phi Accrual: suspicion level, not binary
  • Phi = 8 (default) = 99.999% confidence node is down
  • Adapts to network conditions
  • Configurable via phi_convict_threshold
Hinted Handoff:
  • Temporary solution for node failures
  • Stored locally on coordinator
  • Max window: 3 hours (default)
  • Not a replacement for repair!
Read Repair:
  • Fixes data queried in reads
  • Foreground (blocking) + Background (async)
  • Probabilistic (10% by default)
  • Limited scope
Anti-Entropy Repair:
  • Compares all data using Merkle trees
  • Essential for consistency
  • Must run within gc_grace_seconds
  • Resource-intensive
Multi-DC:
  • NetworkTopologyStrategy for replication
  • LOCAL_* consistency for low latency
  • Asynchronous cross-DC replication
  • Per-DC repair recommended
Cluster Operations:
  • 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