Lesson 1 of 14
Lamport Clocks
Lamport Clocks
In a distributed system, there is no global clock. Machines run at different speeds, clocks drift, and network delays are unpredictable. How do we order events?
Leslie Lamport introduced logical clocks in 1978. The core idea: if event A caused event B (A happened-before B), then timestamp(A) < timestamp(B).
The Rules
Each process maintains an integer counter:
- Before sending a message: increment your clock.
- On receiving a message: set your clock to
max(local, received) + 1. - For any other event: increment your clock.
class LamportClock {
constructor() {
this.time = 0;
}
tick() {
this.time++;
return this.time;
}
send() {
this.time++;
return this.time; // attach this to the message
}
receive(timestamp) {
this.time = Math.max(this.time, timestamp) + 1;
return this.time;
}
}
Example
const p1 = new LamportClock();
const p2 = new LamportClock();
const t1 = p1.send(); // p1 sends at time 1
const t2 = p2.receive(t1); // p2 receives: max(0, 1) + 1 = 2
const t3 = p2.send(); // p2 sends at time 3
const t4 = p1.receive(t3); // p1 receives: max(1, 3) + 1 = 4
Limitation
Lamport clocks provide partial ordering: if A happened-before B, then ts(A) < ts(B). But the converse is not guaranteed — ts(A) < ts(B) does not mean A caused B. For that, you need vector clocks.
Your Task
Implement a LamportClock class with tick(), send(), and receive(timestamp) methods. Each should return the new clock value.
JavaScript loading...
Loading...
Click "Run" to execute your code.