Cross-Cloud Data Synchronization and Unified API Gateway
Medium · System Design · Software Engineer · Onsite
Prompt
Architect an event-driven cross-cloud synchronization pipeline paired with a global API gateway for a multi-tenant platform. Authoritative records (such as security policies and rule definitions) are written to a single on-premise PostgreSQL primary database and must be replicated reliably to regional deployments across AWS, GCP, and Azure. Simultaneously, external clients call the platform through a unified API gateway that enforces authentication and rate limits while steering traffic to healthy cloud deployments with consistent semantics.
Your design must satisfy these operational constraints: - Minimal primary-DB impact: Capturing and publishing data changes must not place heavy CPU, lock, or query load on the on-premise PostgreSQL primary. - Throughput & latency: Sustain at least 10,000 requests per second with high cross-region availability while keeping API gateway authentication and routing overhead well under 100 ms. - Fault resilience: Handle duplicate deliveries, out-of-order network packets, cross-cloud WAN partitions, an offline cloud region, or temporary message-broker outages cleanly.
Scope & Expectations
- End-to-end architecture & wire protocol: Present a clear text architecture diagram and specify how committed changes move from on-premise PostgreSQL to cloud consumers.
- Consistency & destination idempotency: Justify eventual vs. strong consistency trade-offs and propose destination metadata/schema rules that keep regional applies ordered, atomic, and idempotent.
- Edge API gateway design: Detail sub-100 ms token authentication, distributed rate limiting, and health- or freshness-aware regional request routing.
- Failure handling & lag observability: Explain system behavior during regional or broker outages and define metrics that measure true end-to-end replication lag across clouds.
Step-by-step walkthrough
Clarify requirements and assumptions
We are building two connected pieces that make a global security-policy platform feel like one fast, reliable service: 1. A multicloud replication pipeline that copies policy changes from a single on-premise PostgreSQL database out to cloud deployments in AWS, GCP, and Azure. 2. A unified API gateway in front of those clouds that authenticates callers, enforces rate limits, and routes requests to a healthy, up-to-date region in well under 100 ms.
Functional requirements
- Event publishing: Every insert, update, and delete on policy tables (policies, rule sets, labels) in the on-premise primary database must propagate to all cloud regions. Assume 2 regions per cloud across AWS, GCP, and Azure (6 cloud regions total).
- Local reads, single-writer writes: Clients read policies from the nearest healthy cloud region. Clients send policy edits through the same public API, and the gateway forwards writes to the on-premise primary so there is only one source of truth and never a multi-writer conflict.
- API gateway controls: Authenticate every request, rate-limit per tenant or client, and route requests based on region health, data freshness, and tenant location rules.
Non-functional requirements
- Protect the primary database: Replication must not add triggers, heavy polling queries, or extra network waits to primary transactions. Instead, we read PostgreSQL's Write-Ahead Log (WAL)—the sequential recovery log PostgreSQL already writes to disk for every transaction—using Change Data Capture (CDC), a technique that turns database log entries into a stream of change events.
- Throughput and latency: Support at least 10,000 requests per second (RPS) on average (design for 30,000 RPS at peak). Keep gateway authentication and routing overhead under 10 ms at p99—comfortably inside the 100 ms budget.
- Replication freshness and correctness: Normal end-to-end replication lag should stay under 5 seconds at p99. Even when networks drop packets or retry, each cloud region must apply changes in commit order per tenant, all-or-nothing per transaction (a half-applied firewall policy is a security hole), and idempotently (receiving the same event twice has the exact same effect as receiving it once).
- High availability: Losing a cloud region, a cross-cloud network link, or a message broker node must not take down the platform.
Assumptions to state out loud
- Policy workloads are overwhelmingly read-heavy: 98% reads (workloads and agents fetching policy rules) and 2% writes (administrators updating policies).
- Every policy row belongs to a
tenant_id. Some enterprise tenants require data residency (for example, EU tenant data may only live in EU cloud regions). - Each cloud region runs managed PostgreSQL (RDS, Cloud SQL, Azure Database for PostgreSQL), so every region runs the exact same applier code and schema.
- On-premise connects to each cloud over dedicated private links (AWS Direct Connect, GCP Cloud Interconnect, Azure ExpressRoute) with encrypted site-to-site VPNs as automatic backup.
Back-of-the-envelope numbers
Before picking components, let's size the traffic, storage, and network budgets so we know where the real bottlenecks live.
API Gateway traffic Average total traffic 10,000 RPS (given); size for 30,000 RPS peak (3x headroom) Read / write split 98% reads (9,800 RPS avg) / 2% writes (200 RPS avg, 600 RPS peak) Busiest region (~40% peak) 30,000 x 0.40 = 12,000 RPS Proxy capacity ~5,000 RPS per 4-vCPU Envoy node (with TLS reuse + local JWT check) Nodes in busiest region 12,000 / 5,000 = 3 nodes -> run 5-6 nodes to absorb a neighbor's failover Replication stream Change rate ~200 row changes/s average; bursts of 5,000/s (bulk policy push) Average event size ~1 KB (keys + row columns + metadata in Protobuf/Avro) Stream throughput 200 x 1 KB = 200 KB/s average (~17.3 GB/day); 5 MB/s on bursts Kafka 7-day retention 17.3 GB/day x 7 days = ~121 GB logical; x 3 replicas = ~363 GB disk WAN egress to 6 regions 6 x 200 KB/s = 1.2 MB/s avg; 6 x 5 MB/s = 30 MB/s (240 Mbit/s) burst Outage catch-up (2-hour region outage) Backlog accumulated 200 events/s x 7,200 s = 1.44M events (~1.44 GB) Drain time at 5,000/s cap 1,440,000 / (5,000 drained - 200 new arriving) = 300 s (~5 minutes) Latency budget (< 100 ms gateway target) Local JWT + rate-limit + route lookup < 1 ms CPU on the gateway node Same-continent network round trip 10 - 40 ms Cross-ocean network round trip 70 - 150 msThree concrete lessons jump out from the math: 1. Replication data volume is tiny (~17 GB/day). One Kafka cluster easily holds a full week of changes. The hard problems are correctness (ordering, atomic transactions, duplicates) and outage recovery, not raw disk bandwidth. 2. A 2-hour regional outage builds only ~1.44 GB of backlog. Kafka retains it effortlessly, and a recovering region can catch up in ~5 minutes at a throttled 5,000 events/s without overwhelming its local database. 3. Network hops—not CPU—threaten the 100 ms gateway budget. If the gateway made a cross-region call to a central authentication service or central Redis on every request, one 80 ms round trip would blow most of our latency budget. Every hot-path gateway decision must happen locally in memory.
API design
Clients talk to a single global hostname (
api.platform.example.com). Global DNS steers each client to the closest healthy cloud region, where any regional gateway can serve reads locally or forward writes to on-premise.1) Read a policy (served from the local cloud region) GET /v1/tenants/{tenant_id}/policies/{policy_id} Authorization: Bearer <JWT> X-Min-Version: 0/4F80A100 (optional: minimum WAL position from client's last write) -> 200 OK X-Data-Version: 0/4F80A190 (WAL commit position applied in this region for this tenant) X-Data-As-Of: 2026-04-12T16:20:05.040Z X-Served-By: gcp-us-central1 { "policy_id": "pol_402", "rules": [...] } 2) Create or update a policy (forwarded by the gateway to the on-prem primary) PUT /v1/tenants/{tenant_id}/policies/{policy_id} Authorization: Bearer <JWT> Idempotency-Key: 3c7a91e0-8d24-4f19-a5b2-61e09f4c82d1 If-Match: "v8" -> 200 OK X-Data-Version: 0/4F80A100 (primary's WAL commit position; client echoes as X-Min-Version) { "policy_id": "pol_402", "version": "v9", "rules": [...] } 3) Error responses -> 429 Too Many Requests Retry-After: 2 X-RateLimit-Remaining: 0 -> 503 Service Unavailable Retry-After: 5 (no eligible region satisfies residency/freshness)Why those headers matter: -
X-Data-Versionuses PostgreSQL's Log Sequence Number (LSN)—a monotonically increasing 64-bit byte offset in the primary's Write-Ahead Log (written like0/4F80A100). When a client writes a policy, the primary returns the commit LSN. When that client immediately reads back the policy and passesX-Min-Version: 0/4F80A100, any cloud gateway can check two integers in memory (region_applied_lsn >= min_version) without querying the primary. -Idempotency-Keyis a client-generated unique ID per write attempt so that retrying a timed-outPUTreturns the original result instead of applying an update twice. -X-Data-As-Ofexposes exact data freshness to callers and operators during partial outages.Data model, event protocol, and idempotency
Communication protocol on the bus. A CDC connector streams committed row changes into an on-premise Kafka topic
policy-changeswith 64 partitions, replication factor 3, andmin.insync.replicas = 2. Every message usestenant_id(serialized as plain UTF-8 bytes) as its Kafka partition key, so all changes for a given tenant—across policies, rule sets, and labels—land in the exact same partition in strict commit order. Payloads are encoded with Protobuf (or Avro) validated against a Schema Registry (a central catalog of message schemas that rejects incompatible breaking changes).Kafka message envelope (key = "org_77") { "event_id": "pg-main:0/4F80A100:1", // unique ID: source + commit_lsn + seq_in_tx "tx_id": 9104, // primary transaction ID (for atomic grouping) "commit_lsn": "0/4F80A100", // WAL byte offset of the transaction's COMMIT "seq_in_tx": 1, // 0-based order of this row change inside tx_id "commit_ts": "2026-04-12T16:20:05.040Z",// primary commit timestamp (for lag monitoring) "schema_version": 4, // table schema version "table": "policy_rule", "op": "u", // "c" (create), "u" (update), "d" (delete), "h" (heartbeat) "key": { "tenant_id": "org_77", "rule_id": "rule_84" }, "after": { "tenant_id": "org_77", "rule_id": "rule_84", "action": "ALLOW", "port": 443 } }Destination schema and idempotency strategy. In each cloud region's PostgreSQL database, every replicated table stores the version tuple
(src_lsn, src_seq)alongside a soft-delete flag (deleted), called a tombstone (a marker row kept after deletion so a delayed replay of an older update cannot accidentally resurrect a deleted record):CREATE TABLE policy_rule ( tenant_id TEXT NOT NULL, rule_id TEXT NOT NULL, action TEXT, port INT, deleted BOOLEAN NOT NULL DEFAULT FALSE, src_lsn PG_LSN NOT NULL, src_seq INT NOT NULL, schema_version INT NOT NULL DEFAULT 1, updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id, rule_id) ); -- Tracks how far this region has progressed on each of the 64 Kafka partitions CREATE TABLE apply_checkpoint ( partition_id INT PRIMARY KEY, last_kafka_offset BIGINT NOT NULL, last_commit_lsn PG_LSN NOT NULL, last_commit_ts TIMESTAMPTZ NOT NULL );Every create, update, or delete at the cloud destination runs as a conditional versioned upsert:
INSERT INTO policy_rule AS t (tenant_id, rule_id, action, port, deleted, src_lsn, src_seq, schema_version) VALUES (:tenant_id, :rule_id, :action, :port, :deleted, :commit_lsn, :seq_in_tx, :schema_version) ON CONFLICT (tenant_id, rule_id) DO UPDATE SET action = EXCLUDED.action, port = EXCLUDED.port, deleted = EXCLUDED.deleted, src_lsn = EXCLUDED.src_lsn, src_seq = EXCLUDED.src_seq, schema_version = EXCLUDED.schema_version, updated_at = now() WHERE (t.src_lsn, t.src_seq, t.schema_version) < (EXCLUDED.src_lsn, EXCLUDED.src_seq, EXCLUDED.schema_version);Let's trace three tricky events on
(org_77, rule_84)to see why this metadata guarantees idempotency and ordering:Incoming event Stored (src_lsn, src_seq) What happens? 1. Update port=443 at (0/300, 0) none Row inserted with (0/300, 0), deleted=false 2. Duplicate of event 1 at (0/300, 0) (0/300, 0) WHERE (0/300,0) < (0/300,0) is FALSE -> no-op 3. Delete rule at (0/380, 0) (0/300, 0) Updated to deleted=true, version=(0/380, 0) 4. Late replay of old (0/340, 0) (0/380, 0) WHERE (0/380,0) < (0/340,0) is FALSE -> stays deleted!Why
(commit_lsn, seq_in_tx)beats wall-clock timestamps or per-statement LSNs: - Wall-clock timestamps can tie within the same millisecond or jump backward during NTP clock adjustments. - Per-statement LSNs reflect when a statement ran, not when its transaction committed: a long-running transaction can modify a row early (low statement LSN) and commit late (high commit LSN). PostgreSQL'scommit_lsnstrictly reflects actual commit order, andseq_in_txbreaks ties when the same transaction updates the same row twice. - Tombstones are filtered out by regional read queries (WHERE deleted = FALSE) and garbage-collected after 14 days (twice our 7-day Kafka retention window).High-level architecture
ON-PREMISE DATA CENTER [ Write API ] ---> [ PostgreSQL Primary ] ===physical WAL stream===> [ Physical Standby (PG 16+) ] ^ (64-row heartbeat | | updated every 1 s) logical slot (pgoutput) | v | [ Debezium CDC Connector ] | | | [ Kafka: policy-changes (64 parts, RF=3) ] | | | Cloud appliers PULL over mTLS via Direct Connect / Interconnect / ExpressRoute | +----------------------------------+---------------------+------------------------+ | v v v | AWS (us-east-1, eu-west-1) GCP (us-central1, europe-west1) Azure (eastus, westeurope) | +--------------------------------------------------------------------------------------------------+ | | Inside each of the 6 cloud regions: | | | [ Applier Consumer Group (up to 64 workers) ] ---> [ Regional PostgreSQL ] ---> [ Read API ] | | | ^ | | | [ Cloud L4 Load Balancer ] ---> [ Stateless Envoy API Gateway Fleet ] ---------------+ | | | | (local JWKS auth + leased token buckets + routing) | | +-------------------------------------+------------------------------------------------------------+ | | +---- PUT/POST/DELETE forwarded over mTLS --+ ^ [ Global Latency-Based DNS ] ^ External Clients (10k+ RPS) [ Control Plane ] collects per-(region, partition) applied LSN & health; pushes routing + token deny-lists (~500 ms) [ Identity (IdP) ] issues short-lived OAuth2 JWTs; gateways cache its public signing keys (JWKS)Two architectural choices keep this clean and resilient: - Cloud regions pull from Kafka instead of on-premise pushing to clouds. On-premise Kafka never needs to track which cloud region is down or manage per-cloud retry queues. Each cloud region runs its own Kafka consumer group (
applier-aws-us-east-1,applier-gcp-europe-west1, etc.) and pulls at its own pace from its own saved offset. - Kafka lives on-premise next to the database. Debezium writes over the fast local LAN, advancing the PostgreSQL replication slot immediately so WAL files do not pile up on database disks when a cloud WAN link degrades.Deep dive 1: CDC without burdening the primary
Let's compare the common ways teams publish database changes and see why log-based CDC over Kafka wins under our strict "do not burden the primary" constraint:
Approach Extra load on primary DB Captures deletes & order? Verdict -------------------------- --------------------------- ------------------------- ------------------------- Poll "WHERE updated_at > T" Repeated index/table scans Misses hard deletes; ties Rejected (heavy + lossy) DB triggers -> queue table Doubles every write + locks Yes Rejected (burdens primary) Dual write (app -> DB & bus) Zero DB overhead Partial crash = drift Rejected (data corruption) Transactional outbox table 1 extra INSERT per tx Yes, clean event schema Good, requires app rewrites Log-based CDC from WAL Reads sequential log only Yes, exact commit order ChosenHow we keep primary database impact near zero: - Run logical decoding on the physical standby (PostgreSQL 16+). PostgreSQL 16+ allows logical replication slots on a physical read standby, and Debezium 2.5+ streams directly from it. The primary does zero extra CPU work beyond its normal high-availability WAL shipping. - Use
REPLICA IDENTITY FULLon replicated policy tables. Because our policy change volume is small (~200 KB/s), logging the full before/after row in WAL adds negligible disk I/O while guaranteeing that everyUPDATEandDELETEincludestenant_idand complete column values (avoiding missing large out-of-line PostgreSQLTOASTcolumns on partial updates). - Protect database disks withmax_slot_wal_keep_size. A replication slot tells PostgreSQL not to delete WAL segments until the CDC connector has read them. If Kafka or Debezium ever stalled for days, unbounded WAL retention could fill the disk and crash the database. Settingmax_slot_wal_keep_size(for example, 50 GB—over two days of changes) caps disk usage; if breached, we re-seed from a standby snapshot rather than risking primary availability. - 64-row heartbeat table. Once per second, a lightweight job updates 64 rows in a tinycdc_heartbeat(slot_id PRIMARY KEY, ts TIMESTAMPTZ)table whose keys hash one-to-one onto the 64 Kafka partitions. That single 64-row write per second ensures every partition receives a fresh LSN and timestamp every second, even when no customer policies change.Deep dive 2: Atomic transactions and consistency model
Why row-by-row application is unsafe. Suppose an administrator replaces a broad rule with two narrower rules in one primary transaction: first inserting
ALLOW 0.0.0.0/0on a staging group and then insertingDENY 0.0.0.0/0except SSH. If a cloud region committed each row change separately, clients reading in between would briefly see the half-applied policy!Because PostgreSQL logical decoding emits a transaction's changes contiguously after
COMMIT, and all rows for a tenant share one Kafka partition (key = tenant_id), the regional applier simply buffers rows sharing the sametx_idand commits them together withapply_checkpointinside one local PostgreSQL transaction:def run_partition_applier(consumer, db, partition_id): """Consume one Kafka partition and apply whole source transactions atomically.""" row = db.one( "SELECT last_kafka_offset FROM apply_checkpoint WHERE partition_id = %s", partition_id, ) next_offset = 0 if row is None else row.last_kafka_offset + 1 consumer.seek(partition_id, next_offset) pending = [] # buffered events belonging to the same primary tx_id for event in consumer.poll_forever(partition_id): if pending and event.tx_id != pending[0].tx_id: commit_batch(db, partition_id, pending) pending = [] if event.op == "h": # A heartbeat closes any preceding tx and advances checkpoint LSN + timestamp with db.transaction(): db.run( "INSERT INTO apply_checkpoint (partition_id, last_kafka_offset, last_commit_lsn, last_commit_ts) " "VALUES (%s, %s, %s, %s) " "ON CONFLICT (partition_id) DO UPDATE SET " "last_kafka_offset = EXCLUDED.last_kafka_offset, " "last_commit_lsn = EXCLUDED.last_commit_lsn, " "last_commit_ts = EXCLUDED.last_commit_ts", partition_id, event.offset, event.commit_lsn, event.commit_ts, ) else: pending.append(event) def commit_batch(db, partition_id, events): """Commit all row changes of a source transaction plus the Kafka offset atomically.""" with db.transaction(): for ev in events: upsert_versioned_row(db, ev) # runs the INSERT ... ON CONFLICT ... WHERE SQL last = events[-1] db.run( "INSERT INTO apply_checkpoint (partition_id, last_kafka_offset, last_commit_lsn, last_commit_ts) " "VALUES (%s, %s, %s, %s) " "ON CONFLICT (partition_id) DO UPDATE SET " "last_kafka_offset = EXCLUDED.last_kafka_offset, " "last_commit_lsn = EXCLUDED.last_commit_lsn, " "last_commit_ts = EXCLUDED.last_commit_ts", partition_id, last.offset, last.commit_lsn, last.commit_ts, )If the applier crashes at any line, PostgreSQL rolls back any uncommitted batch, and on restart
consumer.seekresumes atlast_kafka_offset + 1.Eventual vs. strong consistency. Synchronous strong consistency across AWS, GCP, and Azure would force every primary commit to wait 70–150 ms for the slowest cross-ocean region and would block writes whenever a cloud region was unreachable—violating both primary performance and high availability. Instead, we use asynchronous eventual consistency upgraded with four client-visible guarantees: 1. Consistent prefix per tenant: Every region shows a tenant's policies at a clean transaction boundary, never half a transaction. 2. Monotonic reads: Clients pass back the highest
X-Data-Versionthey have seen asX-Min-Version, so even if DNS flips them to another region, they never step backward in time. 3. Read-your-writes: After aPUTreturnsX-Data-Version, passing it asX-Min-Versionroutes subsequent reads only to regions whose partitionlast_commit_lsn >= X-Min-Version(with automatic fallback to the primary if a read arrives milliseconds before CDC finishes). Because the 1-second heartbeat advances every partition'slast_commit_lsn, even idle partitions catch up past the global LSN within a second. 4. Bounded staleness: Any region whose lag exceeds 60 seconds is automatically pulled out of read rotation.Deep dive 3: API gateway auth, rate limiting, and routing
At the proxy layer, we separate external edge traffic from internal east-west calls: stateless edge gateway proxies (Envoy fleet behind each cloud's Layer-4 network load balancer) handle TLS termination, auth, rate limiting, and cross-region routing, while lightweight sidecar proxies inside each region handle mutual TLS (mTLS) and retries between internal microservices.
1. Sub-millisecond authentication. - Clients authenticate with short-lived (10-minute) JSON Web Tokens (JWTs) signed by the Identity Service, or with hashed API keys. - Gateways cache the Identity Service's public signing keys (JWKS, refreshed every 5 minutes in the background) and verify JWT signatures locally in ~0.2 ms. Once verified, a node caches
sha256(token) -> claimsin local RAM until expiry, cutting repeat verification to microseconds. - Emergency revocation uses a compact deny-list pushed by the control plane to all gateways within seconds.2. Distributed rate limiting with leased Token Buckets. A token bucket holds up to
bursttokens and refills smoothly atratetokens per second; each request consumes 1 token, or gets429 Too Many Requestswhen empty. Calling a central Redis on every request would add network latency and a failure point; dividing the limit statically bynum_nodesunder-utilizes quota when traffic is uneven. Instead, each gateway node runs a local in-memoryTokenBucketand leases small batches of tokens (say, 10% of the per-second quota) asynchronously from its regional Redis:import time class TokenBucket: """In-memory token bucket: refills `rate` tokens/sec up to `burst`.""" def __init__(self, rate: float, burst: float): self.rate = rate self.burst = burst self.tokens = burst self.updated_at = time.monotonic() def allow(self, cost: float = 1.0) -> bool: now = time.monotonic() elapsed = now - self.updated_at self.tokens = min(self.burst, self.tokens + elapsed * self.rate) self.updated_at = now if self.tokens >= cost: self.tokens -= cost return True return FalseHot-path latency is a few nanoseconds of local arithmetic; if regional Redis ever goes down, nodes automatically fall back to
global_region_share / active_nodes.3. Freshness- and residency-aware routing. Every 500 ms, the control plane pushes a tiny snapshot of
6 regions x 64 partitions = 384(applied_lsn, lag_seconds, health)entries to every gateway node. Routing is then a pure in-memory check:def choose_region(req, local_region, regions, state): """Pick a target region in < 0.1 ms with zero network calls.""" if req.is_write: return "on-prem-primary" part = hash_tenant_to_partition(req.tenant_id, 64) candidates = [] for reg in regions: if req.required_geo and reg.geo != req.required_geo: continue # enforce data residency (e.g., EU-only tenant) if reg.circuit_open or state.lag_seconds(reg.id, part) > 60: continue # unhealthy or exceeds 60s staleness bound if req.min_lsn is not None and state.applied_lsn(reg.id, part) < req.min_lsn: continue # has not yet applied the client's recent write candidates.append(reg) if local_region in candidates: return local_region # fast path: serve right here! if candidates: return min(candidates, key=lambda r: local_region.rtt_ms_to(r)) if req.min_lsn is not None and (not req.required_geo or req.required_geo == "on-prem"): return "on-prem-primary" # read-your-writes fallback return None # gateway returns 503 Retry-AfterMonitoring replication lag and handling failures
Monitoring replication lag. Relying on Kafka consumer offset lag alone is a classic trap: if Debezium crashes or the PostgreSQL slot stalls, nothing new enters Kafka, so consumer offset lag happily reports
0while cloud data grows hours stale! We monitor four distinct checkpoints:Stage Metric What problem it catches ------------------ --------------------------------------------- ------------------------------------------ 1. PostgreSQL slot pg_wal_lsn_diff(replay_lsn, restart_lsn) Unconsumed WAL piling up toward disk cap 2. CDC connector Debezium MilliSecondsBehindSource Slow WAL decoding or Kafka publish stall 3. Kafka consumer (latest_offset - committed_offset) per part Applier backlog in a specific cloud region 4. End-to-end SLO now() - apply_checkpoint.last_commit_ts True user-visible staleness across ALL hopsBecause the 64-row heartbeat updates every partition once per second,
now() - last_commit_tsmeasures true end-to-end lag continuously even at 3 AM when zero policies are edited. Warn if p99 heartbeat lag exceeds 30 s for 5 minutes; page if it exceeds 5 minutes or if retained slot WAL exceeds 50% ofmax_slot_wal_keep_size. To verify data correctness (not just speed), an hourly background job hashes rows for tenants with no edits in the past 10 minutes on the standby and across all regions, alerting and re-syncing any mismatched tenant.Failure handling across components.
Failure scenario Impact & automated recovery --------------------------------- ----------------------------------------------------------------------- Single cloud region unreachable Circuit breakers open in ~10 s; DNS + peer gateways route eligible tenants to nearest healthy region. Appliers resume from checkpoint later. Private link to one cloud cut Traffic fails over to encrypted VPN backup; if lag > 60 s, region leaves read rotation until caught up. X-Data-As-Of shows exact data age. Single Kafka broker crashes Zero impact: replication factor 3, min.insync.replicas=2, acks=all. Entire Kafka cluster down Primary writes still succeed! Standby slot retains WAL safely on disk; clouds serve last consistent state until Kafka returns and drains WAL. WAL cap hit (slot invalidated) Take consistent snapshot from standby tagged with snapshot_lsn, upsert rows into affected regions, tombstone missing rows, resume streaming. On-prem primary crashes Promote physical standby (PG 16+ preserves logical slots across failover), point Write API to new primary, rebuild a new standby. Reads never stop. Poison event fails in one tenant Retry with backoff; if still failing, quarantine that tenant_id's events to a per-tenant park table, route that tenant elsewhere, keep other tenants on the partition flowing.Summary of trade-offs
- Log-based CDC from standby vs. triggers or polling: Zero write amplification on the primary and exact commit ordering including deletes, at the cost of coupling raw CDC events to database table schemas (managed via Schema Registry and expand-and-contract migrations).
- Asynchronous eventual consistency + LSN tokens vs. synchronous global commits: Keeps primary commits fast (local millisecond latency) and immune to cloud outages, while
X-Min-Version, atomic transaction batching, and 60-second staleness eviction still give clients read-your-writes and consistent snapshots. - Partitioning by
tenant_idvs. byrow_id: Guarantees foreign-key-like ordering across rules, rule sets, and labels for a tenant and enables atomic per-tenant transactions, trading away cross-partition parallelism for a single massive tenant. - Checkpoint-in-DB + per-row
(src_lsn, src_seq)vs. deduplication ID table: Gives O(1) metadata per row and handles both normal crash restarts and out-of-order re-snapshots, whereas a table of seenevent_ids grows without bound and cannot reject older updates arriving after newer ones. - Pull-based regional appliers vs. central push orchestrator: Decouples on-premise completely from cloud health—an offline cloud simply pauses its consumer offset—at the cost of opening outbound private-link consumers from each cloud.
- Local JWKS auth + leased token buckets vs. centralized per-request checks: Hits single-digit millisecond gateway latency and survives Redis or IdP blips, accepting bounded token-revocation delay (seconds via control-plane deny-list) and tiny burst over-admission (
nodes x lease_size).
Intuition & how it works
Think of this system like a newspaper printing press with regional newsstands around the world. The headquarters press (the on-premise PostgreSQL primary) writes every edit into a numbered master ledger called a Write-Ahead Log (WAL)—an append-only recovery journal PostgreSQL already writes to disk for every transaction. Rather than asking the busy editor to telephone six cloud offices every time a sentence changes, a clerk sitting next to a backup copy of the ledger (Change Data Capture, or CDC, which reads database log entries and turns them into events) copies each finished batch of edits onto a numbered conveyor belt (Apache Kafka). Delivery trucks in AWS, GCP, and Azure each pull from that belt at their own speed and update their local newsstands, while local receptionists (API Gateways) check visitor badges and hand out the latest local issue—unless a visitor shows a receipt (X-Min-Version) from an edit they just submitted, in which case the receptionist makes sure the local copy includes at least that edition number.
The naive approach—having the application write to PostgreSQL and simultaneously push HTTP requests to AWS, GCP, and Azure, or polling SELECT * FROM policies WHERE updated_at > last_run—fails quickly at scale. Synchronous cross-cloud writes add 70–150 ms of ocean round-trip latency to every commit and stall the primary whenever any cloud blips, while polling hammers the primary with scans, misses hard deletes, and can show half-applied security policies. Similarly, an API gateway that calls a central auth server or central Redis on every request burns its 100 ms latency budget on network hops.
Walk through a concrete 4-step trace for tenant org_77:
1. Write on primary: Admin updates rule rule_84 (port = 443) and deletes obsolete rule rule_83 in one primary transaction tx_id = 9104, committing at WAL position (called a Log Sequence Number, or LSN) 0/4F80A100. The Write API returns X-Data-Version: 0/4F80A100.
2. Stream via CDC: Debezium reads tx_id = 9104 from the standby's WAL and publishes two ordered events—(0/4F80A100, seq 0) and (0/4F80A100, seq 1)—to Kafka partition 27 (selected deterministically from "org_77" across the 64 partitions).
3. Atomic & idempotent apply: In gcp-us-central1, applier worker 27 buffers both events until tx_id changes (or the 1-second heartbeat arrives), then commits both row changes (rule_83 marked deleted = true, rule_84 updated with src_lsn = 0/4F80A100) plus apply_checkpoint.last_commit_lsn = 0/4F80A100 in one regional PostgreSQL transaction. If Kafka ever redelivers (0/4F80A100, seq 0), the WHERE (src_lsn, src_seq) < EXCLUDED guard turns it into a harmless no-op.
4. Fast local read: Client calls GET /v1/tenants/org_77/policies/pol_402 with X-Min-Version: 0/4F80A100. The nearest Envoy gateway verifies the JWT locally (< 0.5 ms), consumes 1 token from its local leased token bucket (an in-memory counter that refills at a steady rate to cap request bursts), sees gcp-us-central1 partition 27 is at 0/4F80A100 >= 0/4F80A100, and serves the read locally in ~8 ms total.
Key trade-offs
- Log-based CDC on a standby vs. transactional outbox vs. triggers/polling: Streaming the WAL from a PostgreSQL 16+ physical standby adds zero write load to the primary, captures deletes, and preserves exact commit order. The trade-off is that raw CDC events mirror physical table columns, whereas a transactional outbox (an application-written event table committed alongside business tables) decouples event schemas from table schemas at the cost of extra primary writes and application code changes.
- Asynchronous eventual consistency with LSN tokens vs. strong cross-cloud consistency: Synchronous quorum or two-phase commit across three clouds would add 70–150 ms per write and couple primary availability to WAN links. Asynchronous replication keeps writes fast and independent, while per-tenant transaction batching,
X-Min-Versionread-your-writes tokens, and a 60-second staleness cutoff provide the consistency properties users actually rely on. - Partitioning Kafka by
tenant_idvs. byrow_id: Keying bytenant_idkeeps a tenant's policies, rule sets, and labels in one partition so foreign-key relationships and multi-row transactions stay intact. Keying byrow_idspreads a giant tenant across all 64 workers, but allows a region to briefly enforce a rule before the label group it references arrives. - Transactional offset checkpoint + per-row
(src_lsn, src_seq)vs. seen-event-ID table: Committinglast_kafka_offsetinside the same regional DB transaction gives exact-once state updates during normal restarts, while storing(src_lsn, src_seq)on each row handles cross-path replays (connector restarts, standby re-snapshots, dead-letter replays) in constantO(1)space per row. A deduplication table of seenevent_ids grows unboundedly and cannot prevent an older delayed event from overwriting a newer row. - Local gateway decisions vs. centralized auth and rate-limit lookups: Local JWT verification via cached JWKS (JSON Web Key Sets—public cryptographic keys used to verify token signatures) and batched Redis token leases keep gateway CPU + routing under 10 ms and survive Redis or Identity Provider outages, trading off a few seconds of revocation propagation delay and small bounded burst slack (
num_nodes x lease_size).
Common mistakes
- Dual-writing from application code to PostgreSQL and Kafka: If the app crashes or times out after committing to PostgreSQL but before publishing to Kafka (or vice versa), the primary and cloud databases silently diverge forever.
- Ordering events with wall-clock timestamps or statement LSNs: Server clocks skew across machines and tie within a millisecond, while early statements inside a long-running transaction carry lower LSNs than short transactions that committed earlier; always order by
(commit_lsn, seq_in_tx). - Applying CDC events one row at a time without transaction boundaries: Committing row-by-row exposes half-applied policy edits in cloud regions, which in a security product can briefly allow blocked traffic or lock out production workloads.
- Executing hard
DELETEs in cloud databases: Physically deleting the destination row removes itssrc_lsnhistory, so a delayed replay of an earlier upsert will resurrect the deleted policy; use versioned tombstones (deleted = true) instead. - Leaving PostgreSQL replication slots uncapped: Without
max_slot_wal_keep_sizeand disk alerts, a broken CDC connector forces PostgreSQL to retain WAL files until the database disk fills up and crashes. - Monitoring only Kafka consumer offset lag: Offset lag only measures the gap between Kafka and the applier; if Debezium stops publishing, offset lag reads
0while cloud data gets arbitrarily stale. Use end-to-end 1-second heartbeat lag (now() - last_commit_ts). - Making synchronous cross-region auth or Redis calls on every gateway request: One network hiccup or cross-region hop blows the sub-100 ms gateway SLA and turns a single dependency into a global point of failure.
Follow-up questions
- Suppose the on-premise PostgreSQL database undergoes a table schema change before every cloud deployment has rolled out the new application build—how do you prevent replication breakages or lost fields? Enforce an expand-and-contract migration policy backed by a Schema Registry: phase 1 (expand) only adds nullable columns or optional fields with defaults—never renames or drops columns in place—so older regional services and appliers safely ignore unknown fields without crashing. To ensure values written on the primary during the upgrade window are not lost when an older applier ignores the new field, either upgrade regional schemas and appliers before enabling the primary writer feature flag, or store
schema_versionon each destination row (so replaying recent Kafka offsets after the regional upgrade updates rows whereEXCLUDED.schema_version > t.schema_version, with unknown fields optionally preserved in an overflowJSONBcolumn). Only after every cloud deployment reports the newschema_versionto the control plane does phase 2 (contract) drop deprecated columns. - When an isolated cloud deployment reconnects after a two-hour network blackout, how do you replay the missed updates without overwhelming its database or WAN link? At 200 changes/s, a 2-hour blackout leaves ~1.44 million events (~1.44 GB) in Kafka—well within our 7-day retention—and the region's appliers automatically resume from
apply_checkpoint.last_kafka_offset + 1. To avoid saturating the regional PostgreSQL instance or shared WAN link, throttle the consumer group to a safe cap (for example, 5,000 events/s = ~5 MB/s, draining the backlog in ~5 minutes), batch multiple complete source transactions per local DB commit, and coalesce intermediate updates to the same(tenant_id, rule_id)in memory before writing. Keep the deployment marked stale (out of read rotation) until its end-to-end heartbeat lag drops below 10 seconds, then gradually ramp gateway traffic back (10% -> 50% -> 100%over several minutes) so connection pools and caches warm smoothly without a thundering herd. - How should the edge gateway use circuit breaking and retry controls so one slow or failing cloud deployment cannot trigger a cascading global outage? A circuit breaker is an automatic state machine (
Closed -> Open -> Half-Open) tracked per(gateway_node, target_region)that stops sending requests to a failing dependency before thread pools and sockets back up. InClosedstate, requests flow normally with tight per-try timeouts (~300 ms); if error rate (5xx + timeouts) exceeds 50% or p99 latency exceeds 3x baseline over a 10-second rolling window (minimum 20 requests), the breaker tripsOpenand immediately routes eligible reads to the next-closest healthy region without waiting on timeouts. After a 30-second cooldown,Half-Openlets a small probe (for example, 5 requests) test recovery, closing the circuit only if all succeed. Pair breakers with a strict retry budget (capping retries at <= 10% of total traffic on idempotent requests only) and load shedding (429/503) on neighboring deployments so failover traffic never cascades into a multi-region outage.
Follow-up questions
- Suppose the on-premise PostgreSQL database undergoes a table schema change before every cloud deployment has rolled out the new application build—how do you prevent replication breakages or lost fields?
- When an isolated cloud deployment reconnects after a two-hour network blackout, how do you replay the missed updates without overwhelming its database or WAN link?
- How should the edge gateway use circuit breaking and retry controls so one slow or failing cloud deployment cannot trigger a cascading global outage?
Similar questions
- Distributed Time-Series Metrics Database
- Connected Land Regions in a Matrix
- Clockwise Spiral Order and Two-Sum Check
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform