Schema Design, Indexes and Locality-Aware Modeling

Article · 5:00

Keys that distribute, interleaved access through composite keys, covering indexes, online schema changes, and the regional and global table types.

Design for the key space, not just for the entity model. In a single-node database the primary key is mostly an identity question. Here it is also a placement question. Two rows that will always be read together should sort next to each other, so that reading them touches one range and therefore one network round trip rather than several.

The practical form of this is a composite primary key that leads with the parent's identifier: PRIMARY KEY (order_id, line_no) for order lines means all of an order's lines sort together, and fetching them is one range scan. The same table keyed on a standalone line_id scatters them across the cluster.

Indexes are themselves ranges, replicated and distributed like tables. Two consequences. First, every secondary index multiplies write cost - a write must update the table range and each index range, each with its own Raft round trip, so indexes are more expensive here than in PostgreSQL. Second, a covering index - one with STORING columns - avoids a second lookup that may be on a different node, so covering matters more here than it does locally.

Schema changes are online. They run as background jobs, in stages, without an exclusive lock. This is a genuine operational advantage and it demands a different habit: issue the change, then watch SHOW JOBS until it completes, and write deployment scripts that wait rather than assume.

Locality-aware modeling is where CockroachDB has features nothing else in this programme has. In a multi-region database each table has a locality:

  • REGIONAL BY TABLE - the whole table's leaseholders live in one named region. Fast there, a cross-region trip from anywhere else. The default.
  • REGIONAL BY ROW - each row has a region, stored in a hidden crdb_region column, and its leaseholder lives there. A European customer's rows are in Europe and a US customer's in the US, in one logical table. This is the feature people buy CockroachDB for.
  • GLOBAL - optimised for fast reads from every region at the cost of slow writes. Correct for reference data: currencies, product catalogues, feature flags.

The honest summary: REGIONAL BY ROW gives you local-latency reads and writes for correctly partitioned data, and a cross-region penalty for anything that touches several regions in one transaction. Choosing it means committing to a schema where transactions rarely cross regions.

Laboratory exercise 2 - two models, measured.

Design two schemas for the capstone's multi-region order service. Suggested contrast: one with independent UUID keys throughout, and one with composite keys that co-locate each order with its lines and payments.

Implement both. Write the representative queries: place an order, read an order with everything attached, list a customer's recent orders, and a revenue report by region.

Measure the difference in ranges touched, not just in time: use EXPLAIN ANALYZE and record the "distribution" and the number of ranges scanned for the order-read query in both models. This is the number that explains the latency.

Then set up a multi-region demo cluster and implement the same schema three ways - REGIONAL BY TABLE, REGIONAL BY ROW and GLOBAL for the reference tables - and measure a read and a write from each region.

Finally, perform an online schema change on a table under write load, and show that the writes never stopped.

Deliverable: both schemas, all queries, the ranges-touched comparison, the three-way locality measurement as a table of read and write latency by region, the schema change under load, and a page arguing for one model.

-- ------------------------------------------------------------------
-- Composite keys that CO-LOCATE related rows.
-- ------------------------------------------------------------------
CREATE TABLE orders (
    id          UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
    customer_id UUID NOT NULL REFERENCES customer (id),
    status      STRING NOT NULL DEFAULT 'pending'
                    CHECK (status IN ('pending','paid','shipped','cancelled')),
    total       DECIMAL(19,4) NOT NULL DEFAULT 0 CHECK (total >= 0),
    ordered_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    INDEX idx_orders_customer (customer_id, ordered_at DESC)
);

CREATE TABLE order_line (
    -- order_id FIRST. All of one order's lines sort together, so
    -- reading them is ONE range scan on ONE node. Keyed on a
    -- standalone line_id they scatter across the cluster and the same
    -- read becomes several network round trips.
    order_id   UUID NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
    line_no    INT NOT NULL,
    product_id UUID NOT NULL,
    quantity   INT NOT NULL CHECK (quantity > 0),
    unit_price DECIMAL(19,4) NOT NULL CHECK (unit_price >= 0),
    PRIMARY KEY (order_id, line_no)
);

