Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Dynamic Network Connectivity &
Fraud Ring Detector with Union-Find.

Partition link events into an idempotent WAL feeding stateful DSU engine shards with periodic RocksDB snapshots and bounded-window edge expiry.
Start the journey7 stages· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If latency budgets leave no room for synchronous retries, because DSU merges are associative and commutative, you can recover exact cluster state from an append-only WAL + periodic checkpoints and trigger fraud alerts on the exact union() that crosses the ring-size threshold.

TL;DR30-second simplified summary
▾

Encoding -size in parent[root] lets a single int32 array hold 200M nodes in 800 MB. Ingesting via Kafka with a Count-Min Sketch hub gate prevents super-node collapses.

Replicas tail the same stream for sub-5ms sameRing() queries, and scheduled epoch rebuilds expire old links.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Disjoint Set Union (Union-Find): Path Compression & Union by Rank
Disjoint Set Union (DSU) maintains a partition of N elements into non-overlapping sets, supporting find(x) and union(x, y) in O(alpha(N)) amortized time.
Consistent Hashing & Virtual Nodes
Consistent hashing assigns data keys to servers in a way that limits how many keys move when servers are added or removed. This helps avoid widespread cache misses and sudden load on databases.
Change Data Capture (CDC)
Change Data Capture (CDC) streams row-level inserts, updates, and deletes directly from a database's transaction log (WAL/binlog/oplog) into event buses like Kafka—eliminating dual-write race conditions and heavy polling queries.
Full walkthrough · 7 stages
01
STAGE 01 · SCALE & MEMORY MATHfoundation

Sizing 200M-Node DSU State & Latency Budgets.

Why this matters: Size a 200M-account fraud-ring DSU in 800 MB RAM plus a RocksDB ID-interning map with <1 ms connectivity queries.

Assume 200M active accounts mapped to dense int32 internal IDs via an ID-interning RocksDB/hash table.

  • DSU Array: 200M * 4 bytes (negative-size parent[]) = 800 MB RAM.
  • ID Interning Map: 200M * ~24 bytes = ~4.8 GB RAM.
  • Throughput: 100K union()/sec and 250K find()/sec easily run on 1–4 CPU cores in C++/Rust/Go at ~100 ns per operation.
STAGE 01 · SCALE & MEMORY MATH

Sizing 200M-Node DSU State & Latency Budgets

200M ActiveAccountsDense ID Space800 MB DSU ArrayCompact Forest4.8 GB RocksDBInternerID Lookup<1 ms sameRing(A,B)Latency SLApersisted in

1.Memory Footprint: 200M * 4 bytes = 800 MB for negative-size parent[]—fits easily in L3/RAM on one server.

2.Dense int32 Encoding: Negative parent[root] stores -component_size, eliminating a separate rank/size array.

3.Query Budget: Fraud-check API calls sameRing(A, B) inline during checkout in <1 ms.

Dense int32[] parent encoding fits 200M accounts in 800 MB RAM and serves sameRing(A, B) in <1 ms.

02
STAGE 02 · INGESTION & SUPER-NODE GUARDfoundation

Preventing False-Positive Collapses on Shared IPs & Hubs.

Why this matters: Prevent false-positive mega-component collapses on shared Wi-Fi/CGNAT IPs using attribute degree caps.

A naive union(account, ip) merges every user on an airport Wi-Fi or CGNAT IP into one mega-component. Before emitting a union edge for an attribute (IP, device, card), enforce a degree cap (e.g., max 20 accounts per IP per 24h) using a Redis/HyperLogLog or Count-Min Sketch gate.

Attributes exceeding the threshold are quarantined as super_node signals rather than hard DSU edges.

STAGE 02 · INGESTION & SUPER-NODE GUARD

Preventing False-Positive Collapses on Shared IPs & Hubs

Edge Event (Acct,IP)Raw SignalHyperLogLog / CountDegree CheckDegree > 20QuarantineSuper-Node GuardSafe DSU union(a,b)Accurate Ringsif > 20

