Skip to main content

What is Realtime Sync?

Realtime sync means data changes are instantly propagated to all connected peers. When one user modifies data, all other users see the update immediately - no polling, no refresh needed. GUN makes realtime sync automatic and effortless:
GUN’s realtime sync works across devices and networks. Update on your phone, see it instantly on your laptop.

The .on() Method

The heart of realtime sync is the .on() method. From src/on.js:4:

Basic Usage

Subscribe to Nested Properties

Multiple Subscribers

.on() triggers immediately with the current value, then continues to trigger on every update.

.once() vs .on()

.once() - Single Read

From src/on.js:57, .once() reads data one time:

.on() - Continuous Subscription

Comparison

.once()

  • Read once
  • No memory overhead
  • Use for static data
  • Unsubscribes automatically

.on()

  • Continuous updates
  • Active subscription
  • Use for live data
  • Must call .off() to stop

Unsubscribing with .off()

From src/on.js:93, stop listening with .off():

Automatic Cleanup

Always call .off() when you’re done listening, especially in React components, to prevent memory leaks.

Pub/Sub Model

GUN implements a publish-subscribe pattern:

Publishers (Writers)

Subscribers (Readers)

Distributed Pub/Sub

Unlike traditional pub/sub systems (Redis, RabbitMQ), GUN’s pub/sub is distributed:

How Realtime Sync Works Internally

1. Local Update

When you call .put():
GUN:
  1. Updates local state immediately
  2. Triggers local .on() callbacks
  3. Creates a state vector (timestamp)
  4. Broadcasts to mesh network

2. Network Propagation

From src/mesh.js, updates flow through the mesh:

3. Remote Update

When a peer receives the update:

4. Conflict Resolution

If two peers write simultaneously, GUN uses state vectors (CRDTs) to resolve:
Learn more about conflict resolution in CRDT Concepts.

Building Realtime Apps

Example 1: Live Counter

Open this page in multiple tabs - they all sync in realtime!

Example 2: Collaborative Text Editor

For production text editors, use operational transforms or finer-grained CRDTs. This example demonstrates the concept.

Example 3: Live Dashboard

Example 4: Multiplayer Game State

Performance Optimization

Debouncing Updates

Selective Subscriptions

Lazy Loading

Realtime Across Network Conditions

Online

Offline

Back Online

GUN handles online/offline transitions automatically. No code changes needed.

Best Practices

1

Always unsubscribe

Call .off() when done to prevent memory leaks.
2

Use .once() for static data

If data doesn’t change, use .once() instead of .on().
3

Debounce rapid updates

Batch frequent writes to reduce network traffic.
4

Subscribe granularly

Listen to specific nodes, not entire collections.

Common Patterns

State Management

Presence (Online Users)

Activity Feeds

Next Steps

Offline-First

Learn how GUN works offline

CRDT

Understand conflict resolution