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

Surviving JVM Stop-the-World
GC Pauses.

A 6-second JVM Stop-the-World GC or safepoint pause freezes all application and heartbeat threads, causing ZooKeeper/etcd/cluster peers to declare the node dead and elect a new leader while the paused node still believes it holds the lease.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, reduce STW pauses below 10 ms via Generational ZGC + GC-safe off-heap/pool allocation, and pair heartbeats with monotonic fencing tokens so a zombie node waking from a GC freeze cannot corrupt shared state.

TL;DR30-second simplified summary
▾

Core Mechanics: A stateful Java node on a 32 GB heap (allocating 4 GB/sec) holds an etcd/ZooKeeper leader lease (5s TTL, 1s heartbeat).

Visual & Structural Flow: Depicts Zombie Split-Brain vs. Storage-Enforced Fencing Token (Node 1 (tok=41) -> etcd Lease (5s) -> Node 2 (tok=42) -> Storage CAS); etcd Mod-Revision Fencing + Generational ZGC (etcd / ZK Quorum -> Leader (Gen ZGC) -> Zombie (Paused) -> Storage Engine).

Trade-Offs & Production: Checking System.currentTimeMillis() < leaseExpiry before writing is broken: the JVM can freeze for 6.5s between the if check and the network write() call, and wall clocks can skew. Combine sub-millisecond GC pauses with cryptographic/monotonic storage fencing: Generational ZGC (-XX:+UseZGC -XX:+ZGenerational): Performs concurrent marking and relocation.

Failure Modes & Application: Fencing tokens are mandatory whenever distributed leases protect mutable state: Distributed Lock Services & Partition Leaders: Prevents split-brain writes in shard coordinators and cron schedulers.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Low-Pause GC & Fencing Tokens Matter.

Why this matters: The mechanism: understand how Why Low-Pause GC & Fencing Tokens Matter works from first principles.

A stateful Java node on a 32 GB heap (allocating 4 GB/sec) holds an etcd/ZooKeeper leader lease (5s TTL, 1s heartbeat).

When a 6.5-second Stop-the-World (STW) Full GC or safepoint freeze hits, etcd expires the lease and elects a new leader.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Real-World Impact of GC-Induced Split-Brain.

Why this matters: The problem: see what breaks without Real-World Impact of GC-Induced Split-Brain under real concurrency or scale.

Clock/GC freezes break naive distributed leases:

  1. Zombie Writes: A paused node wakes up mid-method (if (isLeader) writeStorage()) long after its 5s lease expired.
  2. Concurrent Two-Leader Window: Both the old zombie and the newly elected leader mutate storage simultaneously.
  3. Safepoint TTSP Delays: Even with low-pause GC, uncounted loops or JNI calls can stall all threads waiting for a JVM safepoint.
GC Freeze & Monotonic Fencing Token

Zombie Split-Brain vs. Storage-Enforced Fencing Token

Node 1 (tok=41)etcd Lease (5s)Node 2 (tok=42)Storage CAS1. 6.5s STW Full GC freeze!2. 5s TTL expires -> N2 elected(tok=42)3. write(tok=42) -> current_tok=424. Zombie wakes: write(tok=41)5. Rejected! 41 < 42 (Fenced)

GC tuning reduces pause frequency, while monotonic fencing tokens enforced by the storage layer make zombie writes impossible.

Engineering Decision Framework
Problem
How to implement Surviving JVM Stop-the-World GC Pauses 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
When traffic spikes expose hidden coupling, reduce STW pauses below 10 ms via Generational ZGC + GC-safe off-heap/pool allocation, and pair heartbeats with monotonic fencing tokens so a zombie node waking from a GC freeze cannot corrupt shared state.
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 Surviving JVM Stop-the-World GC Pauses experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive Solution (and Why It Breaks).

Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.

Think of Naive Solution (and Why It Breaks) as the intuition layer for Surviving JVM Stop-the-World GC Pauses: The problem: see what breaks without Naive Solution under real concurrency or scale.

