From 4d41bbe3cccac16b3a2bdfaf81cd4a53d4b24e36 Mon Sep 17 00:00:00 2001 From: Rafi Shamim Date: Wed, 29 Apr 2026 12:44:15 -0400 Subject: [PATCH] skills/analyzing-schema-change-storage-risk: rewrite to match docs and code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The current skill is built around a "3× the largest range size" rule that doesn't exist in CockroachDB. Engineers from the schema team flagged it as inaccurate in [this Slack thread][thread]. Reviewing the CockroachDB source confirmed the skill's specifics are fabricated: - No "3× largest range" rule exists anywhere in the codebase. - The claimed mechanism ("1× existing + 1× backfill + 1× MVCC") has no basis. - The cited cluster setting `kv.range_split.by_load_enabled` controls load-based range splitting, not disk-based backfill pausing. The real mechanism is `kv.bulk_io_write.min_capacity_remaining_fraction` (default 5%), enforced on `AddSSTable` ingests; on rejection the schema change job pauses itself via `jobs.MarkPauseRequestError`. - The recommended SQL queries use `span_stats->>'approximate_disk_bytes'` rather than the `range_size_mb` column the official docs recommend. This rewrite: - Mirrors the [official docs guidance][docs]: up to 3× the size of the affected *table or index* as a conservative bound, not "3× the largest range". - Distinguishes CREATE INDEX (~1× the new index) from ALTER PRIMARY KEY (where 3× the table is the right ballpark). - Uses the docs-recommended `SHOW RANGES ... WITH DETAILS, KEYS, INDEXES` query and `range_size_mb`. - Documents the real disk-full mechanism. - Drops `references/storage-calculations.md` entirely; its decision trees and "common mistakes" all hinge on the removed framing. [thread]: https://cockroachlabs.slack.com/archives/C04U1BTF8/p1777324688585579?thread_ts=1777323782.834359&cid=C04U1BTF8 [docs]: https://www.cockroachlabs.com/docs/stable/online-schema-changes#estimate-your-storage-capacity-before-performing-online-schema-changes --- .../SKILL.md | 530 +++---------- .../references/storage-calculations.md | 700 ------------------ 2 files changed, 108 insertions(+), 1122 deletions(-) delete mode 100644 skills/observability-and-diagnostics/analyzing-schema-change-storage-risk/references/storage-calculations.md diff --git a/skills/observability-and-diagnostics/analyzing-schema-change-storage-risk/SKILL.md b/skills/observability-and-diagnostics/analyzing-schema-change-storage-risk/SKILL.md index e5b717d..feed1f2 100644 --- a/skills/observability-and-diagnostics/analyzing-schema-change-storage-risk/SKILL.md +++ b/skills/observability-and-diagnostics/analyzing-schema-change-storage-risk/SKILL.md @@ -1,468 +1,154 @@ --- name: analyzing-schema-change-storage-risk -description: Estimates storage requirements for CockroachDB schema change backfills by analyzing per-index range sizes using SHOW RANGES WITH DETAILS and applying the 3× free space rule. Use when planning CREATE INDEX, ADD COLUMN, or ALTER PRIMARY KEY operations on large tables to avoid disk exhaustion during backfill. -compatibility: Requires SQL access with admin role or ZONECONFIG system privilege. DETAILS option is expensive; use only on targeted large tables. CockroachDB requires 3× the largest range size as free storage during backfill operations. +description: Estimates storage requirements for CockroachDB online schema change backfills using SHOW RANGES WITH DETAILS, KEYS, INDEXES. Use before CREATE INDEX, ADD COLUMN with INDEX/UNIQUE, ALTER PRIMARY KEY, CREATE MATERIALIZED VIEW, CREATE TABLE AS, REFRESH, or SET LOCALITY on tables with large per-index footprints, to avoid mid-backfill disk exhaustion. +compatibility: Requires SQL access. SHOW RANGES WITH DETAILS computes span_stats on demand and is expensive on tables with many ranges; target specific tables. Mirrors official guidance at https://www.cockroachlabs.com/docs/stable/online-schema-changes#estimate-your-storage-capacity-before-performing-online-schema-changes. metadata: author: cockroachdb - version: "1.0" + version: "2.0" --- # Analyzing Schema Change Storage Risk -Estimates storage requirements for CockroachDB schema change backfills by analyzing per-index range sizes and applying the 3× free space rule. Uses `SHOW RANGES WITH DETAILS` to calculate worst-case disk usage for `CREATE INDEX`, `ADD COLUMN`, and `ALTER PRIMARY KEY` operations, preventing mid-backfill disk exhaustion. +Estimates the storage headroom needed to safely run online schema changes. +Mirrors the [official guidance](https://www.cockroachlabs.com/docs/stable/online-schema-changes#estimate-your-storage-capacity-before-performing-online-schema-changes): +some operations may temporarily require up to **3× the size of the affected +table or index** while the schema change is in flight. -**Complement to range distribution analysis:** This skill focuses on pre-DDL capacity planning; for ongoing range health monitoring, see [analyzing-range-distribution](../analyzing-range-distribution/SKILL.md). +For ongoing range-distribution monitoring, see +[analyzing-range-distribution](../analyzing-range-distribution/SKILL.md). ## When to Use This Skill -- Estimate storage needs before CREATE INDEX on large tables (100GB+) -- Validate capacity before ADD COLUMN backfills with computed/default values -- Pre-flight checks for ALTER PRIMARY KEY operations (full table rewrite) -- Avoid mid-backfill disk exhaustion errors causing schema change failures -- Multi-index planning: prioritize index creation by storage impact -- Capacity planning for batch DDL operations -- SQL-only storage estimation without DB Console access +Run a quick estimate before issuing any of these operations on a table whose +indexes are large (multiple GB per index, or many ranges per index): -**For range-level monitoring:** Use [analyzing-range-distribution](../analyzing-range-distribution/SKILL.md) to analyze range count, leaseholder placement, and fragmentation patterns. +- `CREATE INDEX` +- `ADD COLUMN` with `INDEX` or `UNIQUE` +- `ALTER PRIMARY KEY` +- `CREATE MATERIALIZED VIEW` +- `CREATE TABLE AS` +- `REFRESH MATERIALIZED VIEW` +- `ALTER TABLE ... SET LOCALITY` (when the locality change rewrites data) -## Prerequisites +Tables whose indexes are small (kilobytes to a few megabytes) carry trivial +storage risk; estimation is unnecessary. -- SQL connection to CockroachDB cluster -- Admin role OR `ZONECONFIG` system privilege -- Understanding of online schema change architecture (backfill process, MVCC) -- Knowledge of current cluster free disk space (check monitoring or `crdb_internal.kv_store_status`) -- Target table must have existing data (empty tables = zero storage risk) +## Background -**Check your privileges:** -```sql -SHOW GRANTS ON SYSTEM FOR current_user; -- Should show admin or ZONECONFIG -``` - -**Check cluster free disk space:** -```sql -SELECT - node_id, - store_id, - ROUND((capacity - used) / 1073741824.0, 2) AS free_gb, - ROUND((used::FLOAT / capacity) * 100, 2) AS disk_usage_pct -FROM crdb_internal.kv_store_status -ORDER BY disk_usage_pct DESC; -``` - -See [permissions reference](references/permissions.md) for RBAC setup (shared with analyzing-range-distribution). - -## Core Concepts - -### The 3× Storage Rule - -**Rule:** CockroachDB requires **3× the largest range size** as free disk space during schema change backfills. - -**Why 3×?** -1. **Existing data (1×):** Original table/index data remains during backfill -2. **New backfill data (1×):** New index or column data written during online schema change -3. **MVCC versioning overhead (1×):** Multiple versions during compaction, garbage collection lag - -**Critical:** The rule applies to the **largest single range**, not average range size or total table size. +### How much temporary space does a backfill actually need? -**Example:** -- Table has 100GB total size, 1500 ranges -- Largest range = 80MB -- Required free space = 3 × 80MB = 240MB (per node with replica) +The honest answer depends on the operation: -### Schema Change Backfill Process +- **`CREATE INDEX` / `ADD COLUMN ... UNIQUE`**: needs roughly **1× the size of + the new index** — the indexed columns plus the primary key columns, written + into a fresh index span. This is typically a small fraction of the table. + Worst-case headroom is bounded by the size of that one index. +- **`ALTER PRIMARY KEY`**: rewrites the primary index and any secondary indexes + whose definitions depend on the old PK. Old data sticks around until GC, so + peak on-disk usage during the change can approach the size of the table again. +- **All bulk-ingest backfills**: extra MVCC versions and pre-compaction SSTs + add overhead until Pebble compacts and GC runs. -**Online schema change phases:** -1. **Backfill:** Populate new index/column in background (bulk writes) -2. **Validation:** Verify new index matches existing data -3. **Swap:** Atomically make schema change visible -4. **Cleanup:** Delete old index/column data (GC later) +The official docs round these up into a single conservative recommendation: +plan for up to **3× the size of the affected table or index** as free space. +That figure is a safety bound, not a precise prediction. For most +`CREATE INDEX` operations the real cost is much smaller; for +`ALTER PRIMARY KEY` on a large table it is the right ballpark. -**Storage peak:** During backfill (phases 1-2), both old and new data exist simultaneously. +### What happens if the cluster runs out of disk mid-backfill? -**Backfill pause behavior:** CockroachDB pauses backfills if disk usage exceeds `kv.range_split.by_load_enabled` threshold (~85% by default), preventing disk exhaustion but causing schema change delays. +Backfills bulk-ingest data via `AddSSTable`, which checks the per-store +remaining capacity before each ingestion. If the remaining fraction falls +below `kv.bulk_io_write.min_capacity_remaining_fraction` (default `0.05`, +i.e. 5%), the ingest is rejected with `InsufficientSpaceError`. Both the +legacy and declarative schema changers translate that error into a job pause +request, so the schema change halts rather than wedging the cluster. To +resume, free space (e.g. drop unused indexes, expand storage) and resume the +paused job. -### Per-Index Storage Calculation +This is a *reactive* safety net, not a planning tool — by the time it fires, +foreground writes on the affected store may already be unhealthy. -**Why per-index?** Each index is backed by separate ranges with different sizes. +## Estimating Capacity -**Example table schema:** -```sql -CREATE TABLE orders ( - id UUID PRIMARY KEY, - customer_id UUID, - created_at TIMESTAMP, - total DECIMAL(10,2), - INDEX idx_customer (customer_id), - INDEX idx_created (created_at) -); -``` - -**Storage breakdown:** -- Primary index (`id`): 500GB, largest range 75MB → 225MB required -- `idx_customer`: 150GB, largest range 60MB → 180MB required -- `idx_created`: 200GB, largest range 90MB → **270MB required** (largest) - -**Conclusion:** New index creation requires **270MB free space** (worst case from `idx_created`'s largest range). - -### SHOW RANGES WITH DETAILS Safety - -**CRITICAL WARNING:** The `WITH DETAILS` option computes `span_stats` on-demand, causing: -- **High CPU usage** from statistics computation -- **Memory overhead** proportional to range count -- **Query timeouts** on tables with 1000s of ranges without LIMIT - -**Mandatory guardrails:** -1. **LIMIT clause:** Default 50-100 for exploratory analysis -2. **Specific table targeting:** Use `FROM TABLE table_name`, never cluster-wide -3. **Production timing:** Run during maintenance windows or low-traffic periods -4. **Pre-check range count:** Run basic `SHOW RANGES` first to assess table size - -See [analyzing-range-distribution safety section](../analyzing-range-distribution/SKILL.md#safety-considerations) for detailed guardrails. +### Step 1 — Check free space per store -## Core Diagnostic Queries - -### Query 1: Total Table Storage (All Indexes) +The minimum free space across stores is what bounds the schema change, not the +total cluster free space (replicas are spread across nodes). ```sql --- Estimate total table storage across all indexes SELECT - table_name, - index_name, - COUNT(*) AS range_count, - ROUND(SUM((span_stats->>'approximate_disk_bytes')::BIGINT) / 1073741824.0, 2) AS total_size_gb, - ROUND(AVG((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0, 2) AS avg_range_size_mb -FROM [SHOW RANGES FROM TABLE your_table_name WITH DETAILS] -GROUP BY table_name, index_name -ORDER BY total_size_gb DESC; -``` - -**Output:** -- `total_size_gb`: Total storage per index -- `avg_range_size_mb`: Average range size (not used for 3× rule, but useful for fragmentation context) - -**Interpretation:** High total size (100GB+) indicates CREATE INDEX will have significant storage impact. - -**CRITICAL:** Aggregates DETAILS data across all ranges. Use only on targeted tables, never cluster-wide. - ---- - -### Query 2: Largest Range Size per Index (Critical for 3× Rule) - -```sql --- Find largest range per index (determines 3× storage requirement) -SELECT - table_name, - index_name, - MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 AS largest_range_mb, - ROUND((MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0) * 3, 2) AS required_free_space_mb -FROM [SHOW RANGES FROM TABLE your_table_name WITH DETAILS] -GROUP BY table_name, index_name -ORDER BY largest_range_mb DESC; + node_id, + store_id, + ROUND((capacity - used) / 1073741824.0, 2) AS free_gb, + ROUND((used::FLOAT / capacity) * 100, 2) AS used_pct +FROM crdb_internal.kv_store_status +ORDER BY free_gb ASC; ``` -**Output:** -- `largest_range_mb`: Size of largest range in index -- `required_free_space_mb`: 3× the largest range (minimum free space needed) - -**Interpretation:** -- `largest_range_mb > 64`: Range exceeds default split threshold (may indicate split lag or custom `range_max_bytes`) -- `required_free_space_mb`: Compare with cluster free space (Query from Prerequisites) - -**Use case:** Determine worst-case storage requirement before CREATE INDEX. - -**CRITICAL:** Uses DETAILS with aggregation. Limit to specific tables only. +### Step 2 — Estimate the affected table/index size ---- - -### Query 3: Storage Safety Calculation (Decision Logic) +Use the docs-recommended form of `SHOW RANGES`: ```sql --- Combined query: compare required storage vs. available capacity -WITH range_requirements AS ( - SELECT - table_name, - index_name, - MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 AS largest_range_mb, - ROUND((MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0) * 3, 2) AS required_free_mb_3x, - ROUND((MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0) * 4, 2) AS required_free_mb_4x - FROM [SHOW RANGES FROM TABLE your_table_name WITH DETAILS] - GROUP BY table_name, index_name -), -cluster_capacity AS ( - SELECT - MIN((capacity - used) / 1048576.0) AS min_free_mb -- Minimum free space across all nodes - FROM crdb_internal.kv_store_status -) -SELECT - rr.table_name, - rr.index_name, - rr.largest_range_mb, - rr.required_free_mb_3x AS required_3x, - rr.required_free_mb_4x AS required_4x_recommended, - cc.min_free_mb AS cluster_min_free_mb, - CASE - WHEN cc.min_free_mb >= rr.required_free_mb_4x THEN 'SAFE (4× margin)' - WHEN cc.min_free_mb >= rr.required_free_mb_3x THEN 'MARGINAL (3× only, add capacity recommended)' - ELSE 'UNSAFE (insufficient space, add capacity required)' - END AS risk_assessment -FROM range_requirements rr -CROSS JOIN cluster_capacity cc -ORDER BY rr.largest_range_mb DESC; +SHOW RANGES FROM TABLE WITH DETAILS, KEYS, INDEXES; ``` -**Output:** -- `required_3x`: Minimum free space (3× largest range) -- `required_4x_recommended`: Recommended free space (4× for production safety margin) -- `cluster_min_free_mb`: Minimum free space across all nodes -- `risk_assessment`: SAFE / MARGINAL / UNSAFE - -**Decision matrix:** -- **SAFE:** Proceed with schema change -- **MARGINAL:** Proceed with caution, monitor disk usage closely during backfill -- **UNSAFE:** Add capacity before proceeding (or drop unused indexes first) - -**CRITICAL:** Uses DETAILS and joins with cluster capacity. Run on targeted tables only. - ---- - -### Query 4: Multi-Index Comparison (Prioritization) +The output includes one row per range, with `range_size_mb` and `index_name`. +Aggregate by index for the per-index totals that matter for capacity planning: ```sql --- Compare storage requirements across multiple existing indexes --- Use case: Planning to create index on table with 3+ existing indexes +WITH r AS (SHOW RANGES FROM TABLE
WITH DETAILS, KEYS, INDEXES) SELECT index_name, - COUNT(*) AS range_count, - ROUND(SUM((span_stats->>'approximate_disk_bytes')::BIGINT) / 1073741824.0, 2) AS total_size_gb, - MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 AS largest_range_mb, - ROUND((MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0) * 3, 2) AS required_free_mb -FROM [SHOW RANGES FROM TABLE your_table_name WITH DETAILS] + COUNT(*) AS range_count, + ROUND(SUM(range_size_mb), 2) AS index_size_mb, + ROUND(SUM(range_size_mb) / 1024, 2) AS index_size_gb +FROM r GROUP BY index_name -ORDER BY required_free_mb DESC; +ORDER BY index_size_mb DESC; ``` -**Use case:** Identify which existing index has largest range (determines worst-case for new index creation). - -**Interpretation:** -- New index will likely have similar largest range as largest existing index -- Use worst-case (highest `required_free_mb`) for capacity planning - -**Example scenario:** -- Table has 3 indexes: primary (50MB largest), idx_a (70MB largest), idx_b (90MB largest) -- Creating 4th index: assume 90MB largest range → 270MB required free space - -**CRITICAL:** Aggregates DETAILS across all indexes. Use only on specific tables. - -See [storage-calculations reference](references/storage-calculations.md) for detailed examples and decision trees. - -## Storage Calculation Workflows - -### Workflow 1: Single-Index Backfill Estimation - -**Scenario:** Planning CREATE INDEX on large table (e.g., 200GB table, adding idx_customer). - -**Steps:** -1. **Check current free disk space:** Run cluster capacity query (Prerequisites section) -2. **Find largest range in existing indexes:** Run Query 2 on target table -3. **Calculate 3× requirement:** Multiply largest range by 3 (or 4 for production margin) -4. **Compare required vs. available:** Use Query 3 decision logic -5. **Execute or defer:** Proceed if SAFE, add capacity if UNSAFE - -**Example walkthrough:** -```sql --- 1. Check free space (run first) -SELECT MIN((capacity - used) / 1073741824.0) AS min_free_gb -FROM crdb_internal.kv_store_status; --- Result: 150GB minimum free - --- 2. Find largest range -SELECT MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 AS largest_mb -FROM [SHOW RANGES FROM TABLE orders WITH DETAILS]; --- Result: 75MB largest range - --- 3. Calculate requirement --- 3× = 225MB, 4× = 300MB - --- 4. Decision --- 150GB free >> 300MB required → SAFE, proceed with CREATE INDEX -``` - ---- - -### Workflow 2: Multi-Index Backfill Planning - -**Scenario:** Planning to create 3 new indexes on same table sequentially. - -**Steps:** -1. **Analyze existing indexes:** Run Query 4 to compare storage profiles -2. **Estimate new index sizes:** Assume similar to largest existing index (conservative) -3. **Prioritize by impact:** Create smaller indexes first (faster backfill, less risk) -4. **Monitor between operations:** Check disk usage after each CREATE INDEX before starting next - -**Example:** -```sql --- Analyze existing indexes -SELECT index_name, MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 AS largest_mb -FROM [SHOW RANGES FROM TABLE products WITH DETAILS] -GROUP BY index_name; - --- Results: --- primary: 80MB → 240MB required --- idx_category: 60MB → 180MB required --- idx_supplier: 90MB → 270MB required (worst case) - --- Plan: Assume new indexes will have 90MB largest range → 270MB each --- Create indexes sequentially, monitor disk after each -``` - ---- - -### Workflow 3: Capacity Validation Before ALTER PRIMARY KEY - -**Scenario:** Changing primary key (full table rewrite, highest storage risk). - -**Steps:** -1. **Understand scope:** ALTER PRIMARY KEY rewrites entire table (all indexes) -2. **Calculate total storage:** Sum all index sizes (Query 1) -3. **Find worst-case range:** Largest range across all indexes (Query 2) -4. **Apply 3× rule conservatively:** Use 4× multiplier for ALTER PRIMARY KEY operations -5. **Validate capacity:** Ensure 4× largest range available, plus buffer for MVCC overhead - -**CRITICAL:** ALTER PRIMARY KEY is highest-risk DDL for storage exhaustion. Always use 4× multiplier. - -**Example:** -```sql --- Total table size -SELECT SUM((span_stats->>'approximate_disk_bytes')::BIGINT) / 1073741824.0 AS total_gb -FROM [SHOW RANGES FROM TABLE critical_table WITH DETAILS]; --- Result: 500GB - --- Largest range across all indexes -SELECT MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 AS largest_mb -FROM [SHOW RANGES FROM TABLE critical_table WITH DETAILS]; --- Result: 100MB - --- Requirement: 4× 100MB = 400MB minimum --- Recommendation: Add 20% buffer → 480MB recommended free space per node -``` - ---- - -## Safety Considerations - -### DETAILS Option Performance Impact - -**Resource usage:** -- **CPU:** Computes span statistics on-demand (aggregates across KV layer) -- **Memory:** Proportional to range count returned -- **Timeout risk:** Tables with 5000+ ranges may timeout without LIMIT - -**Mitigation strategies:** -1. **Pre-check range count:** Run `SELECT COUNT(*) FROM [SHOW RANGES FROM TABLE t]` first -2. **Use LIMIT for exploration:** Start with `LIMIT 100`, remove only if needed -3. **Target specific tables:** Never run cluster-wide `SHOW RANGES WITH DETAILS` -4. **Production timing:** Schedule during maintenance windows for large tables -5. **Incremental analysis:** Analyze per-index if table has many indexes - -See [analyzing-range-distribution safety section](../analyzing-range-distribution/SKILL.md#safety-considerations) for complete guardrails. - ---- - -### Production Best Practices - -**Margin of safety:** -- **Minimum (3×):** Theoretical minimum, use only in non-production -- **Recommended (4×):** Production standard, accounts for MVCC spikes, GC lag -- **Conservative (5×):** High-stakes tables (financial, compliance), or during high-traffic periods - -**Monitoring during backfill:** -```sql --- Monitor disk usage every 5 minutes during schema change -SELECT - node_id, - store_id, - ROUND((used::FLOAT / capacity) * 100, 2) AS disk_usage_pct -FROM crdb_internal.kv_store_status -ORDER BY disk_usage_pct DESC; -``` - -**Backfill pause detection:** -```sql --- Check for paused schema changes -SELECT - job_id, - job_type, - description, - status, - fraction_completed -FROM crdb_internal.jobs -WHERE job_type = 'SCHEMA CHANGE' AND status = 'paused'; -``` - -**If paused:** Backfill hit disk threshold. Add capacity or drop unused indexes to free space. - ---- - -### Pre-Execution Checklist - -Before running CREATE INDEX / ADD COLUMN / ALTER PRIMARY KEY: - -- [ ] Run Query 3 to calculate storage safety (SAFE / MARGINAL / UNSAFE) -- [ ] Verify 4× margin available (not just 3×) for production tables -- [ ] Check for unused indexes to drop (frees space immediately) -- [ ] Schedule during maintenance window or low-traffic period -- [ ] Set up disk usage monitoring alerts (85% threshold) -- [ ] Prepare rollback plan (schema change cancellation steps) -- [ ] Validate table statistics are up-to-date (`SHOW STATISTICS FOR TABLE t`) - -**If UNSAFE:** Add capacity first (scale cluster) or drop unused indexes. - ---- - -## Troubleshooting - -| Issue | Cause | Fix | -|-------|-------|-----| -| Query timeout with DETAILS | Too many ranges, no LIMIT | Add `LIMIT 100`, target specific index | -| Zero `approximate_disk_bytes` | Empty table or statistics lag | Run `CREATE STATISTICS` or wait for auto-stats collection | -| Unexpected high storage values | Includes MVCC versions, old data | Normal; use `live_bytes` for current data estimate | -| Permission denied | Missing ZONECONFIG or admin privilege | Grant ZONECONFIG: `GRANT SYSTEM ZONECONFIG TO user` | -| `min_free_mb` shows negative value | Disk usage > capacity (critical!) | Immediate capacity expansion required | -| Backfill paused mid-operation | Disk usage exceeded threshold | Add capacity, or drop unused indexes to free space | -| Different values between nodes | Non-uniform data distribution | Use MIN(free space) for worst-case planning | -| Largest range > 512MB | Custom `range_max_bytes` or split lag | Investigate zone config; 3× rule still applies | - ---- - -## Key Considerations - -- **3× rule applies to largest range, not average:** Always use MAX(range size), not AVG -- **Per-index analysis:** Each index has different range sizes; use worst-case -- **4× for production:** Conservative margin accounts for MVCC spikes, GC lag -- **ALTER PRIMARY KEY = highest risk:** Full table rewrite, use 4-5× multiplier -- **Empty tables have zero risk:** Storage estimation only applies to tables with data -- **DETAILS option is expensive:** Always use LIMIT, target specific tables -- **Backfill pauses automatically:** CockroachDB prevents disk exhaustion by pausing, but delays schema changes -- **Monitor during execution:** Check disk usage every 5-10 minutes during long backfills -- **Statistics accuracy:** `approximate_disk_bytes` includes MVCC overhead; use for conservative estimates - ---- +### Step 3 — Compare against the operation + +| Operation | Conservative free-space target (per store) | +|---------------------------------------------|-----------------------------------------------------------------------------| +| `CREATE INDEX` / `ADD COLUMN ... UNIQUE` | Up to 3× the size of the *new* index (its indexed + PK columns). | +| `ALTER PRIMARY KEY` | Up to 3× the size of the *table* (sum of the relevant indexes from step 2). | +| `CREATE MATERIALIZED VIEW` / `CREATE TABLE AS` | Up to 3× the expected size of the materialized result. | + +The new index does not exist yet, so estimate it from a comparable existing +index (e.g. one on similarly typed columns) or from the source columns' +contribution to the primary index. + +If the smallest free-space figure from step 1 is well above the target, the +operation is safe to run. If it is close, free space first (drop unused +indexes, expand storage) before issuing the DDL. + +## Operational Notes + +- **`SHOW RANGES ... WITH DETAILS` is expensive.** It computes span statistics + on demand. Always target a specific table, never run it cluster-wide, and + prefer maintenance windows on tables with thousands of ranges. +- **Watch the job, not just disk.** If a backfill pauses with + `InsufficientSpaceError`, free disk on the affected store and resume the + paused schema change job. Check with: + ```sql + SELECT job_id, status, error + FROM crdb_internal.jobs + WHERE job_type = 'SCHEMA CHANGE' AND status = 'paused'; + ``` +- **Drop unused indexes first.** Often the cheapest way to free headroom + before a large backfill is to drop indexes that + `crdb_internal.index_usage_statistics` shows are unused. +- **Statistics lag.** `range_size_mb` is approximate and can lag actual disk + usage; treat estimates as conservative ballparks, not exact figures. ## References -**Skill references:** -- [Detailed storage calculations and examples](references/storage-calculations.md) -- [RBAC and privileges setup](references/permissions.md) (shared with analyzing-range-distribution) - -**Official CockroachDB Documentation:** -- [Online Schema Changes](https://www.cockroachlabs.com/docs/stable/online-schema-changes.html) +- [Online Schema Changes — Estimate your storage capacity](https://www.cockroachlabs.com/docs/stable/online-schema-changes#estimate-your-storage-capacity-before-performing-online-schema-changes) - [SHOW RANGES](https://www.cockroachlabs.com/docs/stable/show-ranges.html) -- [CREATE INDEX](https://www.cockroachlabs.com/docs/stable/create-index.html) -- [ALTER TABLE](https://www.cockroachlabs.com/docs/stable/alter-table.html) -- [Architecture: Storage Layer](https://www.cockroachlabs.com/docs/stable/architecture/storage-layer.html) -- [ZONECONFIG privilege](https://www.cockroachlabs.com/docs/stable/security-reference/authorization.html#supported-privileges) - -**Related skills:** -- [analyzing-range-distribution](../analyzing-range-distribution/SKILL.md) - For ongoing range health monitoring and leaseholder analysis -- [profiling-statement-fingerprints](../profiling-statement-fingerprints/SKILL.md) - For query performance analysis -- [triaging-live-sql-activity](../triaging-live-sql-activity/SKILL.md) - For real-time query triage + +## Related Skills + +- [analyzing-range-distribution](../analyzing-range-distribution/SKILL.md) — range count, leaseholder placement, fragmentation diff --git a/skills/observability-and-diagnostics/analyzing-schema-change-storage-risk/references/storage-calculations.md b/skills/observability-and-diagnostics/analyzing-schema-change-storage-risk/references/storage-calculations.md deleted file mode 100644 index 9db8430..0000000 --- a/skills/observability-and-diagnostics/analyzing-schema-change-storage-risk/references/storage-calculations.md +++ /dev/null @@ -1,700 +0,0 @@ -# Storage Calculation Examples for Schema Change Backfills - -This reference provides detailed examples, decision trees, and calculation walkthroughs for estimating storage requirements using the 3× rule for CockroachDB schema change operations. - -## Table of Contents - -1. [The 3× Storage Rule Explained](#the-3-storage-rule-explained) -2. [Example 1: Single Index Creation (Simple)](#example-1-single-index-creation-simple) -3. [Example 2: Multi-Index Table Analysis](#example-2-multi-index-table-analysis) -4. [Example 3: ALTER PRIMARY KEY (High Risk)](#example-3-alter-primary-key-high-risk) -5. [Example 4: ADD COLUMN with Default Value](#example-4-add-column-with-default-value) -6. [Decision Trees](#decision-trees) -7. [Safety Margins: 3× vs 4× vs 5×](#safety-margins-3-vs-4-vs-5) -8. [Common Calculation Mistakes](#common-calculation-mistakes) - ---- - -## The 3× Storage Rule Explained - -### Why 3×? - -CockroachDB's online schema changes create temporary storage overhead during backfill operations. The 3× multiplier accounts for: - -1. **Existing data (1×):** Original table/index data remains accessible during backfill -2. **New backfill data (1×):** New index or column data written in background -3. **MVCC versioning overhead (1×):** Multiple versions exist during compaction, GC lag before old versions deleted - -### Key Insight: Largest Range, Not Total Size - -**CRITICAL:** The rule applies to the **largest single range**, not average range size or total table size. - -**Why?** During backfill, individual ranges split when they approach the split threshold. The largest range determines worst-case storage spike before split occurs. - -**Example:** -- Table: 500GB total, 5000 ranges -- Average range size: 100MB -- Largest range: 150MB -- **Required free space: 3 × 150MB = 450MB** (NOT 3 × 100MB) - -### Formula - -``` -Required Free Space = Largest Range Size × Multiplier -``` - -**Multiplier choices:** -- **3×:** Minimum (theoretical) -- **4×:** Recommended (production standard) -- **5×:** Conservative (high-stakes tables) - ---- - -## Example 1: Single Index Creation (Simple) - -### Scenario - -**Table:** `users` (300GB, 3 existing indexes) -**Operation:** `CREATE INDEX idx_email ON users(email)` -**Goal:** Estimate storage requirement before execution - ---- - -### Step 1: Check Current Cluster Capacity - -```sql -SELECT - node_id, - ROUND((capacity - used) / 1073741824.0, 2) AS free_gb, - ROUND((used::FLOAT / capacity) * 100, 2) AS disk_usage_pct -FROM crdb_internal.kv_store_status -ORDER BY free_gb ASC; -- Identify node with least free space -``` - -**Output:** -``` - node_id | free_gb | disk_usage_pct ----------+---------+---------------- - 1 | 120.50 | 65.2 - 2 | 135.20 | 62.1 - 3 | 125.80 | 64.3 -``` - -**Minimum free space:** 120.50 GB (node 1, worst case) - ---- - -### Step 2: Analyze Existing Index Range Sizes - -```sql -SELECT - index_name, - COUNT(*) AS range_count, - ROUND(SUM((span_stats->>'approximate_disk_bytes')::BIGINT) / 1073741824.0, 2) AS total_gb, - MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 AS largest_range_mb -FROM [SHOW RANGES FROM TABLE users WITH DETAILS] -GROUP BY index_name -ORDER BY largest_range_mb DESC; -``` - -**Output:** -``` - index_name | range_count | total_gb | largest_range_mb ---------------+-------------+----------+------------------ - primary | 2500 | 180.00 | 85.5 - idx_username | 1000 | 70.00 | 72.3 - idx_created | 1200 | 50.00 | 68.1 -``` - -**Largest range across all indexes:** 85.5 MB (primary index) - ---- - -### Step 3: Calculate Storage Requirement - -**Assumption:** New `idx_email` will have similar range size distribution to existing indexes (conservative: use largest observed range). - -**Calculation:** -``` -Largest range: 85.5 MB -3× requirement: 85.5 × 3 = 256.5 MB -4× requirement: 85.5 × 4 = 342 MB (recommended) -``` - ---- - -### Step 4: Decision - -**Comparison:** -- **Available:** 120.50 GB minimum free space -- **Required (4×):** 342 MB = 0.334 GB - -**Risk Assessment:** **SAFE** -- Available >> Required (120.50 GB >> 0.334 GB) -- Proceed with CREATE INDEX - -**Command:** -```sql -CREATE INDEX idx_email ON users(email); -``` - -**Monitoring during backfill:** -```sql --- Check job progress -SELECT job_id, fraction_completed, status -FROM crdb_internal.jobs -WHERE description LIKE '%idx_email%' - AND job_type = 'SCHEMA CHANGE'; - --- Monitor disk usage every 5 minutes -SELECT node_id, ROUND((used::FLOAT / capacity) * 100, 2) AS pct -FROM crdb_internal.kv_store_status -ORDER BY pct DESC; -``` - ---- - -## Example 2: Multi-Index Table Analysis - -### Scenario - -**Table:** `orders` (500GB, 5 existing indexes) -**Operation:** Plan to create 3 new indexes sequentially -**Goal:** Prioritize index creation by storage impact, validate capacity - ---- - -### Step 1: Analyze All Existing Indexes - -```sql -SELECT - index_name, - COUNT(*) AS range_count, - ROUND(SUM((span_stats->>'approximate_disk_bytes')::BIGINT) / 1073741824.0, 2) AS total_gb, - ROUND(AVG((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0, 2) AS avg_range_mb, - MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 AS largest_range_mb, - ROUND((MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0) * 3, 2) AS required_3x_mb, - ROUND((MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0) * 4, 2) AS required_4x_mb -FROM [SHOW RANGES FROM TABLE orders WITH DETAILS] -GROUP BY index_name -ORDER BY largest_range_mb DESC; -``` - -**Output:** -``` - index_name | range_count | total_gb | avg_range_mb | largest_range_mb | required_3x_mb | required_4x_mb ------------------+-------------+----------+--------------+------------------+----------------+---------------- - idx_created_at | 3500 | 220.00 | 64.29 | 95.2 | 285.6 | 380.8 - primary | 3000 | 180.00 | 61.44 | 88.5 | 265.5 | 354.0 - idx_customer_id | 2000 | 80.00 | 40.96 | 75.3 | 225.9 | 301.2 - idx_status | 1500 | 15.00 | 10.24 | 65.1 | 195.3 | 260.4 - idx_total | 1000 | 5.00 | 5.12 | 58.8 | 176.4 | 235.2 -``` - -**Worst-case largest range:** 95.2 MB (`idx_created_at`, timestamp-based index with sequential inserts) - ---- - -### Step 2: Estimate New Index Sizes - -**Planned new indexes:** -1. `idx_shipping_address` (text column, low cardinality) → Assume similar to `idx_status` (~65 MB) -2. `idx_product_id` (UUID, high cardinality) → Assume similar to `idx_customer_id` (~75 MB) -3. `idx_updated_at` (timestamp, sequential) → Assume similar to `idx_created_at` (~95 MB, worst case) - -**Storage requirements (4× margin):** -1. `idx_shipping_address`: 65 MB × 4 = **260 MB** -2. `idx_product_id`: 75 MB × 4 = **300 MB** -3. `idx_updated_at`: 95 MB × 4 = **380 MB** - ---- - -### Step 3: Check Cluster Capacity - -```sql -SELECT MIN((capacity - used) / 1073741824.0) AS min_free_gb -FROM crdb_internal.kv_store_status; -``` - -**Output:** -``` - min_free_gb -------------- - 85.5 -``` - -**Available:** 85.5 GB minimum free space - ---- - -### Step 4: Prioritization Strategy - -**Decision:** Create indexes sequentially, smallest to largest (reduces risk, faster validation). - -**Order:** -1. **First:** `idx_shipping_address` (260 MB required) → SAFE -2. **Second:** `idx_product_id` (300 MB required) → SAFE -3. **Third:** `idx_updated_at` (380 MB required) → SAFE - -**Risk:** All indexes fit comfortably in 85.5 GB available. Proceed sequentially. - -**Execution plan:** -```sql --- 1. Create first index -CREATE INDEX idx_shipping_address ON orders(shipping_address); --- Monitor: Wait for completion, check disk usage - --- 2. Create second index -CREATE INDEX idx_product_id ON orders(product_id); --- Monitor: Wait for completion, check disk usage - --- 3. Create third index -CREATE INDEX idx_updated_at ON orders(updated_at); --- Monitor: Wait for completion, check disk usage -``` - -**Why sequential?** Parallel CREATE INDEX operations compound storage requirements (e.g., 260 + 300 + 380 = 940 MB simultaneously). Sequential execution limits risk to worst-case single index. - ---- - -## Example 3: ALTER PRIMARY KEY (High Risk) - -### Scenario - -**Table:** `transactions` (800GB, 4 existing indexes) -**Operation:** `ALTER TABLE transactions ALTER PRIMARY KEY USING COLUMNS (customer_id, created_at)` -**Goal:** Validate capacity for full table rewrite - ---- - -### Step 1: Understand ALTER PRIMARY KEY Scope - -**Critical:** ALTER PRIMARY KEY rewrites the **entire table** (all indexes), not just primary index. - -**Storage impact:** -- **Old primary index:** Remains until GC (800GB total table size) -- **New primary index:** Full backfill (800GB) -- **All secondary indexes:** Rebuilt to reference new primary key (4 indexes) -- **MVCC overhead:** 2× MVCC versions during compaction - -**Worst-case multiplier:** Use **5× largest range** (not 3×) for ALTER PRIMARY KEY. - ---- - -### Step 2: Find Largest Range Across All Indexes - -```sql -SELECT - MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 AS largest_range_mb_any_index -FROM [SHOW RANGES FROM TABLE transactions WITH DETAILS]; -``` - -**Output:** -``` - largest_range_mb_any_index ----------------------------- - 105.8 -``` - -**Largest range:** 105.8 MB (across all indexes) - ---- - -### Step 3: Calculate Storage Requirement (Conservative) - -**Calculation:** -``` -Largest range: 105.8 MB -5× requirement: 105.8 × 5 = 529 MB per node (conservative for ALTER PRIMARY KEY) -``` - -**Why 5×?** ALTER PRIMARY KEY has higher MVCC churn due to full table rewrite. - ---- - -### Step 4: Check Cluster Capacity - -```sql -SELECT - node_id, - ROUND((capacity - used) / 1073741824.0, 2) AS free_gb -FROM crdb_internal.kv_store_status -ORDER BY free_gb ASC; -``` - -**Output:** -``` - node_id | free_gb ----------+--------- - 1 | 45.2 - 2 | 52.8 - 3 | 48.6 -``` - -**Minimum free space:** 45.2 GB (node 1) - ---- - -### Step 5: Decision - -**Comparison:** -- **Available:** 45.2 GB = 46,284 MB -- **Required (5×):** 529 MB - -**Risk Assessment:** **SAFE** -- Available >> Required (46,284 MB >> 529 MB) -- Proceed with ALTER PRIMARY KEY, but monitor closely - -**Execution:** -```sql --- 1. Set up monitoring alert (85% disk threshold) --- 2. Schedule during maintenance window --- 3. Execute ALTER -ALTER TABLE transactions ALTER PRIMARY KEY USING COLUMNS (customer_id, created_at); - --- 4. Monitor every 5 minutes -SELECT node_id, ROUND((used::FLOAT / capacity) * 100, 2) AS pct -FROM crdb_internal.kv_store_status -ORDER BY pct DESC; -``` - -**Rollback plan:** If disk usage exceeds 85%, pause backfill: -```sql --- Cancel schema change job if critical -CANCEL JOB (SELECT job_id FROM crdb_internal.jobs WHERE description LIKE '%transactions%' AND job_type = 'SCHEMA CHANGE'); -``` - ---- - -## Example 4: ADD COLUMN with Default Value - -### Scenario - -**Table:** `products` (150GB, 2 existing indexes) -**Operation:** `ALTER TABLE products ADD COLUMN featured BOOL DEFAULT false` -**Goal:** Estimate storage requirement for column backfill - ---- - -### Step 1: Understand ADD COLUMN Storage Impact - -**With default value:** Full table backfill required (writes default value to all existing rows). - -**Storage impact:** -- **Existing data:** Remains (150GB) -- **New column backfill:** Adds BOOL column to all rows (minimal size, but still backfill overhead) -- **MVCC overhead:** Temporary versions during write - -**Note:** BOOL columns are small (1 byte + metadata), so backfill size is minimal. However, MVCC overhead still applies. - ---- - -### Step 2: Find Largest Range - -```sql -SELECT - MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 AS largest_range_mb -FROM [SHOW RANGES FROM TABLE products WITH DETAILS]; -``` - -**Output:** -``` - largest_range_mb ------------------- - 78.3 -``` - ---- - -### Step 3: Calculate Requirement - -**Calculation:** -``` -Largest range: 78.3 MB -4× requirement: 78.3 × 4 = 313.2 MB (production standard) -``` - -**Note:** ADD COLUMN backfill has lower storage overhead than CREATE INDEX (smaller data writes), but use 4× for safety. - ---- - -### Step 4: Check Capacity - -```sql -SELECT MIN((capacity - used) / 1073741824.0) AS min_free_gb -FROM crdb_internal.kv_store_status; -``` - -**Output:** -``` - min_free_gb -------------- - 200.5 -``` - -**Available:** 200.5 GB - ---- - -### Step 5: Decision - -**Risk Assessment:** **SAFE** -- Available >> Required (200.5 GB >> 0.313 GB) -- Proceed with ADD COLUMN - -**Execution:** -```sql -ALTER TABLE products ADD COLUMN featured BOOL DEFAULT false; -``` - -**Expected backfill time:** Depends on row count and cluster load. Monitor with: -```sql -SELECT job_id, fraction_completed FROM crdb_internal.jobs WHERE description LIKE '%products%'; -``` - ---- - -## Decision Trees - -### Tree 1: Single Index Creation - -``` -START: Planning CREATE INDEX on table T -│ -├─ Step 1: Check range count -│ ├─ < 1000 ranges → Low complexity -│ └─ > 5000 ranges → High complexity (use LIMIT in queries) -│ -├─ Step 2: Find largest range in existing indexes -│ └─ Run: MAX(span_stats->>'approximate_disk_bytes') -│ -├─ Step 3: Calculate requirement -│ ├─ Dev/staging: 3× largest range -│ └─ Production: 4× largest range -│ -├─ Step 4: Check cluster free space -│ └─ Run: MIN(capacity - used) from kv_store_status -│ -└─ Step 5: Decision - ├─ Free space ≥ 4× → SAFE (proceed) - ├─ Free space ≥ 3× but < 4× → MARGINAL (proceed with monitoring) - └─ Free space < 3× → UNSAFE (add capacity or drop unused indexes) -``` - ---- - -### Tree 2: Multi-Index Creation - -``` -START: Planning N new indexes on table T -│ -├─ Step 1: Analyze all existing indexes -│ └─ Find worst-case largest range across all indexes -│ -├─ Step 2: Estimate each new index -│ └─ Assume similar to worst-case existing index -│ -├─ Step 3: Prioritize -│ ├─ Sequential (recommended): Create smallest to largest -│ │ └─ Required capacity: MAX(individual index requirements) -│ └─ Parallel (high risk): Create simultaneously -│ └─ Required capacity: SUM(all index requirements) -│ -└─ Step 4: Execute - ├─ Sequential → Create one, monitor, create next - └─ Parallel → Monitor continuously, prepare to pause if threshold hit -``` - ---- - -### Tree 3: Capacity Expansion Decision - -``` -START: Required storage > Available storage -│ -├─ Option 1: Add cluster capacity -│ ├─ Add nodes (horizontal scaling) -│ └─ Increase disk per node (vertical scaling) -│ -├─ Option 2: Free existing space -│ ├─ Drop unused indexes -│ │ └─ Check: SELECT * FROM crdb_internal.index_usage_statistics WHERE total_reads = 0 -│ ├─ Reduce GC TTL temporarily (frees MVCC versions faster) -│ │ └─ ALTER TABLE T CONFIGURE ZONE USING gc.ttlseconds = 3600; -- 1 hour (default: 4 hours) -│ └─ Manually trigger GC (force compaction) -│ -├─ Option 3: Defer schema change -│ └─ Schedule during off-peak hours when more capacity available -│ -└─ Option 4: Execute with risk (NOT RECOMMENDED) - └─ Monitor continuously, prepare to cancel if threshold hit -``` - ---- - -## Safety Margins: 3× vs 4× vs 5× - -### When to Use Each Multiplier - -| Multiplier | Use Case | Risk Level | Examples | -|------------|----------|------------|----------| -| **3×** | Dev/staging, non-critical tables | Minimum (theoretical) | Test environments, scratch tables | -| **4×** | Production standard | Recommended | Most production workloads | -| **5×** | High-stakes, ALTER PRIMARY KEY | Conservative | Financial tables, compliance data, full table rewrites | - ---- - -### Calculation Comparison Table - -**Example:** Largest range = 100 MB - -| Multiplier | Required Free Space | Buffer Above Minimum | Use Case | -|------------|---------------------|----------------------|----------| -| 3× | 300 MB | 0 MB (baseline) | Minimum (theory) | -| 4× | 400 MB | 100 MB (33% buffer) | Production standard | -| 5× | 500 MB | 200 MB (66% buffer) | High-stakes operations | - -**Recommendation:** Always use **4× for production CREATE INDEX**, **5× for ALTER PRIMARY KEY**. - ---- - -## Common Calculation Mistakes - -### Mistake 1: Using Average Instead of Max - -**WRONG:** -```sql --- INCORRECT: Using average range size -SELECT AVG((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 AS avg_mb -FROM [SHOW RANGES FROM TABLE t WITH DETAILS]; --- Avg: 50 MB → 3× = 150 MB (UNDERESTIMATED) -``` - -**CORRECT:** -```sql --- CORRECT: Using largest range size -SELECT MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 AS max_mb -FROM [SHOW RANGES FROM TABLE t WITH DETAILS]; --- Max: 80 MB → 3× = 240 MB (accurate worst case) -``` - -**Why wrong?** Largest range determines worst-case storage spike before split occurs. - ---- - -### Mistake 2: Applying 3× to Total Table Size - -**WRONG:** -```sql --- INCORRECT: Multiplying total table size -SELECT SUM((span_stats->>'approximate_disk_bytes')::BIGINT) / 1073741824.0 * 3 AS wrong_required_gb -FROM [SHOW RANGES FROM TABLE t WITH DETAILS]; --- Total: 500 GB → 3× = 1500 GB (MASSIVELY OVERESTIMATED) -``` - -**CORRECT:** -```sql --- CORRECT: Multiplying largest single range -SELECT (MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1073741824.0) * 3 AS correct_required_gb -FROM [SHOW RANGES FROM TABLE t WITH DETAILS]; --- Max range: 0.08 GB → 3× = 0.24 GB (accurate) -``` - -**Why wrong?** 3× rule applies per-range, not per-table. CockroachDB splits large ranges automatically; total table size is irrelevant. - ---- - -### Mistake 3: Ignoring MVCC Overhead - -**WRONG:** -```sql --- INCORRECT: Using live_bytes only -SELECT MAX((span_stats->>'live_bytes')::BIGINT) / 1048576.0 * 3 AS wrong_mb -FROM [SHOW RANGES FROM TABLE t WITH DETAILS]; --- Live: 60 MB → 3× = 180 MB (UNDERESTIMATED) -``` - -**CORRECT:** -```sql --- CORRECT: Using approximate_disk_bytes (includes MVCC) -SELECT MAX((span_stats->>'approximate_disk_bytes')::BIGINT) / 1048576.0 * 3 AS correct_mb -FROM [SHOW RANGES FROM TABLE t WITH DETAILS]; --- Disk: 80 MB → 3× = 240 MB (includes MVCC versions) -``` - -**Why wrong?** `live_bytes` excludes MVCC versions and old data. Use `approximate_disk_bytes` for realistic estimates. - ---- - -### Mistake 4: Not Checking Per-Node Free Space - -**WRONG:** -```sql --- INCORRECT: Checking total cluster capacity -SELECT SUM(capacity - used) / 1073741824.0 AS total_free_gb -FROM crdb_internal.kv_store_status; --- Total: 500 GB free across 3 nodes -``` - -**CORRECT:** -```sql --- CORRECT: Checking minimum per-node free space -SELECT MIN((capacity - used) / 1073741824.0) AS min_free_gb -FROM crdb_internal.kv_store_status; --- Min: 120 GB free (worst-case node) -``` - -**Why wrong?** Replicas distribute across nodes. Worst-case node (minimum free space) determines capacity limit. - ---- - -### Mistake 5: Parallel Index Creation Without Buffer - -**WRONG:** -```sql --- INCORRECT: Creating 3 indexes in parallel without checking combined requirement --- Index 1: 200 MB, Index 2: 250 MB, Index 3: 300 MB --- Assumes: 300 MB required (only checking largest) - -CREATE INDEX idx_a ON t(col_a); -CREATE INDEX idx_b ON t(col_b); -CREATE INDEX idx_c ON t(col_c); --- Actual required: 200 + 250 + 300 = 750 MB (UNDERESTIMATED) -``` - -**CORRECT:** -```sql --- CORRECT: Sequential creation or account for parallel overhead --- Option 1: Sequential (safer) -CREATE INDEX idx_a ON t(col_a); -- Wait for completion -CREATE INDEX idx_b ON t(col_b); -- Wait for completion -CREATE INDEX idx_c ON t(col_c); -- Wait for completion --- Required: 300 MB (worst case at any given time) - --- Option 2: Parallel (if necessary, with buffer) --- Check: MIN(free space) ≥ 750 MB + 20% buffer = 900 MB -``` - -**Why wrong?** Parallel backfills compound storage requirements. Sequential execution limits risk to single worst-case index. - ---- - -## Quick Reference: Calculation Checklist - -- [ ] Use `MAX(span_stats->>'approximate_disk_bytes')`, NOT average -- [ ] Apply multiplier to largest range, NOT total table size -- [ ] Use `approximate_disk_bytes`, NOT `live_bytes` -- [ ] Check `MIN(free space)` across nodes, NOT total cluster capacity -- [ ] Use 4× for production CREATE INDEX, 5× for ALTER PRIMARY KEY -- [ ] For parallel operations, SUM individual requirements + buffer -- [ ] Validate capacity BEFORE executing DDL -- [ ] Monitor disk usage DURING backfill execution - ---- - -## Related Documentation - -- [Main skill documentation](../SKILL.md) -- [Permissions reference](permissions.md) -- [CockroachDB Online Schema Changes](https://www.cockroachlabs.com/docs/stable/online-schema-changes.html) -- [SHOW RANGES documentation](https://www.cockroachlabs.com/docs/stable/show-ranges.html)