Serializable Transactions, Retries and Distributed Execution

Article · 4:00

Serializable isolation, the 40001 retryable error and its mandatory retry loop, contention diagnosis, savepoints, and how a query is distributed.

Serializable is the default and it is not free. Under serializable isolation the database guarantees that concurrent transactions produce the same result as some serial order. No anomalies - no write skew, no phantom reads, none of the subtleties that make REPEATABLE READ interesting. The cost is that the database sometimes discovers, at commit time, that it cannot place a transaction in any valid order, and must abort it.

That abort is error code 40001, and it is retryable. This is the single most important operational fact in CockroachDB. It is not a bug, not a configuration problem and not avoidable - it is how serializable isolation is implemented. A 40001 means "this transaction could not be ordered; run it again and it will probably succeed".

Therefore: every application that writes to CockroachDB must implement a retry loop, with exponential backoff and jitter, around every transaction. An application without one is not finished, and will fail under exactly the load where you most need it not to. Most official drivers provide a helper - use it.

The related errors: 40003 (statement completion unknown, after an ambiguous commit), and restart transaction messages carrying RETRY_SERIALIZABLE, RETRY_WRITE_TOO_OLD or ABORT_REASON_PUSHER_ABORTED, which name the specific conflict.

Reducing retries is a design activity. Keep transactions short; order writes consistently; avoid read-modify-write where a conditional UPDATE would do; use SELECT ... FOR UPDATE to take the conflict early rather than at commit; and above all avoid a single hot row that every transaction touches - a counter, a sequence table, a "current balance" row - because that row serialises the whole system.

AS OF SYSTEM TIME is the escape hatch for reads. A read at a past timestamp needs no coordination at all and can be served by any replica, including the nearest one. AS OF SYSTEM TIME follower_read_timestamp() gives you a read a few seconds stale at local latency from anywhere in the world - excellent for reports and dashboards, wrong for anything that will be written back.

Distributed execution. The optimiser decides whether to run a query on the gateway node or distribute it. Aggregations and joins can be pushed down to the nodes holding the data, so that only partial results cross the network - genuinely clever, and visible in EXPLAIN as the distribution field and in the DistSQL diagram the DB Console draws.

Laboratory exercise 3 - force the retries, then reduce them.

Build a service that places orders and run at least 100 concurrent clients.

First, write it without a retry loop. Run the load. Record the failure rate and the exact error text. This is what a production incident looks like, and seeing it once is worth more than reading about it.

Then add a correct retry loop with exponential backoff and jitter, re-run, and record the retry rate and the latency distribution including retries.

Now reduce the retries by design: introduce a deliberately hot row - a single counter every transaction updates - and measure the retry rate. Remove it and measure again. Then convert one read-modify-write into a conditional UPDATE and measure again.

Finally, demonstrate AS OF SYSTEM TIME: run a reporting query normally and as a follower read, from a node that is not the leaseholder, and record both latencies.

Deliverable: the service in both forms, the failure rate without retries, the retry rate and latency with them, the three retry-reduction measurements, the follower read comparison, and a short note on which design change helped most.

-- ------------------------------------------------------------------
-- THE RETRY LOOP. Not optional. Not a tuning detail.
-- ------------------------------------------------------------------
-- Under SERIALIZABLE the database may discover at COMMIT that it
-- cannot order a transaction, and abort it with SQLSTATE 40001. That
-- is not a bug - it is how serializable isolation is implemented.
--
-- Pseudocode for what every writer must do:
--
--   for attempt in 1..MAX_RETRIES:
--       try:
--           BEGIN
--           ... statements ...
--           COMMIT
--           return
--       except SQLSTATE in ('40001', '40003'):
--           ROLLBACK
--           sleep(min(2^attempt * BASE, CAP) * (0.5 + random()/2))
--           continue            # <- jitter, or 100 clients retry in
--       except:                 #    lockstep and collide again
--           ROLLBACK; raise
--   raise TooManyRetries
--
-- Use the driver's helper where there is one:
--   Go:     crdb.ExecuteTx(ctx, db, nil, func(tx *sql.Tx) error {...})
--   Python: with conn.transaction(): ...   (sqlalchemy-cockroachdb)
--   Java:   the retry example in the official docs