1.Airport Wi-Fi Trap: One shared IP with 5,000 travelers would merge 5,000 innocent users into one giant fraud ring.

2.Attribute-Specific Caps: Cap shared IPs at 20 accounts, shared devices at 5, and shared cards at 3.

3.Quarantine Log: Send excluded super-node attributes to a separate anomaly stream instead of the DSU.

Attribute degree caps quarantine shared Wi-Fi/CGNAT IPs before union(), preventing giant-component false positives.

Engineering Decision Framework
Problem
How to implement Design a Dynamic Network Connectivity & Fraud Ring Detector with Union-Find without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
If latency budgets leave no room for synchronous retries, because DSU merges are associative and commutative, you can recover exact cluster state from an append-only WAL + periodic checkpoints and trigger fraud alerts on the exact union() that crosses the ring-size threshold.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design a Dynamic Network Connectivity & Fraud Ring Detector with Union-Find experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · CORE DSU ENGINEintermediate

Thread-Safe Sharded Engine with Threshold Alerting.

Why this matters: Implement FraudRingDSU with iterative path halving, union-by-size, and >50-member ring threshold alerts.

On every union(a, b) that merges two distinct components whose combined size crosses ALERT_THRESHOLD = 50, emit an asynchronous alert event to the Risk Sink.

class FraudRingDSU:
    def __init__(self, capacity: int, alert_threshold: int = 50) -> None:
        self.parent = [-1] * capacity
        self.alert_threshold = alert_threshold

def find(self, x: int) -> int:
        if not (0 <= x < len(self.parent)):
            raise ValueError('Invalid account ID')
        root = x
        while self.parent[root] >= 0:
            root = self.parent[root]
        while x != root:
            nxt = self.parent[x]
            self.parent[x] = root
            x = nxt
        return root
STAGE 03 · CORE DSU ENGINE

Thread-Safe Sharded Engine with Threshold Alerting

Iterative PathHalvingSafe FindUnion by SizeBalanced MergeCrosses Size >= 50?Ring DetectionEmit Risk SinkAlertFraud Actionchecks size

1.Iterative Only: Path halving (parent[x] = parent[parent[x]]) runs in a simple while loop with zero recursion.

2.One-Time Crossing Alert: Alert when a merge pushes combined size from <50 to >=50 so downstream isn't spammed.

3.Thread Safety: Shard or synchronize writes on the single writer thread while serving lock-free/RCU reads.

Iterative path halving and union-by-size emit risk alerts the moment any merged component crosses 50 accounts.

04
STAGE 04 · CRASH RECOVERYintermediate

Idempotent WAL Replay & Non-Blocking Snapshots.

Why this matters: Recover crashed DSU instances via copy-on-write 60s parent[] snapshots and idempotent Kafka WAL replay.

Because union(a, b) is commutative and associative, replaying duplicate WAL records after a crash is naturally idempotent! Every 60 seconds, fork/copy-on-write snapshot the parent[] array + Kafka offset to object storage (S3/GCS).

On restart, mmap the latest 800 MB snapshot in < 1 second and replay only the tail WAL from the recorded offset.

STAGE 04 · CRASH RECOVERY

Idempotent WAL Replay & Non-Blocking Snapshots

Kafka Edge TopicIdempotent Log60s Fork / CoWSnapshotFast CheckpointCrash RestoreSub-10s RecoveryExact State RebuiltZero Driftrestores

1.Natural Idempotency: Because union(a, b) is commutative and associative, replaying duplicate Kafka messages changes nothing.

2.Copy-on-Write Fork: Using Linux fork() snapshots the 800 MB array to disk without pausing live queries.

3.Fast Boot: Loading an 800 MB binary snapshot plus 60s of Kafka tail takes <10 seconds.

60s copy-on-write snapshots and naturally idempotent Kafka union replay recover 200M-node state in <10 seconds.

05
STAGE 05 · HANDLING EDGE EXPIRYadvanced

Rolling Epoch DSU for 30-Day Sliding Windows.

Why this matters: Expire edges older than 30 days using rolling shadow-rebuilt epoch snapshots swapped atomically at midnight.

Instead of deleting edges online, maintain daily or weekly DSU epochs (or a background shadow-rebuild job over the trailing 30-day edge log). At midnight UTC, promote the freshly built 30-day DSU snapshot atomically via pointer swap.

Queries read the active immutable-horizon snapshot + live delta ring buffer.

STAGE 05 · HANDLING EDGE EXPIRY

Rolling Epoch DSU for 30-Day Sliding Windows

30-Day Edge LogSource of TruthNightly Shadow BuildOffline RebuildAtomic Pointer SwapZero DowntimeStale Edges PrunedClean Windowpromotes

1.Why Not Online Delete?: Standard DSU with path compression cannot delete individual edges efficiently.

2.Shadow Rebuild Cost: Replaying 30 days of edges into a fresh int32[] array takes ~2 minutes on one background core.

3.Atomic Cutover: Swap the read-replica pointer cleanly once the shadow snapshot catches up to Kafka head.

Background 30-day shadow rebuilds and atomic pointer swaps expire old edges without sacrificing O(alpha(N)) finds.

06
STAGE 06 · READ SCALINGadvanced

Read Replicas & Cross-Shard Federation.

Why this matters: Scale read throughput linearly by replicating the Kafka edge stream to N local-RAM read replicas.

Replicate the Kafka edge stream to N stateless-recovery read replicas. Each replica maintains an identical in-memory DSU and serves sameRing(A, B) locally in < 1 ms.

If graph size outgrows single-node RAM, shard by region/tenant or run a two-tier architecture: local shard DSU + global cross-shard boundary-edge DSU.

STAGE 06 · READ SCALING

Read Replicas & Cross-Shard Federation

Kafka Edge StreamSingle SourceRead Replica 1<1ms sameRingRead Replica N<1ms sameRingRegion FederationFuture Scalestreams to

1.Zero Network Read Hop: Every API replica or sidecar holds the 800 MB DSU locally—queries never cross the network.

2.Deterministic Convergence: All replicas applying the same ordered Kafka log converge to identical connected components.

3.Regional Sharding: If accounts exceed 1B, shard by region and federate rare cross-region edges.

Streaming the Kafka edge log to local-RAM read replicas scales sameRing() reads horizontally at <1 ms.

07
STAGE 07 · OBSERVABILITY & FAILURE MODESadvanced

Monitoring Giant-Component Drift & Replication Lag.

Why this matters: Monitor max_component_size, p99 find hops, super-node quarantine rate, and WAL consumer lag.

Think of Monitoring Giant-Component Drift & Replication Lag as the intuition layer for Design a Dynamic Network Connectivity & Fraud Ring Detector with Union-Find: Monitor max_component_size, p99 find hops, super-node quarantine rate, and WAL consumer lag.

Track max_component_size, p99_find_hops, super_node_quarantine_rate, and wal_consumer_lag_ms. If max_component_size spikes suddenly (e.g., > 100K accounts), trigger an automatic circuit breaker that pauses ingestion from the offending attribute source and rolls back to the previous 60-second snapshot.

STAGE 07 · OBSERVABILITY & FAILURE MODES

Monitoring Giant-Component Drift & Replication Lag

max_component_sizeCollapse Guardp99_find_hopsTree Healthsuper_node_quarant…Signal Hygienewal_consumer_lag_msSync KPItuned by

1.Giant-Component Breaker: If max_component_size jumps past 100K, pause ingestion automatically before flagging innocent users.

2.Hop Count Check: Rising p99_find_hops signals path compression was accidentally disabled.

3.Lag Alert: Alert if replica WAL lag exceeds 5 seconds so checkout fraud checks stay fresh.

Giant-component circuit breakers (>100K), p99 hop counts, and WAL lag alerts keep fraud-ring detection accurate.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why is replaying an edge stream from a Kafka offset after a crash safe for DSU state recovery?

Recommended Learning Flow