Shard Rebalancing, Operations, and High Availability
14 min read
Welcome back to the trenches of distributed databases.
In earlier modules, you learned how to slice your data into shards like a master sushi chef. But here is the brutal reality of production systems: data does not stay balanced, hardware is allergic to staying alive, and users refuse to stop sending writes while you reorganize the cluster.
When your primary shard hits 92% disk utilization at 2:00 AM on Black Friday, you cannot just run ALTER TABLE or take a 6-hour maintenance window. You need to split shards while accepting thousands of queries per second, restore multi-terabyte clusters to a consistent millisecond in time without generating "phantom money," and monitor 64+ database nodes without going deaf from PagerDuty alerts.
Let's dive into day-two operations for sharded architectures.
1. Live Data Migration and Zero-Downtime Shard Splitting
The Definition and Problem Statement
What it is: Shard Splitting is the process of taking an existing shard whose data range is too large or hot (e.g., IDs
[0, 1_000_000)) and partitioning it across two or more new physical shards (e.g.,Shard A: [0, 500_000)andShard B: [500_000, 1_000_000)).The Problem: Moving 500 GB of live data takes time—often hours over network interfaces. If writes continue landing on the original shard while you copy rows, the new shards will be instantly stale. Conversely, if you lock the database for writes during the copy, you cause an immediate customer-facing outage.
BEFORE SPLIT
+------------------------+
| Shard 1: [A - Z) | <-- Maxed out IOPS & Storage
+------------------------+
|
(Live Split via CDC / Dual-Replication)
v
AFTER SPLIT
+-----------------------+ +-----------------------+
| Shard 1A: [A - M) | | Shard 1B: [M - Z) |
+-----------------------+ +-----------------------+The Industry Standard: The 4-Phase Dual-Replication Pattern
Modern distributed engines (like Vitess with VReplication, CockroachDB range-splitting, or Citus data movement) avoid downtime by treating shard splitting as an asynchronous continuous synchronization with an atomic cutover [1, 2].
[Phase 1: Seed Snapshot] ───► [Phase 2: Catch-Up (CDC)] ───► [Phase 3: Atomic Cutover] ───► [Phase 4: Cleanup]
Copy historical data Tail Binlog / Changefeed Microsecond routing flip Decommission oldStep 1: Baseline Seed Snapshot
The system takes a point-in-time snapshot of the source shard without acquiring long-lived table locks (e.g., using PostgreSQL SNAPSHOT export or MySQL REPEATABLE READ snapshot). Data belonging to the target split range is copied over to the destination nodes.
Step 2: Change Data Capture (CDC) Catch-Up
While Step 1 copies raw bytes, live queries are still modifying the source shard. The destination shard subscribes to the source's Change Data Capture stream (MySQL Binlog, Postgres WAL, or MongoDB Oplog) [1, 3]:
- The target filters and executes incoming
INSERT,UPDATE, andDELETEstatements whereShardKey >= 'M' AND ShardKey < 'Z'. - As the backlog drains, replication lag approaches zero (typically under 100 milliseconds).
Step 3: Verification & The Microsecond Cutover
Once replication lag is negligible, an orchestrator (such as Vitess vtctld or Citus metadata coordinator) initiates cutover [1, 4]:
- Brief Routing Pause: The routing proxies (e.g., Vitess
vtgateor application connection pools) temporarily buffer incoming writes for the specific shard key range. - Drain Stream: Wait a few milliseconds for the target shard to consume the absolute latest CDC events.
- Metadata Update: Atomically update the routing directory (e.g., etcd, ZooKeeper, or the coordinator catalog) so queries pointing to range
[M - Z)point directly to Shard 1B. - Resume Writes: Unbuffer queries. The write pause lasts tens of milliseconds—completely unnoticeable to end users.
Example: Vitess VReplication Resharding Workflow
In modern production MySQL topologies running Vitess, resharding is managed declaratively via Reshard [1]:
# 1. Start resharding from 1 source shard to 2 target shards (-80, 80-)
vtctldclient Reshard --workflow customer_split customer/0 create --target-shards customer/-80,customer/80-
# 2. Check the difference between source and destination (Data Integrity Verification)
vtctldclient VDiff customer.customer_split create
# 3. Switch non-primary (replica/read) traffic first to test performance
vtctldclient Reshard --workflow customer_split customer switchtraffic --tablet-types replica,rdonly
# 4. Atomically switch primary (write) traffic (Microsecond write cutover)
vtctldclient Reshard --workflow customer_split customer switchtraffic --tablet-types primary
# 5. Clean up the old shard after verification
vtctldclient Reshard --workflow customer_split customer completeBoundaries and Scope: What Live Resharding CANNOT Do
- Zero Overhead is a Myth: Live copying 2 TB of data consumes disk read IOPS and network bandwidth. If Shard 1 was already running at 95% disk IOPS saturation, starting a migration can tip the shard over into request timeouts. Migrations must be throttled by an adaptive rate-limiter.
- Non-Splittable Foreign Keys: If you have tables with foreign keys that do not include the shard key, splitting a shard range across different nodes physically breaks foreign key constraints. Those constraints must be dropped or moved to the application layer prior to sharding.
2. Disaster Recovery, Distributed Backup, and Point-in-Time Recovery (PITR)
The Definition and Problem Statement
What it is: Distributed Disaster Recovery (DR) is the ability to restore an entire cluster of independent database shards to a state of transactional consistency across all nodes as of a precise moment in time .
The Problem: In a sharded database, running
pg_dumpor taking independent disk snapshots across 16 shards creates a Skewed Snapshot Disaster.
Imagine a banking app where Alice (on Shard 1) sends $500 to Bob (on Shard 2):
- 02:00:00 AM: Alice has $1,000; Bob has $0.
- 02:00:05 AM: Shard 1 finishes its backup. Alice's balance in the backup: $1,000.
- 02:00:06 AM: Alice transfers $500 to Bob. Shard 1 balance drops to $500; Shard 2 balance rises to $500.
- 02:00:10 AM: Shard 2 finishes its backup. Bob's balance in the backup: $500.
If you restore this cluster from these backups, the database now has $1,500 total. You just minted $500 out of thin air because the backups were not globally coordinated.
Time ──► 02:00:00 02:00:05 02:00:06 02:00:10
Shard 1: [Alice: $1000] ───► [BACKUP TAKEN] ──► [Sends $500] ──────► [Alice: $500]
($1000 saved)
Shard 2: [Bob: $0] ────────────────────────► [Receives $500] ──► [BACKUP TAKEN]
($500 saved)
---------------------------------------------------------------------------------------
Restored State: Alice has $1000, Bob has $500. Total = $1500 (Phantom Money Bug 💸)How the Industry Solves Distributed PITR
Approach A: The Hybrid Logical Clock (HLC) / Global Timestamp Method
Modern NewSQL engines (CockroachDB, Google Spanner, YugabyteDB) maintain a monotonic, synchronized timeline across all nodes using TrueTime (GPS + atomic clocks) or Hybrid Logical Clocks [5, 6].
Because every transaction across all shards is committed at an exact timestamp , backups are defined as a logical cut at that exact physical/logical tick:
-- CockroachDB distributed backup as of an exact timestamp
BACKUP DATABASE orders
INTO 's3://company-backups/cluster-01/2026-11-07/'
AS OF SYSTEM TIME '2026-11-07 02:00:00.000000+00:00';When restored, the engine discards any writes committed after that microsecond, ensuring zero cross-shard anomalies [6].
Approach B: Continuous Log Archiving with Distributed Checkpointing (Vitess / MySQL / Postgres)
In modular sharded systems running traditional RDBMS engines:
- Base Physical Backups: Nodes take physical backups (e.g., Percona XtraBackup or pgBackRest) from replica nodes to avoid impacting primaries [7].
- Continuous WAL / Binlog Streaming: Primaries ship their transaction logs to durable cloud storage (e.g., S3 or GCS) every few seconds [7].
- Global Checkpoint Token: To perform a cross-shard PITR, a central coordinator writes a heartbeat transaction containing a globally unique, monotonically increasing counter (
checkpoint_id) across all shards simultaneously via a 2-Phase Commit (2PC) or an event-bus sync. - Replay to Checkpoint: During recovery, each shard restores its physical base image and rolls forward its WAL/binlog, halting precisely at the designated
checkpoint_id.
PITR RECOVERY COORDINATION
Shard 1 Log: ... [Tx 101] [Tx 102] [CHECKPOINT_42] [Tx 105] ...
│
▼ (Halt Replay Here)
Shard 2 Log: ... [Tx 801] [Tx 802] [CHECKPOINT_42] [Tx 804] ...Boundaries and Scope: What Distributed DR Cannot Protect You From
- The "Speed of Light" Multi-Region Dilemma: If Shard 1 is in US-East and Shard 2 is in EU-Central, achieving a globally synchronous recovery point without distributed transactions introduces latency overheads (70–100ms per write). Most architectures accept an RPO (Recovery Point Objective) of a few seconds rather than forcing synchronous multi-region consistency for every write.
- Storage Cost Explosion: Storing base snapshots + 14 days of WAL logs across 64 shards means you are storing multiple petabytes in cloud storage. Distributed systems require strict log-retention policies and deduplicated storage tiers to avoid bankruptcy.
3. Shard Health Monitoring, Capacity Planning, and Alerting
The Definition and Problem Statement
What it is: Shard Observability and Capacity Management is the science of continuously tracking resource consumption across all independent partitions to detect imbalances before they cascade into cluster-wide outages.
The Problem: In a non-sharded database, you monitor one CPU metric, one disk metric, and one connection pool. In a 64-shard cluster, averages lie. If your cluster CPU average is a comfortable 22%, but Shard 14 is at 100% CPU due to a hot partition key, your entire application will experience cascading failures while your high-level dashboard glows green.
+--------------------------------------------------------------------+
| CLUSTER AVERAGE CPU: 22% (Everything looks fine! 🌴) |
+--------------------------------------------------------------------+
Shard 01: [== ] 20%
Shard 02: [= ] 10%
...
Shard 14: [==========!!] 100% <-- 💥 HOT SHARD CRASHING PRODUCTION
...
Shard 64: [= ] 15%Key Metrics You Must Track per Shard
| Metric Category | Metric Name | What It Means | Red Flag Threshold |
|---|---|---|---|
| Skew Metrics | Gini Coefficient of Storage/QPS | Statistical dispersion of data across shards (). | Gini means your sharding key is causing hot spots. |
| Replication | Replication Lag (Bytes / Seconds) | Time delay between the primary writing a transaction and the replica executing it. | Lag (triggers read-stale alerts or replica failover risks). |
| Cross-Shard Load | Scatter-Gather Ratio | Percentage of queries hitting multiple or all shards instead of routing to a single shard. | Ratio of total queries. (Indicates missing shard keys in WHERE clauses). |
| Resources | IOPS Read/Write Saturation | Percentage of provisioned EBS or NVMe IOPS being consumed per node. | Sustained IOPS (requires immediate splitting or rebalancing). |
| Connection Pooling | Route-to-Shard Pool Utilization | Active connections from proxy (e.g., PgBouncer, Envoy) to an individual shard. | Pool exhaustion (). Can lead to cascading queuing delays. |
Capacity Planning Formula: The Splitting Trigger
You must not wait until a shard reaches 90% disk capacity to trigger a rebalance. Moving a 1 TB shard over a 1 Gbps network connection can take hours:
If your shard is accumulating 50 GB of data an hour, waiting until 90% capacity guarantees your disk will hit 100% (causing read-only lockdown) before the data finishes migrating!
The Golden Rule of Shard Capacity Planning:
Where is your safety margin factor. In high-throughput architectures, shard splitting is automatically initiated when disk usage exceeds 70% or when projected growth exceeds headroom within a 7-day window.
Alerting: Defeating Alert Fatigue
If you create naive alerts like:ALERT ShardReplicationLagHigh IF replication_lag > 5s
When a network switch drops for 30 seconds, all 64 shards will page your on-call engineers simultaneously.
Production-Grade Prometheus Alert Rule (Grouped by Cluster)
Use Prometheus alerting rules that group alerts and alert on sustained anomalies and cluster-wide topology impact rather than individual blips [8]:
groups:
- name: database_shards_alerts
rules:
- alert: ShardStorageHotSpot
# Compare a single shard's size against the cluster median size
expr: |
(
db_shard_storage_bytes
- on(cluster) group_left()
topk(1, median(db_shard_storage_bytes) by (cluster))
) > 100 * 1024 * 1024 * 1024 # 100 GB heavier than median
for: 2h
labels:
severity: warning
annotations:
summary: "Shard {{ $labels.shard_id }} is experiencing severe data skew"
description: "Storage on shard {{ $labels.shard_id }} has deviated by >100GB from cluster median for 2 hours."
- alert: ShardCapacityEmergency
# Linear prediction: Will this shard run out of disk space in the next 48 hours?
expr: predict_linear(db_shard_disk_free_bytes[4h], 48 * 3600) < 0
for: 30m
labels:
severity: critical
annotations:
summary: "Shard {{ $labels.shard_id }} disk filling up fast"
description: "Based on 4-hour ingestion rate, shard {{ $labels.shard_id }} will exhaust disk within 48 hours. Trigger shard splitting immediately."Boundaries and Scope: What Automated Balancing Cannot Solve
- The "Key-Range Monolith" (Indivisible Keys): If 80% of your traffic belongs to a single celebrity user or tenant ID (e.g.,
tenant_id = 'shopify_super_store'), no amount of shard splitting can split that single key across multiple physical nodes without altering your underlying data model. Shard splitting splits ranges of keys, not individual hot keys. To fix a single hot key, you must introduce secondary salt keys (e.g.,tenant_id_salt = hash(user_id) % 8).
4. Hands-On Lab: Simulating Zero-Downtime Shard Cutover
Let's simulate the fundamental state-machine of an atomic shard cutover using Python. This demo models how an orchestrator transitions reads and writes from an old shard (Shard 0) to new child shards (Shard 0A and Shard 0B) using a simulated routing proxy and CDC queue.
import time
from collections import deque
# 1. State Machine Definitions
ROUTING_TABLE = {
"ranges": [
{"range": (0, 100), "target": "shard_0"} # Initial single shard
]
}
STORAGE = {
"shard_0": {},
"shard_0A": {},
"shard_0B": {}
}
# Simulated CDC change-log queue for live replication
cdc_queue = deque()
def route_write(user_id: int, data: str):
"""Simulates the routing proxy directing writes to shards."""
target_shard = None
for item in ROUTING_TABLE["ranges"]:
low, high = item["range"]
if low <= user_id < high:
target_shard = item["target"]
break
if not target_shard:
raise Exception(f"No route found for user_id {user_id}!")
# Write to target
STORAGE[target_shard][user_id] = data
# If writing to shard_0 during migration, publish to CDC queue
if target_shard == "shard_0":
cdc_queue.append((user_id, data))
def replay_cdc_events():
"""Destination shards consume the CDC queue."""
while cdc_queue:
user_id, data = cdc_queue.popleft()
# Route to child shards: [0, 50) -> 0A, [50, 100) -> 0B
if user_id < 50:
STORAGE["shard_0A"][user_id] = data
else:
STORAGE["shard_0B"][user_id] = data
# --- SIMULATION START ---
print("Step 1: Populating initial data in Shard 0...")
for uid in [10, 25, 60, 85]:
route_write(uid, f"Profile_Data_{uid}")
print(f"Shard 0 state: {STORAGE['shard_0']}\n")
print("Step 2: Starting background baseline copy from Shard 0 to Child Shards...")
for uid, data in STORAGE["shard_0"].items():
if uid < 50:
STORAGE["shard_0A"][uid] = data
else:
STORAGE["shard_0B"][uid] = data
print("Step 3: New writes occur on Shard 0 while migration is underway...")
route_write(15, "Profile_Data_15_UPDATED")
route_write(70, "Profile_Data_70_NEW")
print(f"CDC lag: {len(cdc_queue)} events waiting to be replayed.")
print("Step 4: Draining CDC queue to sync destinations...")
replay_cdc_events()
print("Destination shards are now caught up!\n")
print("Step 5: Performing Atomic Routing Cutover (Microsecond pause)...")
# Atomic directory update
ROUTING_TABLE["ranges"] = [
{"range": (0, 50), "target": "shard_0A"},
{"range": (50, 100), "target": "shard_0B"}
]
print("Step 6: Writing to cluster after cutover...")
route_write(20, "Profile_Data_20_POST_SPLIT")
route_write(95, "Profile_Data_95_POST_SPLIT")
print("\n--- Final State Verification ---")
print(f"Shard 0A data: {STORAGE['shard_0A']}")
print(f"Shard 0B data: {STORAGE['shard_0B']}")
print(f"Shard 0 (to be retired): {STORAGE['shard_0']}")Try It Yourself
Run the code snippet. Notice that:
- Writes made during the migration landed in the destination shards through the CDC pipeline (
replay_cdc_events()). - Post-split writes routed cleanly to
shard_0Aandshard_0Bwithout needing to modify the records or touchshard_0. - If an error occurred prior to updating
ROUTING_TABLE, the database could safely roll back toshard_0without data corruption.
5. Summary & Operational Checklist
Before declaring your sharded cluster production-ready, run through this survival checklist:
- Throttled Resharding: Is your CDC/backfill rate limited so it cannot consume more than 30% of baseline disk read IOPS?
- Coordinated Backup Tokens: Do backups utilize a global timestamp (HLC/TrueTime) or coordinated distributed checkpoints to prevent cross-shard phantom transactions?
- Replica-Offloaded Snapshots: Are all backup snapshots taken from secondary/replica nodes to preserve primary node query budgets?
- Gini Skew Alerting: Do you monitor storage and QPS variance across shards rather than just looking at cluster-wide averages?
- Automated Predictive Splitting: Are alert triggers set to warn you days before a shard runs out of disk, accounting for total migration transfer times?
References and Extra Reading
- Vitess Documentation: Resharding & VReplication Concepts [1]
- CockroachDB Docs: How Range Splits Work Internally [2]
- CockroachDB: Backup and Restore Architecture with AS OF SYSTEM TIME [6]
- Martin Kleppmann: Designing Data-Intensive Applications (Chapter 6: Partitioning)
- Prometheus Alerting Best Practices for Distributed Topologies [8]
Challenge
Shard Splitting & Day-Two Operations — Recall Check
You are the on-call engineer for a sharded database that is about to split a hot shard. Before you touch production, prove you can recall the operational mechanics from memory.
Rules
- Answer each question in the blank line(s) beneath it, directly in the editor.
- Write in your own words — short, precise sentences beat long paragraphs.
- Do not look anything up. This is a recall exercise; partial answers are fine.
- Where a question asks for a number or threshold, give the concrete value.
- Where a question asks for an ordering, number your steps.
Focus areas: dual-replication cutover, backfill throttling, consistent recovery across shards, per-shard observability thresholds, and safe rollback.
Expected result
A complete response fills every blank line with a substantive answer. Grading criteria (objective, per question):
- Four phases — exactly four phases, listed in the correct operational sequence, each with a purpose that matches its phase. Ordering errors or a missing phase count as incorrect.
- Backfill throttling — states that migration competes with live traffic and names the two saturated resources (one storage-IO resource, one network resource).
- Cutover ordering — all three actions in the correct relative order, plus a justification that references avoiding lost or double-counted writes during the switch.
- Phantom money — explanation correctly identifies that a transfer debited on one shard and credited on another can be captured in only one of the two backups when snapshot times differ, and names the correct cross-shard consistency mechanism.
- NewSQL — names the correct clock technology and the correct SQL clause; both must be right for full credit.
- Thresholds — five numeric values, each matching the documented red-flag threshold. Partial credit per correct value.
- Hot keys — explains that range splitting partitions key ranges, not individual keys, so a single key stays on one shard; two distinct remedies given.
- Foreign keys — two distinct resolutions, both of which remove the constraint from the database layer's cross-shard path.
- Rollback — identifies the atomic routing-metadata update as the point of no return and explains that post-update writes land only on the new shards.
- Capacity trigger — the correct percentage-based disk trigger and the correct predictive alert function name.
Answers are judged on correctness of terminology and ordering, not on prose style. Any answer that is vague, hedged, or omits a requested item should be marked incomplete.