Hybrid Logical Clock Updates

medium · distributed-systems, clocks, ordering

Hybrid Logical Clock (HLC) Updates

Hybrid Logical Clocks combine physical time with a logical counter. Each HLC timestamp is (H, L):

  • H is the physical time component
  • L is a logical counter for ordering within the same H

You are given a starting HLC and a sequence of events. Each event includes the current physical time Now. For a receive event, a remote HLC is also provided. Compute the local HLC after each event.

HLC Update Rules

Let the current local clock be (H, L) and Now be the physical time.

Local or Send event:

  • If Now > H: H = Now, L = 0
  • Else: L = L + 1

Receive event with remote (Hr, Lr):

  1. H' = max(H, Hr, Now)
  2. If H' == H and H' == Hr: L = max(L, Lr) + 1
  3. Else if H' == H: L = L + 1
  4. Else if H' == Hr: L = Lr + 1
  5. Else (H' == Now): L = 0
  6. Set H = H'

Types

type Event struct {
    Kind    string // "local", "send", "recv"
    Now     int
    RemoteH int
    RemoteL int
}

type HLC struct {
    H int
    L int
}

Function signature

func HLCUpdates(start HLC, events []Event) []HLC

Example

start = (H=10, L=0)
Events:
1) local, Now=10
2) recv,  Now=12, remote=(11,3)

Result:
1) (10,1)
2) (12,0)

Constraints

  • 0 <= len(events) <= 100000
  • 0 <= Now, RemoteH, RemoteL <= 1_000_000
Run tests to see results
No issues detected