Checking System.currentTimeMillis() < leaseExpiry before writing is broken: the JVM can freeze for 6.5s between the if check and the network write() call, and wall clocks can skew. Relying solely on GC tuning without fencing tokens is also unsafe because kernel swapping or VM live-migration can still pause a process.

Component Topology

Naive Solution (and Why It Breaks)

ProducersingressBounded QueuecomputeWorker PoolstorageShared Memorycontroloffer(task)dispatchCAS update
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise Solution: Generational ZGC + Monotonic Fencing Tokens.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Combine sub-millisecond GC pauses with cryptographic/monotonic storage fencing:

  • Generational ZGC (-XX:+UseZGC -XX:+ZGenerational): Performs concurrent marking and relocation on a 32 GB heap at 4 GB/sec allocation, keeping STW pauses < 1 ms (far below the 5s lease TTL).
  • Monotonic Fencing Tokens: Every lease acquisition from etcd (mod_revision) or ZooKeeper (zxid) issues a strictly increasing integer token. Pass that token on every storage write.
  • Storage-Side CAS Rejection: The storage layer atomically executes WHERE fencing_token <= :token (or rejects token < max_seen_token), fencing any zombie node regardless of pause duration.
Fenced Leader Election

etcd Mod-Revision Fencing + Generational ZGC

etcd / ZK QuorumIssues monotonic tokenLeader (Gen ZGC)<1ms STW | token=42Zombie (Paused)Stale token=41Acquire lease -> 42

1.Generational ZGC: Handles 4 GB/s alloc rate on 32 GB heap with <1 ms STW pauses.

2.Fencing Token: Strictly monotonic ID (etcd revision / ZK zxid) per lease grant.

3.Storage Enforcement: Only the storage layer can prevent split-brain by rejecting stale tokens.

4.Safepoint Checks: Enable -Xlog:gc*,safepoint to catch non-GC TTSP pauses.

ZGC prevents 6.5s GC freezes in practice, while storage-enforced fencing tokens guarantee correctness even under arbitrary pauses.

// JVM Flags:
// -XX:+UseZGC -XX:+ZGenerational -Xms32g -Xmx32g -XX:+AlwaysPreTouch
// -XX:+PerfDisableSharedMem -Xlog:gc*,safepoint:file=/var/log/gc.log:time,uptime

public final class FencedLeaderClient {
    public record Lease(long fencingToken, long expiresAtNano) {}
    private volatile Lease currentLease = new Lease(-1L, 0L);

    public void renewLease(long ttlNs) {
        long sendNano = System.nanoTime(); // Anchor BEFORE RPC!
        long token = etcdRenewRpc(ttlNs);
        if (token > 0) {
            this.currentLease = new Lease(token, sendNano + ttlNs);
        }
    }

    public void fencedWrite(String key, String value) {
        Lease lease = this.currentLease;
        if (System.nanoTime() > lease.expiresAtNano() - 500_000_000L) {
            throw new IllegalStateException("Local lease near expiry; stepping down");
        }
        int updated = executeSql(
            "UPDATE kv_store SET val = ?, fencing_token = ? WHERE k = ? AND fencing_token <= ?",
            value, lease.fencingToken(), key, lease.fencingToken()
        );
        if (updated == 0) {
            this.currentLease = new Lease(-1L, 0L);
            throw new IllegalStateException("Fenced out by newer leader");
        }
    }
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Low-Pause GC & Fencing Tokens Apply in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Fencing tokens are mandatory whenever distributed leases protect mutable state:

  • Distributed Lock Services & Partition Leaders: Prevents split-brain writes in shard coordinators and cron schedulers.
  • Kafka & Stream Processors: producer_epoch is Kafka's built-in fencing token.
  • Low-Latency JVM Services: Generational ZGC / Shenandoah keeps tail latency flat under multi-GB/sec allocation.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why can't a leader node prevent split-brain solely by checking its local lease expiration timestamp before writing to storage?

Recommended Learning Flow