Ranges, Replicas and the PostgreSQL Compatibility Boundary

Article · 6:00

The key space, ranges, replicas and leaseholders; the SQL shell; and an explicit list of where PostgreSQL habits break.

There is one sorted key space. Every table and index in the cluster is encoded into one monolithic sorted map of keys to values. A table's primary key determines where its rows sit in that order, and that single fact drives most of this course.

The key space is cut into ranges. A range is a contiguous slice, by default up to 512 MiB, and it is the unit of replication, distribution and movement. When a range grows past the limit it splits; when traffic is uneven, the cluster rebalances ranges between nodes.

Each range is replicated, by default three times, using Raft. The replicas elect a leader, and writes are committed when a quorum - a majority, so two of three - has durably acknowledged them. This is where the cluster's resilience comes from and also where its write latency comes from: a write is never faster than the round trip to the second-closest replica.

One replica per range holds the lease. The leaseholder serves all reads and coordinates all writes for its range. Which node holds the lease therefore determines the latency of operations on that data, and in a multi-region cluster that is the single most important performance fact there is.

The PostgreSQL boundary. CockroachDB speaks the PostgreSQL wire protocol, so psql, JDBC, pgx, psycopg and your ORM all connect. Most SQL works. What does not:

  • No stored procedures with the full PL/pgSQL surface - support has been growing but assume it is not there.
  • No triggers until recently, and not the full PostgreSQL semantics.
  • Serializable is the only isolation level by default. READ COMMITTED is now available and must be enabled deliberately; there is no REPEATABLE READ in PostgreSQL's sense.
  • SERIAL is not a sequence of consecutive integers. It defaults to unique_rowid(), which produces unordered values - deliberately, to avoid hot ranges.
  • Schema changes are online and asynchronous. ALTER TABLE ... ADD COLUMN returns before the change is complete and runs as a background job. There is no long exclusive lock, and also no moment when you can assume it has finished.
  • No LISTEN/NOTIFY, no extensions, no PostGIS-equivalent at parity (spatial support exists and is its own implementation).
  • pg_catalog exists for compatibility and is not complete. Use crdb_internal and SHOW statements for real introspection.

Laboratory exercise 1 - see the ranges move.

Start a multi-node cluster. cockroach demo --nodes 3 is the quickest route; a three-node start cluster is more realistic.

Create a table and load at least one million rows - enough that the table occupies several ranges. Then watch it split: query crdb_internal.ranges before and after the load and record the range count, and find the same information in the DB Console's Databases page.

Identify, for one specific range, which nodes hold its replicas and which holds the lease. Then kill the leaseholder node and watch the lease move. Record how long the table was unavailable - it should be seconds, and knowing the actual number is the point.

Finally, test the compatibility boundary: attempt five things that work in PostgreSQL and do not work here, and record the exact error for each.

Deliverable: a setup.sql and a README, the range count before and after loading, the replica and leaseholder map for one range, the measured lease transfer time, and the five compatibility failures with their error messages.

-- ------------------------------------------------------------------
-- The cluster, and where the data actually is.
-- ------------------------------------------------------------------
--   cockroach demo --nodes 3 --insecure
--   cockroach sql --insecure --host localhost:26257
--   DB Console: http://localhost:8080  <- keep this open all course

SELECT node_id, address, locality, is_live FROM crdb_internal.gossip_nodes;
SHOW REGIONS FROM CLUSTER;

CREATE DATABASE IF NOT EXISTS shop;
USE shop;

