ARCHIVED from builddistributedsystem.com on 2026-04-28 — URL: https://builddistributedsystem.com/tracks/identifier/tasks/task-2-4-1-hlc-format
TASK

Implementation

Hybrid Logical Clocks (HLC), used in CockroachDB and Spanner, combine physical time with a logical counter. The format is (physical_ms, logical_counter).

Rules for updating HLC on a local event or send:

  1. Get current physical time pt
  2. If pt > hlc.pt: set hlc.pt = pt, hlc.lc = 0
  3. Else: keep hlc.pt, increment hlc.lc += 1

Implement an HLC with hlc_tick and hlc_get handlers:

Request:  {"type": "hlc_tick", "msg_id": 1}
Response: {"type": "hlc_tick_ok", "in_reply_to": 1, "pt": 1234567, "lc": 0}
Request:  {"type": "hlc_get", "msg_id": 2}
Response: {"type": "hlc_get_ok", "in_reply_to": 2, "pt": 1234567, "lc": 0}

Sample Test Cases

HLC tick returns pt and lcTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"hlc_tick","msg_id":2}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
HLC get returns initial zero stateTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"hlc_get","msg_id":2}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "hlc_get_ok", "pt": 0, "lc": 0, "in_reply_to": 2, "msg_id": 1}}

Hints

Hint 1
HLC is a tuple: (physical_time_ms, logical_counter)
Hint 2
Physical time comes from the system clock
Hint 3
Logical counter disambiguates events within the same millisecond
Hint 4
HLC always moves forward, even if clock goes backward
Hint 5
On send: if pt > max_pt, reset counter; else increment counter
OVERVIEW

Theoretical Hub

Concept overview coming soon

Key Concepts

HLChybrid clockphysical timelogical counter
main.py
python
Understand and Implement HLC Format - The Identifier | Build Distributed Systems