Skip to content

Go implementation of several clocks types: Lamport, Vector and Hybrid Logic Clock

License

Notifications You must be signed in to change notification settings

gasparian/logical-clocks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

main tests

logical-clocks

In the distributed systems there is a problem of defining causal order of events. Usually you need that to implement MVCC or CRDTs. And you can't always rely only on physical clocks since it is very hard to achieve tight clocks synchronization in real world.
But there is a very "elegant" solution to that: use logical clocks, where we can also rely on counting events occuring in the system.
So here you will find my naive go implementation of three basic logical clocks types: Lamport clock, Vector clock and Hybrid logical clock.

Usage

Run make init to replace pre-commit hook into .git folder.
To test the clocks implementations run make test.
Getting the package:

go get github.com/gasparian/logical-clocks

Then you can start using clocks:

import (
    hlc "github.com/gasparian/logical-clocks/hlc"
)

// Instantiate hybrid clock with the current wall clock timestamp
hc := hlc.NewNow(0)
// ...handle request from other service
req := ...
// Apply tick using the hybrid timestamp that came from another service
hc.Tick(req.Time)
// Get current time
currentTime := hc.Now()
// Compare two timestamps if needed
cmp := hlc.Compare(currentTime, req.Time)
// ...

API

All clocks shares the same API:

  • New() *SomeClock creates a new clock object;
  • clock.Now() SomeClock returns a copy of the current state of the clock;
  • clock.AddTicks(ticks int) adds the specified number to the internal counter (thread-safe);
  • clock.Tick(requestTime *SomeClock) moves clock forward, comparing to the incoming value;
  • Compare(a, b *SomeClock) compares the current states of two clocks, returns -1 ("happens before"), 0 ("concurrent") or 1;

References

About

Go implementation of several clocks types: Lamport, Vector and Hybrid Logic Clock

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published