-- ------------------------------------------------------------------
-- Primary keys: the single most consequential choice here.
-- ------------------------------------------------------------------
CREATE TABLE customer (
    -- UUID, not a sequence. A sequential key sends EVERY insert to the
    -- range holding the current maximum, so one range - and therefore
    -- ONE NODE - takes the whole write load however many nodes you own.
    -- This is THE classic CockroachDB mistake.
    id            UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
    email         STRING NOT NULL UNIQUE,
    name          STRING NOT NULL,
    credit_limit  DECIMAL(19,4) NOT NULL DEFAULT 0
                      CHECK (credit_limit >= 0),
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- SERIAL exists, and is NOT what PostgreSQL means by it:
CREATE TABLE audit_demo (id SERIAL PRIMARY KEY, note STRING);
SHOW CREATE TABLE audit_demo;
--   id INT8 NOT NULL DEFAULT unique_rowid()
-- unique_rowid() is unique and UNORDERED, by design, so inserts spread
-- across ranges. Code that assumes consecutive ids is wrong.

-- If you genuinely need ordered-ish keys and still want distribution,
-- hash-shard the index: the leading column is a computed bucket.
CREATE TABLE event_log (
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    id         UUID NOT NULL DEFAULT gen_random_uuid(),
    payload    JSONB,
    PRIMARY KEY (created_at, id) USING HASH WITH (bucket_count = 8)
);
--                               ^^^^^^^^^^ spreads a monotonic key
-- across 8 ranges. Costs an extra column in every scan; worth it when
-- the alternative is one hot range.

-- ------------------------------------------------------------------
-- Load enough to force splits.
-- ------------------------------------------------------------------
INSERT INTO customer (email, name, credit_limit)
SELECT 'c' || i::STRING || '@example.test', 'Customer ' || i::STRING,
       (random() * 50000)::DECIMAL(19,4)
FROM generate_series(1, 1000000) AS g(i);

-- ------------------------------------------------------------------
-- Ranges, replicas and leaseholders - the deliverable.
-- ------------------------------------------------------------------
SELECT count(*) AS range_count FROM [SHOW RANGES FROM TABLE customer];
--     ^^^^^^^ [SHOW ...] as a table source: a Cockroach extension
--             that lets you aggregate over a SHOW statement.

SELECT range_id, start_pretty, end_pretty,
       replicas, lease_holder, range_size / 1024 / 1024 AS mb
FROM crdb_internal.ranges WHERE table_name = 'customer'
ORDER BY range_id LIMIT 10;
--   replicas: {1,2,3}   lease_holder: 2
-- The leaseholder serves ALL reads and coordinates ALL writes for that
-- range. In a multi-region cluster this one number decides your
-- latency.

-- Default replication. 3 survives one node; 5 survives two.
SELECT target, raw_config_sql FROM [SHOW ZONE CONFIGURATION FOR RANGE default];

-- ------------------------------------------------------------------
-- THE COMPATIBILITY BOUNDARY. Run these. Record the errors.
-- ------------------------------------------------------------------
-- 1. Isolation levels. SERIALIZABLE is the default and was the only
--    one for years. READ COMMITTED must be enabled deliberately:
SHOW TRANSACTION ISOLATION LEVEL;      -- serializable
SET CLUSTER SETTING sql.txn.read_committed_isolation.enabled = true;
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;  -- mapped, not native
ROLLBACK;

-- 2. LISTEN / NOTIFY: not implemented. No pub-sub from the database.
--    LISTEN my_channel;   -> unimplemented

-- 3. Extensions: there is no CREATE EXTENSION ecosystem.
--    CREATE EXTENSION pg_trgm;   -> unimplemented

-- 4. Schema changes are ONLINE and ASYNCHRONOUS. This returns before
--    the work is done:
ALTER TABLE customer ADD COLUMN loyalty_tier STRING NOT NULL DEFAULT 'bronze';
SHOW JOBS;      -- the backfill is a background job. There is no long
                -- exclusive lock, and also no moment you may assume
                -- it has finished. Poll the job.

-- 5. pg_catalog exists for compatibility and is incomplete. Use the
--    real introspection:
SELECT * FROM [SHOW CREATE TABLE customer];
SELECT * FROM crdb_internal.table_indexes WHERE descriptor_name = 'customer';

Discussion

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