Challenge 4: Grow-Only Counter

desccode

Time to build a CRDT! Specifically a grow-only counter that works across distributed nodes without coordination. This is where distributed systems theory gets practical.

What it Does

  • Implements a grow-only (increment-only) counter
  • Each node maintains its own counter value
  • Nodes periodically sync to get the global view
  • No coordination needed for increments

The CRDT Approach

Used a G-Counter (Grow-only Counter) CRDT:

  1. Each node tracks increments per node (vector of counters)
  2. To increment: just bump your own counter
  3. To read: sum all nodes' counters
  4. To merge: take the max for each node position

Key Properties

  • Convergence: All nodes eventually see the same total
  • No Coordination: Increments are pure local operations
  • Partition Tolerant: Works even during network splits
  • Monotonic: Counter never decreases

Implementation Details

  • Vector of counters (one per node)
  • Periodic state exchange between nodes
  • Max-based merging for conflict resolution
  • Clean separation of local vs global operations

Why CRDTs Are Cool

  • Mathematical properties guarantee correctness
  • No need for locks, consensus, or coordination
  • Naturally partition tolerant
  • Simple to reason about

Trade-offs

Pros:

  • Zero coordination overhead
  • Partition tolerant by design
  • Eventually consistent
  • Simple local operations

Cons:

  • Space grows with number of nodes
  • Only supports increment (no decrement)
  • Network overhead for state sync

This pattern shows up everywhere in distributed systems - any time you need shared state without coordination, CRDTs are often the answer.

PrevSeriesNext