Deliver chat messages in causal order with vector clocks: buffering, duplicates, gaps and one shared timeline
Problem
In a group chat over an unreliable network, a reply can reach a member before the message it answers: Ravi answers Asha's "lunch?", and Meera's device gets "yes!" first. Showing the reply above the question is confusing. Causal ordering fixes this: a message is shown only after every message its sender had seen when writing it. Vector clocks make that dependency precise without a central server.
const asha = createReplica("asha");
const ravi = createReplica("ravi");
const meera = createReplica("meera");
const question = asha.send("lunch?");
ravi.receive(question);
const answer = ravi.send("yes!"); // clock { asha: 1, ravi: 1 }
meera.receive(answer); // [] (buffered: it depends on asha:1)
meera.missing(); // ["asha:1"]
meera.receive(question); // [question, answer]Ref. UR-1446 · © UIRound · uiround.com/questions/deliver-chat-messages-in-causal-order-with-vector-clocks-buffering-duplicates-gaps-and-one-shared-timeline
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 3
- code listings
- 6
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Give every replica a vector clock: for each sender, how many of its messages this replica has delivered. A sent message carries the sender's clock with its own entry incremented.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.