JSON vs Y.Map Tradeoffs

Choosing between plain JSON objects and nested Y.Maps is a critical design decision.

The Core Tradeoff

Aspect JSON Objects Nested Y.Maps
Update granularity Whole object replaced Per-field
Concurrent field edits Last-write-wins (data loss!) Merge correctly
Memory overhead Lower Higher (CRDT metadata)
Code complexity Simpler More complex

The Concurrent Edit Problem

This is the critical consideration. With JSON objects, concurrent field edits cause data loss.

// Two users editing same entity
entities.set('player', { name: 'Alice', score: 100 })

// User A updates name:
entities.set('player', { ...entities.get('player'), name: 'Bob' })

// User B updates score (concurrently):
entities.set('player', { ...entities.get('player'), score: 200 })

// Result: ONE UPDATE IS LOST!
// Either { name: 'Bob', score: 100 } or { name: 'Alice', score: 200 }

With Y.Map, both changes merge correctly → { name: 'Bob', score: 200 }

Decision Framework

Use JSON when:

  • Thousands of small entities (memory matters)
  • Entities rarely updated after creation
  • Users won’t edit same entity simultaneously
  • Values are primitives

Use Y.Map when:

  • Concurrent editing of same entity is likely
  • Entities have many fields
  • Frequent partial updates
  • Field-level merging matters

Hybrid: Separate by Volatility

Different parts of entities may have different update patterns:

// Cell values: frequent, small, different users → different cells
const values = yDoc.getMap('values')     // JSON primitives
values.set('A1', 42)

// Styles: rare updates, can replace whole
const styles = yDoc.getMap('styles')     // JSON objects
styles.set('A1', { bold: true, color: '#000' })

// Canvas objects: concurrent x/y/size edits on same object
const objects = yDoc.getMap('objects')   // Nested Y.Maps

Memory Impact

Structure ~Overhead per item
JSON in Y.Map ~50 bytes
Nested Y.Map (5 fields) ~300 bytes

For 10,000 items: ~500KB (JSON) vs ~3MB (Y.Map)

Guidelines Summary

Scenario Recommendation
Large collection of small values JSON
Complex objects, unlikely concurrent edits JSON
Complex objects, likely concurrent edits Y.Map required
Mixed update patterns Separate maps by volatility

See Also