Lamport Logical Clock Implementation & It's Drawback
While reading about system design, I became interested in logical clocks and decided to further explore them. Here in this article, I will talk about Lamport Logical clock with it’s use case and implementation.
What are Logical Clocks?
In a distributed environment where several nodes or processes are working together, it then becomes important to order the events to maintain consistency. In this situation we cannot rely on a physical clock, as not every node of the distributed environment will have a synchronized physical clock.
Logical clocks let us maintain the ordering of events without relying on physical clocks. The main idea behind a logical clock is to maintain a local timestamp of the event and pass this timestamp when communicating with other nodes. Let's implement a very basic logical clock to understand this more.
Algorithm for Lamport Clock
Initialize a clock with zero.
When a node performs any action internally, it will increment its clock by one.
When sending a message to another node, the clock will be included with the message body.
Once another node receives a message, it will set its timestamp to the maximum value of the received timestamp or its own logical times.
Implementation
Code: https://github.com/x-sushant-x/Clocks/blob/main/logical_clock.go
Drawback
No, we have an issue, not an issue with implementation. Lamport Logical Clock cannot detect concurrency. If two events occur independently (e.g., in two different processes that do not communicate), their Lamport timestamps will be different, but you cannot tell whether they are causally related or concurrent.
Suppose we have three processes P1,P2,P3P1,P2,P3.
Events:
P1 does an action (timestamp = 1).
P1 sends a message to P2, which does an action (timestamp = 2).
P3 does an independent action (timestamp = 1).
Lamport clocks might look like this:
P1: 1 → 2
P2: 2
P3: 1
Here, we cannot tell if P3's event was before, after, or concurrent with P1 and P2.
Solution
In order to solve this issue, another type of clock was introduced that is known as a vector clock. Instead of maintaining just a single clock, it maintains a vector of clocks. You can try searching about vector clocks and implementing it on the basis of the Lamport clock. I am not covering Vector Clock in this blog, but if you want me to write a blog about it, I can do that too.
Also Read:
Let me know your thoughts in the comments. Also, you can subscribe to this newsletter, which is completely free, and I will make sure that the latest articles will reach your mailbox instantly.