-- ------------------------------------------------------------------
-- Covering indexes matter MORE here than in PostgreSQL: the second
-- lookup may be on a different NODE, not just a different page.
-- ------------------------------------------------------------------
CREATE INDEX idx_orders_status_covering
    ON orders (status, ordered_at DESC)
    STORING (customer_id, total);
--  ^^^^^^^ the index range answers the query completely. Without
--  STORING, every row needs a trip back to the primary index, which
--  may be a network hop.

-- And the cost: EVERY secondary index adds a Raft round trip to EVERY
-- write to this table. Indexes are more expensive here than locally.
-- Count them deliberately.
SELECT index_name, is_unique, created_at
FROM [SHOW INDEXES FROM orders];

-- ------------------------------------------------------------------
-- Ranges touched - the number that explains the latency.
-- ------------------------------------------------------------------
EXPLAIN ANALYZE
SELECT o.id, o.total, l.line_no, l.quantity
FROM orders o JOIN order_line l ON l.order_id = o.id
WHERE o.id = '...';
--   distribution: local            <- good
--   KV rows read: 4
--   KV bytes read: 312 B
--   ranges fully scanned: 1        <- THE number. Compare models here.
--
-- "distribution: full" means the plan fans out to every node. For a
-- single-order read that is a design error, not a tuning problem.

-- ------------------------------------------------------------------
-- MULTI-REGION: the feature nothing else here has.
-- ------------------------------------------------------------------
--   cockroach demo --nodes 9 --demo-locality \
--     region=us-east1,region=us-west1,region=europe-west1 ...

ALTER DATABASE shop SET PRIMARY REGION "us-east1";
ALTER DATABASE shop ADD REGION "us-west1";
ALTER DATABASE shop ADD REGION "europe-west1";
SHOW REGIONS FROM DATABASE shop;

-- 1. REGIONAL BY TABLE - leaseholders in ONE region. The default.
ALTER TABLE orders SET LOCALITY REGIONAL BY TABLE IN "us-east1";
--   us-east1 read:  ~2 ms     europe-west1 read:  ~85 ms
--   us-east1 write: ~5 ms     europe-west1 write: ~170 ms

-- 2. REGIONAL BY ROW - EACH ROW has a region, and its leaseholder
--    lives there. One logical table; data physically local to its
--    users. This is the feature people buy CockroachDB for.
ALTER TABLE customer ADD COLUMN region crdb_internal_region
    AS (CASE WHEN country IN ('GB','DE','FR') THEN 'europe-west1'
             WHEN country = 'US' THEN 'us-east1'
             ELSE 'us-west1' END) STORED;
ALTER TABLE customer SET LOCALITY REGIONAL BY ROW AS region;
--   A European customer reads and writes their own row in ~3 ms.
--   A transaction touching rows in TWO regions pays the cross-region
--   trip. Choosing this means committing to a schema where
--   transactions rarely cross regions.

-- 3. GLOBAL - fast reads everywhere, slow writes. Reference data.
CREATE TABLE currency (code STRING PRIMARY KEY, rate DECIMAL(12,6) NOT NULL)
    LOCALITY GLOBAL;
--   read from any region: ~2 ms      write from anywhere: ~250 ms
--   Correct for currencies, catalogues, feature flags. Catastrophic
--   for an orders table.

SELECT table_name, locality FROM [SHOW TABLES] WHERE locality IS NOT NULL;

-- ------------------------------------------------------------------
-- Online schema change, under load.
-- ------------------------------------------------------------------
ALTER TABLE orders ADD COLUMN shipping_region STRING;
CREATE INDEX idx_orders_region ON orders (shipping_region);

SELECT job_id, job_type, description, status, fraction_completed
FROM [SHOW JOBS] WHERE status IN ('running','pending');
-- Keep a write workload going throughout and show it never stopped.
-- Then write your deployment script to WAIT on the job rather than
-- assume it finished:
--   SHOW JOB WHEN COMPLETE <job_id>;

Discussion

No questions on this topic yet. Sign in to ask the first one.