← All Exercises

Merge Replicas with Last-Writer-Wins

intermediatejavascript~25min

Background

Offline-first apps merge concurrent edits from several devices. A deterministic tie-break is what makes replication converge instead of oscillating.

Problem

Merge key-value updates from multiple replicas using logical clocks, keeping the value with the highest clock per key and reporting conflicts.

Input

JSON object: { replicas: [{ id, updates: [{ key, value, clock }] }] }

Output

JSON object: { merged: object, conflicts: string[] }

Sample tests

Sample 1

Input: {"replicas":[{"id":"r1","updates":[{"key":"title","value":"A","clock":3}]},{"id":"r2","updates":[{"key":"title","value":"B","clock":5}]}]}
Expected: {"merged":{"title":"B"},"conflicts":["title"]}

Sample 2

Input: {"replicas":[{"id":"r1","updates":[{"key":"done","value":true,"clock":1}]},{"id":"r2","updates":[{"key":"tags","value":["a"],"clock":2}]}]}
Expected: {"merged":{"done":true,"tags":["a"]},"conflicts":[]}

Your solution

Learning objective

Design a merge that converges under concurrent offline edits.