-- Server-side SAVEPOINT, for retrying inside one connection:
BEGIN;
SAVEPOINT cockroach_restart;
    UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = '...';
    INSERT INTO order_line (order_id, line_no, product_id, quantity, unit_price)
    VALUES ('...', 1, '...', 1, 9.99);
RELEASE SAVEPOINT cockroach_restart;
COMMIT;
-- On 40001: ROLLBACK TO SAVEPOINT cockroach_restart; and run it again.

-- ------------------------------------------------------------------
-- The errors, and what each one names.
-- ------------------------------------------------------------------
--  40001 RETRY_SERIALIZABLE        could not be ordered; retry
--  40001 RETRY_WRITE_TOO_OLD       another txn wrote this key first
--  40001 ABORT_REASON_PUSHER_ABORTED  pushed by a conflicting txn
--  40003 statement completion unknown
--        The commit was AMBIGUOUS. It may have succeeded. A blind
--        retry can therefore DOUBLE-APPLY. Make the write idempotent -
--        a client-supplied idempotency key with a unique constraint -
--        or verify before retrying.

-- ------------------------------------------------------------------
-- Reducing retries BY DESIGN. The measurements for the lab.
-- ------------------------------------------------------------------
-- 1. A hot row serialises the whole system. Do not do this:
--      UPDATE counters SET order_count = order_count + 1 WHERE id = 1;
--    Every transaction contends on one key. Retry rate goes to the
--    ceiling and no amount of retrying helps.
--    Instead: shard the counter, or aggregate from the orders table.

-- 2. Replace read-modify-write with ONE conditional statement.
--    Bad - two statements, a window between them, contention at commit:
--      SELECT on_hand FROM inventory WHERE product_id = $1;
--      UPDATE inventory SET on_hand = $2 WHERE product_id = $1;
--    Good - one atomic statement that cannot interleave wrongly:
UPDATE inventory SET on_hand = on_hand - $2
WHERE product_id = $1 AND on_hand >= $2
RETURNING on_hand;
-- Zero rows returned means it was refused. No retry needed at all.

-- 3. Take the conflict EARLY rather than at commit:
BEGIN;
SELECT on_hand FROM inventory WHERE product_id = $1 FOR UPDATE;
-- ... decide ...
COMMIT;
-- Fewer 40001s, more waiting. Measure which your workload prefers.

-- ------------------------------------------------------------------
-- Diagnosing contention. These two views are the first stop.
-- ------------------------------------------------------------------
SELECT table_name, index_name, num_contention_events, cumulative_contention_time
FROM crdb_internal.cluster_contention_events
ORDER BY num_contention_events DESC LIMIT 10;

SELECT key, count(*) AS events,
       sum(contention_duration) AS total_wait
FROM crdb_internal.transaction_contention_events
GROUP BY key ORDER BY events DESC LIMIT 10;
--  ^^^ this finds your hot row. It is almost always one key.

SELECT * FROM crdb_internal.cluster_locks WHERE granted = false;

-- ------------------------------------------------------------------
-- AS OF SYSTEM TIME: reads with NO coordination at all.
-- ------------------------------------------------------------------
SELECT count(*), sum(total) FROM orders
AS OF SYSTEM TIME follower_read_timestamp()
WHERE ordered_at > now() - INTERVAL '7 days';
--     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- Served by the NEAREST replica, not the leaseholder. No consensus,
-- no cross-region trip: ~2 ms from anywhere in the world instead of
-- ~170 ms. The data is a few seconds stale (default ~4.8 s).
--
-- Correct for reports, dashboards and analytics.
-- WRONG for anything that will be written back: you would be deciding
-- on data that has since changed, which is the write-skew bug
-- serializable isolation exists to prevent.

-- An exact past moment, for an investigation:
SELECT * FROM orders AS OF SYSTEM TIME '-30s' WHERE id = '...';

-- ------------------------------------------------------------------
-- Distributed execution: what crosses the network.
-- ------------------------------------------------------------------
EXPLAIN (DISTSQL)
SELECT c.region, count(*), sum(o.total)
FROM customer c JOIN orders o ON o.customer_id = c.id
GROUP BY c.region;
-- The aggregation is pushed to the nodes holding the data, so only
-- PARTIAL AGGREGATES cross the network rather than rows. The DB
-- Console draws the flow diagram; it is worth looking at once.

SELECT * FROM crdb_internal.node_statement_statistics
ORDER BY (statistics->'statistics'->>'cnt')::INT DESC LIMIT 10;

Discussion

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