PR Review Lab · Serve Writes From Both Regions

40:00left of 40:00

Serve Writes From Both Regions

EU customers see 180 ms on every write because all writes go to us-east-1. This makes both regions primary: requests write to the nearest region's database, a replication worker applies each region's changes to the other, and conflicts resolve by last write wins on updated_at. Sequences are split by parity so ids never collide. Failover becomes automatic, since either region can take all traffic. I tested it with both regions in staging under synthetic load.

Asrc/replication/applier.ts1 of 4

Files Changed

src/replication/

src/routing/

config/

db/migrations/

src/replication/applier.ts

TypeScript · Click a line number to comment · Tap a line to comment
@@ -0,0 +1,14 @@
Added: import { db } from "../db";
Added: import type { Change } from "./stream";
Added:
Added: // Applies a change replicated from the other region. The newest
Added: // updated_at wins, so both regions converge on the same row.
Added: export async function apply(change: Change): Promise<void> {
Added: if (change.op === "delete") {
Added: await db.none("DELETE FROM " + change.table + " WHERE id = $1", [change.id]);
Added: return;
Added: }
Added: const current = await db.oneOrNone("SELECT updated_at FROM " + change.table + " WHERE id = $1", [change.id]);
Added: if (current && current.updated_at >= change.row.updated_at) return;
Added: await db.upsert(change.table, change.row);
Added: }