Project: shard the shop
Move the live shop from one Postgres to a Citus cluster with replicas: copy, catch up, verify, switch, with a load running the whole time and a checker that proves nothing was lost
The brief
The shop runs on one Postgres, db from labs/databases/compose.yaml. It has to move to the Citus cluster from the partitioning and sharding chapter: a coordinator coord and workers w1 and w2 from labs/databases/citus.yaml, sharded by customer, with a hot standby behind every node. Then it has to grow to a third worker. A load generator places orders, pays them and reads customers’ order lists at about 200 operations a second from the first step to the last, and it is not allowed to see an error.
What you build:
- The target cluster with replicas.
coord,w1,w2, each with a streaming standby (coordr,w1r,w2r), the worker standbys registered in Citus as secondaries so read-only sessions can use them. - An expand step on the source. Sharded by customer,
order_itemsandpaymentsneed acustomer_idcolumn. You add it and backfill 800 000 rows without stopping the load. - A change follower. Copy every table, then keep the target current from a change log until you switch. You write this:
sync.py, withcapture,copy,follow,drain,fence,unfenceandsequences. - A cutover script. Pause the pooler, drain the log, fence the old database, verify every row, move the sequences, repoint the pooler, resume. On any failure it must leave traffic on the old database with nothing lost. You write this:
cutover.sh. - Evidence. A checker (given) compares the two sides while the load runs, verifies every row exactly at the cutover, proves that every order the load was told had committed exists on the new side with the same total, and compares Citus primaries with their standbys.
Why a trigger log and not logical replication
The partitioning chapter’s rebalancer moves shards with logical replication between Citus nodes, and Notion moved between Postgres databases the same way. Here the source schema and the target schema differ (customer_id on the child tables, composite primary keys, reference tables), and a subscription into a Citus coordinator is not where you want to debug a first migration. A trigger that logs only which row changed, and a follower that re-reads the current row and upserts it, works between any two schemas, is idempotent by construction, and is small enough to reason about completely. The cost is one extra insert per write on the source, which at this load is nothing. At Notion’s scale, use the database’s own replication.
The follower has one trap, and finding it is the point of the project. The obvious design reads WHERE seq > last_seen and remembers the highest seq it has applied. But seq is taken when the trigger fires, not when the transaction commits. A transaction that took seq 100 and is slow to commit becomes visible after the follower has applied 101 and moved its mark past it, and change 100 is never applied. The bug shows up only under concurrency and only occasionally, which is the worst kind. The fix uses the snapshot: a change is safe to consume only when its transaction id is below pg_snapshot_xmin(pg_current_snapshot()), the oldest transaction still in flight. Everything below that line has finished; nothing new can appear below it.
The cutover, in order
PAUSE shopin PgBouncer: in-flight transactions finish, server connections close, new queries wait.- Drain: apply the change log until it is empty.
- Fence: make the old database read-only for new sessions and terminate the ones left, so nothing that bypasses the pooler can write to it. A silent write to the old copy after the switch is lost data; the failover chapter called this split brain.
- Verify: a count and a checksum of every column of every row of all six tables, on both sides. Any difference aborts.
- Sequences: set the target’s id sequences past the source’s.
- Repoint PgBouncer at
coord,RELOAD,RESUME shop.
The pause lasts as long as steps 2 to 6 take, a few seconds here. Each step before the RELOAD can be undone by unfencing and resuming on the old database. Writing that abort path and rehearsing it before the real cutover is part of the project.
Rules
- The load runs from step 4 to the end. Restarting it is allowed only where a step says so.
- No
docker compose downon the shop and no manual edits to rows except where a step tells you to make one. - Everything runs at scale 0.1. At scale 1 the copy and backfill are ten times longer; the procedure is the same.
Rubric
| criterion | passes when |
|---|---|
| target cluster | pg_dist_node lists coord, w1, w2 as primaries and w1r, w2r as secondaries; pg_stat_replication on each primary shows its standby streaming |
| expand and backfill | zero order_items or payments rows with a null customer_id, done while the load ran with no errors |
| follower correctness | check.py window shows MATCH on all four lines while the load runs; your follower uses the xmin rule, and you can explain what breaks without it |
| abort rehearsal | a deliberately corrupted target row makes cutover.sh abort; traffic stays on the old database; you repair the row through the follower and the next exact check matches |
| cutover | the load prints no errors; the longest request in the cutover window is under 10 s; check.py exact matched inside the pause; PgBouncer points at coord afterwards |
| no lost writes | check.py acked reports 0 lost and 0 wrong totals after the cutover and again after the rebalance |
| fencing | a write to the old database after the cutover fails with cannot execute ... in a read-only transaction |
| growth | w3 and w3r join, the rebalance completes under load, check.py replicas matches |
| runbook | a half-page written note: the steps, how long the pause was, the abort conditions, and how you would make the switch reversible after RESUME |
Stretch goals, for a senior answer: run the follower in reverse after the cutover so that you could switch back; handle inventory decrements at checkout without a two-phase commit on every order (it is a reference table, so every write touches every node); restore a global unique email with a table distributed by email.
The lab stack
All files live in a new directory, labs/databases/shard/. The override shard/compose.yaml is used together with citus.yaml, so every docker compose command in the lab runs against the atlas-citus project once COMPOSE_FILE=citus.yaml:shard/compose.yaml is exported; the shop is addressed with -f compose.yaml. Ports: shop 5432, coordinator 5450, PgBouncer 6440. The standbys are not published to the host. Python scripts run on the host from labs/databases with a venv in shard/.venv.
Terminal 1 runs the steps, terminal 2 runs the load, terminal 3 runs the follower. In terminal 1, define two helpers for psql on each side (they last for that shell):
cd labs/databases
P() { docker compose -f compose.yaml exec -T db psql -U atlas -d shop "$@"; }
C() { docker compose exec -T coord psql -U atlas -d shop "$@"; }1. Clear the old cluster and write the stack.
If the Citus cluster from the partitioning chapter is still up, remove it first: docker compose -f citus.yaml down -v. Then create shard/compose.yaml:
# Override on citus.yaml for databases/project-shard-the-shop (module D3).
#
# export COMPOSE_FILE=citus.yaml:shard/compose.yaml # from labs/databases
# docker compose up -d
#
# Adds a hot standby for the coordinator and for each worker (coordr, w1r, w2r; w3r with
# the grow profile) and a PgBouncer, `bouncer`, on host port 6440 that the shop's load
# connects through. bouncer also joins the shop's network (databases_default) so that it
# can reach the old database as `db`. Paths are relative to citus.yaml.
# About 3 GB of RAM in all with the shop. Tear down: docker compose down -v
x-standby: &standby
image: citusdata/citus:14.2.0-pg17
user: postgres
shm_size: 128m
entrypoint: ["bash", "/etc/atlas/standby.sh"]
services:
coordr:
<<: *standby
environment: { PRIMARY: coord, NODE: coordr }
depends_on: { coord: { condition: service_healthy } }
volumes: [./shard:/etc/atlas:ro, coordr-data:/var/lib/postgresql/data]
w1r:
<<: *standby
environment: { PRIMARY: w1, NODE: w1r }
depends_on: { w1: { condition: service_healthy } }
volumes: [./shard:/etc/atlas:ro, w1r-data:/var/lib/postgresql/data]
w2r:
<<: *standby
environment: { PRIMARY: w2, NODE: w2r }
depends_on: { w2: { condition: service_healthy } }
volumes: [./shard:/etc/atlas:ro, w2r-data:/var/lib/postgresql/data]
w3r:
<<: *standby
profiles: ["grow"]
environment: { PRIMARY: w3, NODE: w3r }
depends_on: { w3: { condition: service_healthy } }
volumes: [./shard:/etc/atlas:ro, w3r-data:/var/lib/postgresql/data]
bouncer:
image: edoburu/pgbouncer:v1.24.1-p0
ports: ["6440:6432"]
volumes: [./shard/pgbouncer:/etc/pgbouncer:ro] # our own pgbouncer.ini; the cutover edits it
networks: [default, shop]
networks:
shop:
external: true
name: databases_default
volumes:
coordr-data:
w1r-data:
w2r-data:
w3r-data:shard/standby.sh, which retries the base backup until the primary accepts replication connections:
#!/bin/bash
# Entrypoint for the hot standbys in shard/compose.yaml. First start: clone $PRIMARY with
# pg_basebackup, retrying until the primary accepts replication connections. Then run.
set -uo pipefail
export PGDATA=/var/lib/postgresql/data/pgdata
if [ ! -s "$PGDATA/PG_VERSION" ]; then
until pg_isready -q -h "$PRIMARY" -U atlas -d shop; do sleep 1; done
until
psql -h "$PRIMARY" -U atlas -d shop -Atqc "SELECT pg_drop_replication_slot(slot_name)
FROM pg_replication_slots WHERE slot_name = '$NODE' AND NOT active" >/dev/null
pg_basebackup -h "$PRIMARY" -U atlas -D "$PGDATA" -X stream -R -C -S "$NODE" --checkpoint=fast
do
echo "base backup of $PRIMARY failed (is the replication line in its pg_hba.conf?); retrying in 3 s"
rm -rf "$PGDATA"; sleep 3
done
fi
exec postgres -D "$PGDATA" -c cluster_name="$NODE"And PgBouncer’s two files, shard/pgbouncer/pgbouncer.ini and shard/pgbouncer/userlist.txt. The pooler starts pointed at the old database:
[databases]
shop = host=db port=5432 dbname=shop user=atlas password=atlas
[pgbouncer]
listen_addr = *
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
admin_users = atlas
pool_mode = transaction
default_pool_size = 20
max_client_conn = 200printf '"atlas" "atlas"\n' > shard/pgbouncer/userlist.txt
export COMPOSE_FILE=citus.yaml:shard/compose.yaml # in all three terminals
docker network ls --filter name=databases_default --format '{{.Name}}'
docker compose up -ddatabases_default, the shop’s network, which bouncer joins. up starts seven containers: coord, w1, w2, coordr, w1r, w2r and bouncer. docker compose logs w1r repeats base backup of w1 failed (is the replication line in its pg_hba.conf?): the Citus image allows normal connections from the network but not replication connections. That is the next step.2. Open replication, register the nodes and the secondaries.
for n in coord w1 w2; do
docker compose exec $n bash -c 'echo "host replication all all trust" >> "$PGDATA/pg_hba.conf"'
docker compose exec $n psql -U atlas -d shop -qc "SELECT pg_reload_conf()"
done
sleep 10
C -c "SELECT citus_set_coordinator_host('coord', 5432)" \
-c "SELECT citus_add_node('w1', 5432)" -c "SELECT citus_add_node('w2', 5432)" \
-c "SELECT citus_add_secondary_node('w1r', 5432, 'w1', 5432)" \
-c "SELECT citus_add_secondary_node('w2r', 5432, 'w2', 5432)" \
-c "SELECT nodename, groupid, noderole FROM pg_dist_node ORDER BY nodeid"
docker compose exec w1 psql -U atlas -d shop -c "SELECT application_name, state, sync_state FROM pg_stat_replication"pg_dist_node lists coord in group 0, w1 and w2 as primary in their own groups, and w1r and w2r as secondary in the same groups as their primaries. On w1, pg_stat_replication shows w1r | streaming | async. The trust line is acceptable only inside a lab network; in production it is scram-sha-256 and a replication role. coordr is a standby for failover of the coordinator and is not registered: Citus reads from secondaries in the worker groups only.3. Install the instruments.
The load generator and the checker are given; you will use them, not write them. Create shard/shop_tables.py, the table definitions both share:
"""The six shop tables as both sides see them during the move. Shared by sync.py and check.py."""
import os
SRC = os.environ.get("SRC_DSN", "postgres://atlas:atlas@localhost:5432/shop") # the old single Postgres
DST = os.environ.get("DST_DSN", "postgres://atlas:atlas@localhost:5450/shop") # the Citus coordinator
# table: (source key column, target conflict key, columns in a fixed order)
TABLES = {
"products": ("id", "id", ["id", "sku", "name", "category", "price_cents", "created_at"]),
"inventory": ("product_id", "product_id", ["product_id", "on_hand", "updated_at"]),
"customers": ("id", "id", ["id", "email", "name", "country", "created_at"]),
"orders": ("id", "customer_id, id", ["id", "customer_id", "status", "total_cents", "created_at", "shipped_at"]),
"order_items": ("id", "customer_id, id", ["id", "customer_id", "order_id", "product_id", "qty", "unit_price_cents"]),
"payments": ("id", "customer_id, id", ["id", "customer_id", "order_id", "provider", "status", "amount_cents", "created_at"]),
}
TIMESTAMPS = {"created_at", "updated_at", "shipped_at"}shard/load.py:
"""Read/write load on the shop through the bouncer. Runs until Ctrl-C.
About LOAD_RATE operations a second (default 200): 60% read a customer's recent orders,
30% place an order (order + 1-3 items + payment in one transaction), 10% pay the
customer's newest placed order. Every acknowledged order goes to
acked.csv; an order whose COMMIT failed (outcome unknown) goes to unknown.csv.
"""
import os, random, threading, time
import psycopg
DSN = os.environ.get("LOAD_DSN", "postgres://atlas:atlas@localhost:6440/shop")
THREADS = int(os.environ.get("LOAD_THREADS", "8"))
RATE = float(os.environ.get("LOAD_RATE", "200")) # operations per second, all threads together
HERE = os.path.dirname(os.path.abspath(__file__))
lock = threading.Lock()
acked = open(os.path.join(HERE, "acked.csv"), "a", buffering=1)
unknown = open(os.path.join(HERE, "unknown.csv"), "a", buffering=1)
win = {"read": 0, "order": 0, "pay": 0, "err": 0, "lat": []}
total = {"read": 0, "order": 0, "pay": 0, "err": 0}
def connect():
return psycopg.connect(DSN, prepare_threshold=None, application_name="shop-load", connect_timeout=5)
def place_order(conn, rnd, c, max_prod):
picks = {rnd.randint(1, max_prod): rnd.randint(1, 3) for _ in range(rnd.randint(1, 3))}
prices = dict(conn.execute("SELECT id, price_cents FROM products WHERE id = ANY(%s)", (list(picks),)).fetchall())
total_cents = sum(q * prices[p] for p, q in picks.items())
oid = conn.execute("INSERT INTO orders (customer_id, status, total_cents) VALUES (%s, 'placed', %s) RETURNING id",
(c, total_cents)).fetchone()[0]
for p, q in picks.items():
conn.execute("INSERT INTO order_items (customer_id, order_id, product_id, qty, unit_price_cents)"
" VALUES (%s, %s, %s, %s, %s)", (c, oid, p, q, prices[p]))
conn.execute("INSERT INTO payments (customer_id, order_id, provider, status, amount_cents)"
" VALUES (%s, %s, 'card', 'authorised', %s)", (c, oid, total_cents))
return oid, total_cents
def pay(conn, c):
oid = conn.execute("SELECT max(id) FROM orders WHERE customer_id = %s AND status = 'placed'", (c,)).fetchone()[0]
if oid:
conn.execute("UPDATE orders SET status = 'paid' WHERE customer_id = %s AND id = %s", (c, oid))
conn.execute("UPDATE payments SET status = 'captured' WHERE customer_id = %s AND order_id = %s", (c, oid))
def worker(seed, max_cust, max_prod):
rnd, conn = random.Random(seed), None
while True:
c, op, phase, order = rnd.randint(1, max_cust), rnd.random(), "run", None
t = time.perf_counter()
try:
conn = conn or connect()
if op < 0.6:
kind = "read"
conn.execute("SELECT id, status, total_cents FROM orders WHERE customer_id = %s"
" ORDER BY created_at DESC LIMIT 10", (c,)).fetchall()
elif op < 0.9:
kind = "order"
order = place_order(conn, rnd, c, max_prod)
else:
kind = "pay"
pay(conn, c)
phase = "commit"
conn.commit()
if order:
with lock:
acked.write(f"{order[0]},{c},{order[1]}\n")
except psycopg.Error as e:
kind = "err"
with lock:
if order and phase == "commit":
unknown.write(f"{order[0]},{c},{order[1]}\n")
print(f" error: {type(e).__name__}: {str(e).strip().splitlines()[0]}", flush=True)
try:
conn and conn.close()
except Exception:
pass
conn = None
time.sleep(0.2)
ms = (time.perf_counter() - t) * 1000
with lock:
win[kind] += 1
total[kind] += 1
win["lat"].append(ms)
time.sleep(max(0.0, THREADS / RATE - ms / 1000))
def report():
start = time.monotonic()
while True:
time.sleep(5)
with lock:
lat = sorted(win["lat"]) or [0]
line = (f"t={time.monotonic() - start:5.0f}s ops/s {len(win['lat']) / 5:6.0f} "
f"read {win['read']:5} order {win['order']:5} pay {win['pay']:4} err {win['err']:3} "
f"p50 {lat[len(lat) // 2]:6.1f} ms p99 {lat[int(len(lat) * .99)]:7.1f} ms max {lat[-1]:7.1f} ms")
win.update(read=0, order=0, pay=0, err=0, lat=[])
acked.flush(); unknown.flush()
print(line, flush=True)
if __name__ == "__main__":
with connect() as conn:
max_cust = conn.execute("SELECT max(id) FROM customers").fetchone()[0]
max_prod = conn.execute("SELECT max(id) FROM products").fetchone()[0]
print(f"{THREADS} threads, {RATE:.0f} ops/s on {DSN.split('@')[-1]}; customers 1..{max_cust}, products 1..{max_prod}")
for i in range(THREADS):
threading.Thread(target=worker, args=(i, max_cust, max_prod), daemon=True).start()
threading.Thread(target=report, daemon=True).start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
with lock:
acked.flush(); unknown.flush()
print("totals:", total)shard/check.py:
"""Compare the old shop with the Citus cluster while the load runs.
python check.py window [--loop] counts and money totals for rows older than T, both sides
python check.py exact count + checksum of every column of every row (writes must be stopped)
python check.py acked every order load.py was told committed exists on the target, same total
python check.py replicas the window check, primaries against the Citus secondaries
Exit status 1 on any difference.
"""
import os, sys, time
import psycopg
from shop_tables import SRC, DST, TABLES, TIMESTAMPS
HERE = os.path.dirname(os.path.abspath(__file__))
def connect(dsn, **kw):
return psycopg.connect(dsn, application_name="shard-check", autocommit=True, prepare_threshold=None, **kw)
# Immutable facts about rows created before %(t)s: new rows do not change them, status updates do not either.
WINDOW = {
"orders": "SELECT count(*), coalesce(sum(total_cents), 0) FROM orders WHERE created_at < %(t)s",
"order_items": "SELECT count(*), coalesce(sum(i.qty * i.unit_price_cents), 0) FROM order_items i"
" JOIN orders o ON o.customer_id = i.customer_id AND o.id = i.order_id WHERE o.created_at < %(t)s",
"payments": "SELECT count(*), coalesce(sum(amount_cents), 0) FROM payments WHERE created_at < %(t)s",
"customers": "SELECT count(*), count(DISTINCT country) FROM customers WHERE created_at < %(t)s",
}
def show(rows):
bad = 0
for name, a, b in rows:
a, b = tuple(int(x) for x in a), tuple(int(x) for x in b)
ok = a == b
bad += not ok
print(f" {name:12} {str(a):>34} {str(b):>34} {'MATCH' if ok else 'DIFF'}")
return bad
def window(left, right, labels=("source", "target"), tables=WINDOW):
with connect(left) as l, connect(right) as r:
t = l.execute("SELECT least(now() - interval '30 seconds', (SELECT max(created_at) FROM orders))").fetchone()[0]
print(f"rows created before {t:%H:%M:%S} {labels[0] + ' (count, sum)':>34} {labels[1] + ' (count, sum)':>34}")
return show([(n, l.execute(q, {"t": t}).fetchone(), r.execute(q, {"t": t}).fetchone()) for n, q in tables.items()])
def checksum_sql(t):
cols = TABLES[t][2]
parts = [f"coalesce((extract(epoch FROM {c}))::text, '-')" if c in TIMESTAMPS else f"coalesce({c}::text, '-')"
for c in cols]
return f"SELECT count(*), coalesce(sum(hashtextextended(concat_ws('|', {', '.join(parts)}), 0)), 0) FROM {t}"
def exact():
with connect(SRC) as l, connect(DST) as r:
print(f"every row, every column {'source (count, checksum)':>34} {'target (count, checksum)':>34}")
return show([(t, l.execute(checksum_sql(t)).fetchone(), r.execute(checksum_sql(t)).fetchone()) for t in TABLES])
def acked():
def load(name):
try:
with open(os.path.join(HERE, name)) as f:
return {int(a): (int(c), int(tot)) for a, c, tot in (line.strip().split(",") for line in f if line.strip())}
except FileNotFoundError:
return {}
ok, unk = load("acked.csv"), load("unknown.csv")
found = {}
with connect(DST) as r:
ids = list(ok) + list(unk)
for i in range(0, len(ids), 5000):
found.update(dict(r.execute("SELECT id, total_cents FROM orders WHERE id = ANY(%s)", (ids[i:i + 5000],)).fetchall()))
lost = [i for i in ok if i not in found]
wrong = [i for i in ok if i in found and found[i] != ok[i][1]]
print(f"acknowledged orders {len(ok)}: lost {len(lost)}, wrong total {len(wrong)}")
print(f"unknown-outcome orders {len(unk)}: committed {sum(i in found for i in unk)}, not committed {sum(i not in found for i in unk)}")
if lost[:5]:
print(" first lost ids:", lost[:5])
return len(lost) + len(wrong)
def replicas():
secondary = DST + ("&" if "?" in DST else "?") + "options=-c%20citus.use_secondary_nodes%3Dalways"
return window(DST, secondary, labels=("primaries", "secondaries"))
if __name__ == "__main__":
cmds = {"window": lambda: window(SRC, DST), "exact": exact, "acked": acked, "replicas": replicas}
if len(sys.argv) < 2 or sys.argv[1] not in cmds:
sys.exit(__doc__)
if "--loop" in sys.argv:
try:
while True:
cmds[sys.argv[1]]()
time.sleep(5)
except KeyboardInterrupt:
sys.exit(0)
sys.exit(1 if cmds[sys.argv[1]]() else 0)python3 -m venv shard/.venv
shard/.venv/bin/pip install "psycopg[binary]==3.3.6"
P -c "SELECT count(*) FROM orders"200000 at scale 0.1. load.py commits after every operation, including reads: in transaction pooling, a session that sits inside an open transaction holds a server connection, and PAUSE would wait for it. It turns off prepared statements (prepare_threshold=None) for the same reason. It records every acknowledged order in shard/acked.csv, and any order whose COMMIT raised an error in shard/unknown.csv, because a failed COMMIT may have committed. That distinction is the Jepsen idea from the consistency chapter.4. Expand the source, then start the load.
Adding a nullable column without a default is a catalogue change, but it still takes a brief ACCESS EXCLUSIVE lock, so give it a lock timeout:
P <<'SQL'
SET lock_timeout = '2s';
ALTER TABLE order_items ADD COLUMN IF NOT EXISTS customer_id bigint;
ALTER TABLE payments ADD COLUMN IF NOT EXISTS customer_id bigint;
CREATE INDEX IF NOT EXISTS orders_customer_created ON orders (customer_id, created_at);
SQLIn terminal 2:
shard/.venv/bin/python shard/load.pyALTER TABLE lines and either CREATE INDEX or a notice that orders_customer_created already exists from an earlier chapter. Terminal 2 prints 8 threads, 200 ops/s on localhost:6440/shop; customers 1..50000, products 1..5000, then a line every 5 seconds: about 190 ops/s, err 0, p50 around 1 to 3 ms. Every request goes through bouncer to db. Leave it running until the end of the lab.5. Backfill customer_id under load.
New rows already carry customer_id, because the load writes it. Write shard/backfill.sql to fill the old rows from orders, in batches of 20 000 ids, committing after each batch so no transaction holds row locks for long, and ending with a count of rows still null in each table.
P < shard/backfill.sqlSolution
A DO block can COMMIT between batches when it is not inside an outer transaction, which is the case when psql sends it on its own:
DO $$
DECLARE lo bigint := 0; hi bigint; step int := 20000; n bigint := 0; k bigint;
BEGIN
SELECT max(id) INTO hi FROM order_items;
WHILE lo <= hi LOOP
UPDATE order_items i SET customer_id = o.customer_id FROM orders o
WHERE o.id = i.order_id AND i.id > lo AND i.id <= lo + step AND i.customer_id IS NULL;
GET DIAGNOSTICS k = ROW_COUNT; n := n + k;
COMMIT;
lo := lo + step;
END LOOP;
RAISE NOTICE 'order_items: % rows backfilled', n;
lo := 0; n := 0;
SELECT max(id) INTO hi FROM payments;
WHILE lo <= hi LOOP
UPDATE payments p SET customer_id = o.customer_id FROM orders o
WHERE o.id = p.order_id AND p.id > lo AND p.id <= lo + step AND p.customer_id IS NULL;
GET DIAGNOSTICS k = ROW_COUNT; n := n + k;
COMMIT;
lo := lo + step;
END LOOP;
RAISE NOTICE 'payments: % rows backfilled', n;
END $$;
SELECT (SELECT count(*) FROM order_items WHERE customer_id IS NULL) AS items_missing,
(SELECT count(*) FROM payments WHERE customer_id IS NULL) AS payments_missing;At scale 0.1 it reports about 600 000 and 200 000 rows backfilled in a few seconds each, and both counts at the end are 0. Terminal 2 shows a slightly higher p99 while it runs and still err 0. One large UPDATE would also work here, but it would hold locks on 600 000 rows for its whole duration and write one transaction’s worth of WAL that every standby must replay at once; the batches keep both small. On a table where customer_id must become NOT NULL, add CHECK (customer_id IS NOT NULL) NOT VALID, then VALIDATE CONSTRAINT (which takes a weaker lock), and SET NOT NULL then skips its full-table scan.
6. Create the target schema.
Create shard/target.sql. It is the partitioning chapter’s schema extended to all six tables, with customer_id leading every distributed primary key and the two small, rarely written tables as reference tables:
-- The shop on Citus: customer_id leads every distributed key; products and inventory are
-- reference tables (a full copy on every node). No foreign keys: the follower applies
-- changes table by table, and a child row may arrive before its parent.
CREATE TABLE products (id bigint PRIMARY KEY, sku text NOT NULL UNIQUE, name text NOT NULL,
category text NOT NULL, price_cents int NOT NULL, created_at timestamptz NOT NULL DEFAULT now());
CREATE TABLE inventory (product_id bigint PRIMARY KEY, on_hand int NOT NULL, updated_at timestamptz NOT NULL DEFAULT now());
CREATE TABLE customers (id bigint PRIMARY KEY, email text NOT NULL, name text NOT NULL,
country char(2) NOT NULL, created_at timestamptz NOT NULL DEFAULT now());
CREATE TABLE orders (id bigserial, customer_id bigint NOT NULL,
status text NOT NULL CHECK (status IN ('placed', 'paid', 'shipped', 'cancelled')),
total_cents int NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), shipped_at timestamptz,
PRIMARY KEY (customer_id, id));
CREATE TABLE order_items (id bigserial, customer_id bigint NOT NULL, order_id bigint NOT NULL,
product_id bigint NOT NULL, qty int NOT NULL, unit_price_cents int NOT NULL,
PRIMARY KEY (customer_id, id));
CREATE TABLE payments (id bigserial, customer_id bigint NOT NULL, order_id bigint NOT NULL,
provider text NOT NULL CHECK (provider IN ('card', 'paypal', 'bank')),
status text NOT NULL CHECK (status IN ('authorised', 'captured', 'failed', 'refunded')),
amount_cents int NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (customer_id, id));
CREATE INDEX orders_customer_created ON orders (customer_id, created_at);
SELECT create_reference_table('products');
SELECT create_reference_table('inventory');
SELECT create_distributed_table('customers', 'id');
SELECT create_distributed_table('orders', 'customer_id', colocate_with => 'customers');
SELECT create_distributed_table('order_items', 'customer_id', colocate_with => 'orders');
SELECT create_distributed_table('payments', 'customer_id', colocate_with => 'orders');C -v ON_ERROR_STOP=1 < shard/target.sql
C -c "SELECT table_name, citus_table_type, count(*) AS shards FROM citus_shards GROUP BY 1, 2 ORDER BY 1"create_*_table call returns an empty row. citus_shards shows 32 shards each for customers, orders, order_items and payments (type distributed), and one shard with a placement on each node for products and inventory (type reference; the query counts placements, so 3). customers.email has no UNIQUE constraint here: a unique index that does not include the distribution column cannot exist on a distributed table, as the partitioning chapter showed.7. Write the follower: capture and copy.
Write shard/sync.py with these commands, connecting with SRC and DST from shop_tables.py:
capture: on the source, createshard_changes (seq, xid, at, tbl, id)withxiddefaulting topg_current_xact_id(), and anAFTER INSERT OR UPDATE OR DELETE ... FOR EACH ROWtrigger on all six tables that logs the table name and the row’s key.copy: truncate the target andCOPYeach table across with the column lists fromTABLES.follow: loop. In a REPEATABLE READ transaction on the source, take up to 5000 changes whosexidis belowpg_snapshot_xmin(pg_current_snapshot()); re-read those rows from the source in the same snapshot; upsert the ones that exist into the target (ON CONFLICTon the target key) and delete the ones that do not; commit the target; then delete the consumed changes from the log and commit the source. Print the number pending and the age of the oldest once a second.drain: asfollow, but exit when the log is empty.fence/unfence:ALTER DATABASE shop SET default_transaction_read_only = on, and terminate every other session inshopexcept the checker’s (application_nameshard-check); and the reverse.sequences: fororders,order_itemsandpayments,setvalthe target’s*_id_seqto the source’slast_value.
Order matters: install the triggers before the copy starts, so any row that changes during the copy is also in the log.
shard/.venv/bin/python shard/sync.py capture
shard/.venv/bin/python shard/sync.py copySolution
"""Move the shop from one Postgres to Citus: capture, copy, follow, drain, fence.
python sync.py capture # change log + triggers on the source
python sync.py copy # truncate the target, COPY every table across
python sync.py follow # apply the change log until Ctrl-C
python sync.py drain # apply until the log is empty, then exit
python sync.py fence # source read-only, other sessions killed
python sync.py unfence # undo fence (abort path)
python sync.py sequences # target sequences past the source's
python sync.py uncapture # drop triggers and the log
"""
import sys, time
import psycopg
from shop_tables import SRC, DST, TABLES
CAPTURE = """
CREATE TABLE IF NOT EXISTS shard_changes (
seq bigserial PRIMARY KEY,
xid xid8 NOT NULL DEFAULT pg_current_xact_id(),
at timestamptz NOT NULL DEFAULT clock_timestamp(),
tbl text NOT NULL,
id bigint NOT NULL);
CREATE OR REPLACE FUNCTION shard_capture() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO shard_changes (tbl, id)
VALUES (TG_TABLE_NAME, (to_jsonb(CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END) ->> TG_ARGV[0])::bigint);
RETURN NULL;
END $$;
"""
def connect(dsn, **kw):
return psycopg.connect(dsn, application_name="shard-sync", prepare_threshold=None, **kw)
def capture():
with connect(SRC) as s:
s.execute(CAPTURE)
for t, (key, _, _) in TABLES.items():
s.execute(f"DROP TRIGGER IF EXISTS shard_capture ON {t}")
s.execute(f"CREATE TRIGGER shard_capture AFTER INSERT OR UPDATE OR DELETE ON {t} "
f"FOR EACH ROW EXECUTE FUNCTION shard_capture('{key}')")
print("capturing changes on", ", ".join(TABLES))
def uncapture():
with connect(SRC) as s:
for t in TABLES:
s.execute(f"DROP TRIGGER IF EXISTS shard_capture ON {t}")
s.execute("DROP TABLE IF EXISTS shard_changes; DROP FUNCTION IF EXISTS shard_capture()")
def copy():
with connect(SRC) as s, connect(DST) as d:
d.execute("TRUNCATE " + ", ".join(TABLES))
for t, (_, _, cols) in TABLES.items():
c = ", ".join(cols)
t0, n = time.perf_counter(), 0
with s.cursor().copy(f"COPY (SELECT {c} FROM {t}) TO STDOUT") as cin, \
d.cursor().copy(f"COPY {t} ({c}) FROM STDIN") as cout:
for block in cin:
cout.write(block)
n += bytes(block).count(b"\n")
d.commit()
print(f"{t:12} {n:>9} rows {time.perf_counter() - t0:5.1f}s")
def upsert_sql(t):
_, conflict, cols = TABLES[t]
keys = {k.strip() for k in conflict.split(",")}
sets = ", ".join(f"{c} = EXCLUDED.{c}" for c in cols if c not in keys)
return (f"INSERT INTO {t} ({', '.join(cols)}) VALUES ({', '.join(['%s'] * len(cols))}) "
f"ON CONFLICT ({conflict}) DO UPDATE SET {sets}")
def apply_batch(s, d, limit=5000):
"""One round: changes from finished transactions -> re-read rows -> upsert -> forget. Returns count."""
with s.transaction():
s.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")
changes = s.execute(
"SELECT seq, tbl, id FROM shard_changes"
" WHERE xid < pg_snapshot_xmin(pg_current_snapshot()) ORDER BY seq LIMIT %s", (limit,)).fetchall()
if not changes:
return 0
by_table = {}
for _, t, i in changes:
by_table.setdefault(t, set()).add(i)
with d.transaction():
for t, ids in by_table.items():
key, _, cols = TABLES[t]
rows = s.execute(f"SELECT {', '.join(cols)} FROM {t} WHERE {key} = ANY(%s)", (list(ids),)).fetchall()
if rows:
d.cursor().executemany(upsert_sql(t), rows)
gone = ids - {r[cols.index(key)] for r in rows}
if gone:
d.execute(f"DELETE FROM {t} WHERE {key} = ANY(%s)", (list(gone),))
# Target committed. Forget the changes; a crash before this line replays them, harmlessly.
s.execute("DELETE FROM shard_changes WHERE seq = ANY(%s)", ([c[0] for c in changes],))
return len(changes)
def lag(s):
n, age = s.execute("SELECT count(*), coalesce(extract(epoch FROM clock_timestamp() - min(at)), 0)"
" FROM shard_changes").fetchone()
return n, float(age)
def follow(until_empty=False):
with connect(SRC, autocommit=True) as s, connect(DST, autocommit=True) as d:
last = time.monotonic()
while True:
n = apply_batch(s, d)
if until_empty and n == 0 and lag(s)[0] == 0:
return
if time.monotonic() - last >= 1 and not until_empty:
pending, age = lag(s)
print(f"applied {n:5} pending {pending:6} oldest {age:5.2f}s", flush=True)
last = time.monotonic()
if n == 0:
time.sleep(0.05)
def fence():
with connect(SRC, autocommit=True) as s:
s.execute("ALTER DATABASE shop SET default_transaction_read_only = on")
k = s.execute("SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity"
" WHERE datname = 'shop' AND pid <> pg_backend_pid()"
" AND application_name NOT IN ('shard-check')").fetchone()[0]
print(f"source fenced: read-only for new sessions, {k} sessions terminated")
def unfence():
with connect(SRC, autocommit=True) as s:
s.execute("SET default_transaction_read_only = off") # this session was born read-only
s.execute("ALTER DATABASE shop RESET default_transaction_read_only")
print("source unfenced")
def sequences():
with connect(SRC) as s, connect(DST, autocommit=True) as d:
for t in ("orders", "order_items", "payments"):
v = s.execute(f"SELECT last_value FROM {t}_id_seq").fetchone()[0]
d.execute("SELECT setval(%s, %s)", (f"{t}_id_seq", v))
print(f"{t}_id_seq -> {v}")
if __name__ == "__main__":
cmds = {"capture": capture, "uncapture": uncapture, "copy": copy, "follow": follow,
"drain": lambda: follow(until_empty=True), "fence": fence, "unfence": unfence,
"sequences": sequences}
if len(sys.argv) != 2 or sys.argv[1] not in cmds:
sys.exit(__doc__)
try:
cmds[sys.argv[1]]()
except KeyboardInterrupt:
passWhy each choice is there:
- Log the key, re-read the row. The log holds no row images, so it does not matter in which order changes to one row are applied: the follower always copies the row as the source holds it now. Applying a change twice is harmless, so a crash between the target commit and the log delete costs nothing but a replay.
- The xmin rule.
pg_snapshot_xminof the follower’s own snapshot is the oldest transaction still running when the snapshot was taken. Every change below it belongs to a transaction that has committed (and is visible in this snapshot) or aborted (and its log rows vanished with it). Without the rule, a change from a transaction that commits late would be consumed only if the follower happened to read it after its commit; with a high-water mark it would be skipped for good. - CREATE TRIGGER before COPY.
CREATE TRIGGERtakes a SHARE ROW EXCLUSIVE lock, which waits for in-flight writes on the table to finish, so every write that commits afterwards is logged. A row copied and then changed is fixed by the follower; a row changed and then copied is upserted again with the same values. - Deletes fan out. The log holds only the source key, so a delete on the target filters on
idalone, which Citus sends to every shard. The load never deletes; in a system that does, log the shard key as well.
capturing changes on products, inventory, customers, orders, order_items, payments, then one line per table: 5000 products, 5000 inventory rows, 50 000 customers, a little over 200 000 orders, a little over 600 000 order items and a little over 200 000 payments (the load has added some), in 10 to 30 seconds in all. The load in terminal 2 keeps printing err 0 throughout; the trigger costs it a fraction of a millisecond per write.8. Follow, and check while the load runs.
In terminal 3:
shard/.venv/bin/python shard/sync.py followIn terminal 1, after half a minute:
shard/.venv/bin/python shard/check.py windowpending in single or low double figures and oldest well under a second: the target is a fraction of a second behind. The checker prints four lines, each (count, sum) on both sides and MATCH; orders, order_items and payments have the same money total, which is the shop’s invariant that an order’s total equals its lines and its payment. It compares only rows created more than 30 seconds ago, and only columns that never change after insert, which is why it can match while both sides are moving. Status changes are checked at the cutover, when nothing moves.9. Write the cutover, and rehearse the abort.
Write shard/cutover.sh to run the six cutover steps from the brief. Use PgBouncer’s admin console through docker compose exec -T -e PGPASSWORD=atlas bouncer psql -h 127.0.0.1 -p 6432 -U atlas -d pgbouncer -Atqc "...". Repoint by changing host=db to host=coord in shard/pgbouncer/pgbouncer.ini (the directory is mounted, so an edit on the host is visible to PgBouncer) and sending RELOAD. If any step fails, restore the file, unfence the source, RESUME, and exit non-zero. Print how many seconds the pause lasted.
Solution
#!/bin/bash
# Cut the shop over from the single Postgres to Citus. Run from labs/databases with
# COMPOSE_FILE=citus.yaml:shard/compose.yaml exported and `sync.py follow` stopped.
set -uo pipefail
PY=shard/.venv/bin/python
INI=shard/pgbouncer/pgbouncer.ini
admin() { docker compose exec -T -e PGPASSWORD=atlas bouncer psql -h 127.0.0.1 -p 6432 -U atlas -d pgbouncer -Atqc "$1"; }
abort() {
echo "ABORT: $1. Traffic stays on the old database."
sed -i.bak 's/host=coord /host=db /' "$INI" && admin "RELOAD"
$PY shard/sync.py unfence
admin "RESUME shop"
exit 1
}
SECONDS=0
admin "PAUSE shop" || { echo "PAUSE failed; nothing changed"; exit 1; }
echo "paused after ${SECONDS}s; draining"
$PY shard/sync.py drain || abort "drain failed"
$PY shard/sync.py fence || abort "fence failed"
$PY shard/check.py exact || abort "source and target differ"
$PY shard/sync.py sequences || abort "could not move the sequences"
sed -i.bak 's/host=db /host=coord /' "$INI"
admin "RELOAD" || abort "RELOAD failed"
admin "RESUME shop"
echo "resumed after ${SECONDS}s on: $(admin 'SHOW DATABASES' | grep '^shop|' | cut -d'|' -f2)"PAUSE returns only when every server connection to shop is closed, so after it no write can reach either database. RELOAD with a changed database line makes new server connections go to the new host; because PAUSE closed the old ones, there is nothing left pointing at db. The checker excludes itself from the fence by its application_name. abort is safe at every point: before the sed, the restore is a no-op, and unfencing a database that was not fenced resets nothing.
Rehearse the failure before the real thing. Corrupt one row on the target, stop the follower (Ctrl-C in terminal 3), and run the cutover:
C -c "UPDATE customers SET name = name || ' (corrupt)' WHERE id = 51"
bash shard/cutover.shpaused, the follower’s drain, source fenced: read-only for new sessions, 0 sessions terminated (the pooler has no server connections while paused), then the exact check: six lines, customers with matching counts and different checksums, DIFF. Then ABORT: source and target differ. Traffic stays on the old database., source unfenced, and the script exits 1. Terminal 2 shows one 5-second line with a max latency of a few seconds and err 0, then carries on against db. The window check in step 8 could never have caught this: a name is not in it. That is why the exact check runs inside the pause.Repair it the way a real divergence is repaired, through the follower: touch the row on the source so the trigger logs it, and let the follower copy it.
P -c "UPDATE customers SET name = name WHERE id = 51"
shard/.venv/bin/python shard/sync.py follow # terminal 3; leave it running10. Cut over.
Stop the follower (Ctrl-C in terminal 3), then:
bash shard/cutover.shsource fenced, six MATCH lines, three *_id_seq -> lines, and resumed after Ns on: coord with N between 2 and 8 seconds, most of it docker compose exec start-up time; the database work is under a second at this scale. Terminal 2 shows one 5-second window with fewer operations and a max latency equal to the pause, and err 0. From the next line on, every operation goes to Citus. Nothing in load.py changed: the application’s connection string still points at the pooler.11. Prove nothing was lost.
shard/.venv/bin/python shard/check.py acked
shard/.venv/bin/python shard/check.py window
P -c "INSERT INTO orders (customer_id, status, total_cents) VALUES (51, 'placed', 100)"
C -c "EXPLAIN (COSTS OFF) SELECT id, status FROM orders WHERE customer_id = 51 ORDER BY created_at DESC LIMIT 10"acknowledged orders N: lost 0, wrong total 0 and unknown-outcome orders 0. The window check matches: now that the source is frozen, T is the source’s last order, so it compares every row the source ever had. The insert on the old database fails with cannot execute INSERT in a read-only transaction: the fence holds, and a stray writer gets an error instead of losing data quietly. The plan is a Custom Scan (Citus Adaptive) with Task Count: 1, a router query on one worker, as the load’s reads are.12. Read from the standbys, then grow under load.
shard/.venv/bin/python shard/check.py replicasMATCH lines, primaries against secondaries. The second connection sets citus.use_secondary_nodes=always in its startup options (it can only be set when the connection starts), so the coordinator plans every read against w1r and w2r. That session cannot write: Citus refuses with writing to worker nodes is not currently allowed.Add w3 and its standby, register both, and rebalance while the load runs:
docker compose --profile grow up -d w3 w3r
docker compose exec w3 bash -c 'echo "host replication all all trust" >> "$PGDATA/pg_hba.conf"'
docker compose exec w3 psql -U atlas -d shop -qc "SELECT pg_reload_conf()"
sleep 10
C -c "SELECT citus_add_node('w3', 5432)" -c "SELECT citus_add_secondary_node('w3r', 5432, 'w3', 5432)" \
-c "SELECT citus_rebalance_start()" -c "SELECT citus_rebalance_wait()" \
-c "SELECT nodename, count(*) FROM citus_shards WHERE table_name = 'orders'::regclass GROUP BY 1 ORDER BY 1"
shard/.venv/bin/python shard/check.py acked
shard/.venv/bin/python shard/check.py replicascustomers shard with its co-located orders, order_items and payments shards) to w3, each by logical replication with a short write block at the end; citus_rebalance_wait returns when all are done, about a minute at this scale. orders ends roughly a third per worker. Terminal 2 shows a few brief latency spikes, one per move, and err 0. acked still reports 0 lost; replicas still matches. Leave out the citus_add_secondary_node call for w3r and, after the rebalance, replicas fails with node group N does not have a secondary node: in always-secondary mode, every group that holds a shard the query touches needs a secondary.13. Tear down.
Stop the load (Ctrl-C in terminal 2), then:
docker compose down -v
unset COMPOSE_FILE
shard/.venv/bin/python shard/sync.py unfence
shard/.venv/bin/python shard/sync.py uncapture
docker compose exec -T db psql -U atlas -d shop -f /shop/schema.sql
docker compose exec -T db psql -U atlas -d shop -v scale=0.1 -f /shop/load.sqlschema.sql drops the added customer_id columns along with the tables.sync.py sequences had never run: C -c "SELECT setval('orders_id_seq', 1)". Nothing fails. The load keeps printing err 0, because the primary key is (customer_id, id) and a new order with id 2 for customer 4417 does not collide with the old order 2 of customer 33. After a minute, C -c "SELECT count(*) FROM (SELECT id FROM orders GROUP BY id HAVING count(*) > 1) d" counts the duplicated ids, and check.py acked starts reporting wrong totals, because an id no longer names one order. Every payment and line written in that minute refers to an ambiguous order_id. SELECT setval('orders_id_seq', (SELECT max(id) FROM orders)) stops new damage and repairs none of it. The exact check could not catch this, because it ran before the first insert; the only defence is the step in the script, and a uniqueness check on id after the switch.All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.