Capstone - Multi-Region Order Service

Article · 4:00

Retry-safe writes, regional outage simulation, per-region latency and a cost model that includes egress.

The system. A multi-region order service: customers in three regions, orders and lines placed locally, inventory that must not go negative, and reporting across all regions. Every write path is retry-safe. The database survives the loss of a region.

Three invariants must hold:

  1. An order's total equals the sum of its lines.
  2. Inventory never goes negative under any concurrency, including under retries - a retried transaction must not apply twice.
  3. No order exists for a customer whose credit limit it exceeded.

Invariant 2 is the one that distinguishes this capstone. In a single-node database a retry is a repeat of a failed attempt. Here, after a 40003, the first attempt may have succeeded, so the retry must be idempotent or verified. A client-supplied idempotency key with a unique constraint is the standard answer and your design should use one.

What is assessed. 20% knowledge checks, 35% laboratory portfolio, 15% troubleshooting practical, 30% capstone. Three things carry the capstone.

Retry-safe correctness. Your tests must drive enough contention to produce 40001 errors, show the retry loop handling them, and show the invariants holding afterwards. A capstone with no retries in its logs has not been loaded hard enough.

Measured performance, per region, against a declared baseline. Declare it first: cluster topology, survival goal, dataset, workload mix, and p50/p95/p99 by region for order placement and your reports. Include the retry rate - it is a performance number here, not only a correctness one.

A defensible account of failure modes, operational limits and cost. The survival goal must be stated with its measured write latency cost. The cost model must include inter-region egress, which is continuous. And the design must say which queries use follower reads and why their staleness is acceptable.

Deliverables: architecture diagram with regions and survival goal; data model with locality choices argued; source code including the retry loop; reproducible test dataset; benchmark report with per-region percentiles and retry rates; security review; recovery runbook with measured RPO and RTO from an actual restore and a survived regional outage; cost model including egress; and a short design defence.

-- ================= Invariants, as runnable assertions ==============
-- Schedule these. Run after every deployment, every failover and
-- every restore.

-- 1. Order totals agree with their lines.
SELECT o.id, o.total AS recorded, coalesce(sum(l.quantity*l.unit_price),0) AS derived
FROM orders o LEFT JOIN order_line l ON l.order_id = o.id
GROUP BY o.id, o.total
HAVING o.total <> coalesce(sum(l.quantity*l.unit_price),0);
-- Expected: no rows.

-- 2. Inventory never negative.
SELECT product_id, on_hand FROM inventory WHERE on_hand < 0;
-- Expected: no rows.

-- 3. Nothing exceeded its credit limit.
SELECT c.id, c.credit_limit, sum(o.total) AS outstanding
FROM customer c JOIN orders o ON o.customer_id = c.id
WHERE o.status IN ('pending','shipped')
GROUP BY c.id, c.credit_limit
HAVING sum(o.total) > c.credit_limit;
-- Expected: no rows.

-- ================= IDEMPOTENCY: the capstone's real problem ========
-- In a single-node database a retry repeats a FAILED attempt. Here,
-- after 40003 (ambiguous commit), the first attempt MAY HAVE
-- SUCCEEDED. A blind retry double-applies.
CREATE TABLE order_request (
    idempotency_key UUID PRIMARY KEY,   -- supplied by the CLIENT
    order_id        UUID NOT NULL,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Every write path starts here:
INSERT INTO order_request (idempotency_key, order_id)
VALUES ($1, $2)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING order_id;
-- Zero rows means this request already succeeded. Return the existing
-- order rather than placing a second one. This is what makes the
-- retry loop SAFE rather than merely present.

-- ================= Stock, atomically ===============================
-- One statement. No interleaving can break it, and no retry can
-- double-apply it beyond what the idempotency key already prevents.
UPDATE inventory SET on_hand = on_hand - $2
WHERE product_id = $1 AND on_hand >= $2
RETURNING on_hand;
-- Zero rows = refused. Not an error to retry; a business answer.

-- ================= Declare the baseline BEFORE measuring ===========
--
--   Topology:   9 nodes, 3 regions (us-east1, us-west1, europe-west1)
--   Survival:   REGION   <- state it, and its cost
--   Localities: orders / order_line  REGIONAL BY ROW
--               customer             REGIONAL BY ROW
--               product / currency   GLOBAL
--   Dataset:    1,000,000 customers, 10,000,000 orders
--   Workload:   60% reads, 40% writes, origin split 40/30/30 by region
--
--   Claim, PER REGION, measured from the client:
--                        us-east1   us-west1   europe-west1
--     place_order p50      __ ms      __ ms        __ ms
--     place_order p99      __ ms      __ ms        __ ms
--     order read p99       __ ms      __ ms        __ ms
--     dashboard p99        __ ms      __ ms        __ ms   (follower)
--     retry rate           __ %       __ %         __ %
--
--   One average across regions describes an experience nobody has.
--   And the retry rate is a PERFORMANCE number here, not only a
--   correctness one.

-- Measured, not asserted:
SELECT metadata->>'query',
       (statistics->'statistics'->>'cnt')::INT AS execs,
       (statistics->'statistics'->>'maxRetries')::INT AS max_retries,
       round((statistics->'statistics'->'runLat'->>'mean')::FLOAT*1000,2) AS mean_ms
FROM crdb_internal.node_statement_statistics
WHERE metadata->>'query' LIKE '%order%'
ORDER BY execs DESC LIMIT 10;

-- ================= Survive a region, and prove it ==================
ALTER DATABASE shop SURVIVE REGION FAILURE;
SELECT * FROM [SHOW SURVIVAL GOAL FROM DATABASE shop];

-- Kill every node in one region while the workload runs. Record:
--   writes failed for          ___ seconds
--   lease transfers completed  ___ seconds
--   committed writes lost      0        <- must be 0
--   write p99 during outage    ___ ms
--   write p99 after recovery   ___ ms
SELECT node_id, locality, is_live FROM crdb_internal.gossip_nodes;
SELECT count(*) FROM crdb_internal.ranges WHERE unavailable;   -- must be 0

-- ================= Cost model ======================================
--   nodes                9 x instance x 730 h
--   storage              provisioned GB + IOPS
--   INTER-REGION EGRESS  every write replicated across regions,
--                        continuously. write_bytes/s x cross-region
--                        replicas x $/GB x 2.6M s/month. This is the
--                        line item people omit, and under REGION
--                        survival it is every write, forever.
--   enterprise licence   multi-region, incremental backup, changefeeds
--   backup storage       object storage + retention

-- ================= Failure modes ===================================
--   40001 under load             expected. Retry loop handles it.
--                                Rising rate = a design problem.
--   40003 ambiguous commit       the idempotency key handles it.
--                                WITHOUT one, a double order.
--   node loss                    lease moves in seconds; connections
--                                do NOT fix themselves - the pool must
--                                retry, or you report a false outage
--   2 of 3 replicas lost         range UNAVAILABLE. Consistent, not
--                                serving. Restore quorum.
--   region loss                  survived only under REGION survival.
--                                Under ZONE survival: unavailable.
--   hot range                    one node saturated, cluster idle.
--                                Fix the key, not the hardware.
--   clock drift                  the node shuts ITSELF down. Run NTP.
--
-- Verify after EVERY failover and restore with the three assertions
-- above. "The cluster is up" is not verification.

Where to go from here

Longer reading about this subject, written alongside the course.

Course guide How to work through this course Why to do PostgreSQL first, the one habit that matters most, what the DB Console teaches, and what to skip. 3 min read

Discussion

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