Read the plan for distribution first, then for the usual things. EXPLAIN ANALYZE gives you the familiar information - rows read, index used, estimated against actual - plus the field that matters most here: distribution, which is local or full. For a point read or a small range scan, full means the query is fanning out to the whole cluster and something is wrong with the key or the index. Also read ranges fully scanned and KV bytes read: those count network work, which is the dominant cost.
Hot ranges are the characteristic CockroachDB performance problem, and they have no equivalent in a single-node database. A range receiving disproportionate traffic becomes the cluster's bottleneck however many nodes you add, because the leaseholder is one process on one machine. The usual causes: a sequential primary key, a timestamp-leading index, a small table every query joins, or a single counter row. The DB Console has a Hot Ranges page; crdb_internal.ranges and the SHOW RANGES WITH DETAILS output give you the same data.
The fixes, in order of preference: change the key to distribute (UUID, or hash-sharded for a monotonic key); split the range manually with ALTER TABLE ... SPLIT AT for a known-hot boundary; or, for a small hot table, make it GLOBAL so reads are served locally everywhere.
Statistics. The cost-based optimiser needs table statistics, collected automatically by default. After a bulk load, collect them explicitly - plans chosen on an empty table's statistics are usually bad.
Admission control is CockroachDB's overload protection: when a node is saturated, it queues lower-priority work rather than degrading everything. The consequence to understand is that under overload you will see latency rather than errors, and the queueing is visible in the admission metrics. A cluster that looks "slow but fine" may be shedding load gracefully, and knowing which is which requires looking.
Measuring latency honestly in a distributed system means three things. Measure from the client, not from the server, because the network is the point. Report p50, p95 and p99 separately, because a distributed system's tail is where the interesting failures live. And measure from each region in a multi-region cluster, because one number is the average of experiences nobody has.
Laboratory exercise 4 - a measured improvement.
Load at least five million rows across a realistic schema. Declare a baseline: five queries with p50, p95 and p99 measured from the client, plus distribution, ranges scanned and KV bytes for each.
Deliberately create a hot range: add a table with a sequential or timestamp-leading primary key and drive writes at it. Find it on the Hot Ranges page, show the one node's CPU saturating while the others idle, then fix it with hash sharding and re-measure.
Apply the other techniques one at a time and re-measure: a covering index, statistics collection after a load, a locality change, and a follower read for one report.
Then drive the cluster into admission control: push load past capacity and show the queueing in the metrics, with latency rising while errors do not.
Deliverable: the benchmark report with all percentiles at each step, EXPLAIN ANALYZE before and after, the hot range screenshot or metrics with the per-node CPU, the admission control evidence, and one change that did not help.
-- ------------------------------------------------------------------
-- Read the plan for DISTRIBUTION first.
-- ------------------------------------------------------------------
EXPLAIN ANALYZE
SELECT o.id, o.total, c.name
FROM orders o JOIN customer c ON c.id = o.customer_id
WHERE o.ordered_at > now() - INTERVAL '1 day' AND o.status = 'pending';
--
-- planning time: 1.2ms execution time: 847ms
-- distribution: full <- fanning out to every node
-- vectorized: true
-- rows read from KV: 4,012,338 <- reading 4M to return 200
-- cumulative time spent in KV: 791ms
-- ranges fully scanned: 1,204 <- THE number. Network work.
--
-- `distribution: full` on a query that should touch a day of data is
-- a key or index problem, not a tuning problem.
-- ------------------------------------------------------------------
-- HOT RANGES: the characteristic distributed performance problem.
-- ------------------------------------------------------------------
SELECT table_name, index_name, range_id, lease_holder,
queries_per_second, replicas
FROM crdb_internal.ranges
ORDER BY queries_per_second DESC LIMIT 10;
-- DB Console -> Advanced Debug -> Hot Ranges shows the same.
--
-- One range at 40,000 qps while the rest are at 50 means ONE NODE is
-- your entire cluster. Adding nodes changes nothing, because the
-- leaseholder is one process on one machine.
-- Confirm it: one node's CPU at 95%, the others at 10%.
SELECT node_id, (metrics->>'sys.cpu.combined.percent-normalized')::FLOAT * 100
AS cpu_pct
FROM crdb_internal.kv_node_status ORDER BY cpu_pct DESC;
-- The usual causes:
-- sequential primary key every insert at the maximum
-- timestamp-leading index same, on the index
-- small table joined by all one range, every query
-- a single counter row one key, every transaction
-- Fix 1, best: make the key distribute.
ALTER TABLE event_log ALTER PRIMARY KEY USING COLUMNS (created_at, id)
USING HASH WITH (bucket_count = 16);
-- Fix 2: split a known-hot boundary by hand.
ALTER TABLE orders SPLIT AT VALUES ('80000000-0000-0000-0000-000000000000');
ALTER TABLE orders UNSPLIT ALL; -- let the cluster manage it again
-- Fix 3: a small hot table read everywhere -> GLOBAL.
ALTER TABLE product SET LOCALITY GLOBAL;
-- ------------------------------------------------------------------
-- Statistics. Plans from an empty table's statistics are bad plans.
-- ------------------------------------------------------------------
CREATE STATISTICS ON customer_id, ordered_at, status FROM orders;
SELECT statistics_name, column_names, row_count, distinct_count, created
FROM [SHOW STATISTICS FOR TABLE orders];
SHOW CLUSTER SETTING sql.stats.automatic_collection.enabled;
-- Automatic by default. Still collect explicitly after a bulk load:
-- the automatic pass may not have run yet and your benchmark will
-- measure a plan nobody will ever get in production.
-- ------------------------------------------------------------------
-- ADMISSION CONTROL: why overload looks like latency, not errors.
-- ------------------------------------------------------------------
SELECT node_id,
(metrics->>'admission.wait_durations.kv-p99')::FLOAT AS kv_wait_p99,
(metrics->>'admission.wait_queue_length.kv')::FLOAT AS kv_queued,
(metrics->>'admission.wait_durations.sql-kv-response-p99')::FLOAT
FROM crdb_internal.kv_node_status;
--
-- When a node saturates, lower-priority work is QUEUED rather than
-- everything degrading. So under overload you see LATENCY, not errors.
-- A cluster that looks "slow but fine" may be shedding load
-- gracefully - and only these metrics tell you which.
SHOW CLUSTER SETTING admission.kv.enabled;
-- Leave it on. Turning it off does not make the cluster faster; it
-- makes overload look like failure instead of like queueing.
-- ------------------------------------------------------------------
-- Measuring honestly.
-- ------------------------------------------------------------------
SELECT metadata->>'query' AS query,
(statistics->'statistics'->>'cnt')::INT AS execs,
round((statistics->'statistics'->'runLat'->>'mean')::FLOAT*1000, 2) AS mean_ms,
round((statistics->'statistics'->'runLat'->>'sqDiff')::FLOAT, 2) AS variance,
(statistics->'statistics'->>'maxRetries')::INT AS max_retries
FROM crdb_internal.node_statement_statistics
ORDER BY execs DESC LIMIT 15;
-- ^^^^^^^^^^^ retries belong in
-- the performance report, not only the correctness one.
--
-- Three rules for a distributed system:
-- 1. measure from the CLIENT - the network is the point
-- 2. report p50, p95 AND p99 - the tail is where it fails
-- 3. measure from EACH REGION - one number is an average of
-- experiences nobody actually has
Discussion
No questions on this topic yet. Sign in to ask the first one.