This snippet shows a complete implementation of a Hybrid Logical Clock (HLC) in TypeScript.
An HLC allows synchronizing time in multiple nodes in a distributed system (or local-first application), by using a combination of physical clock (timestamp e.g. Date.now()
) and logical clock (counter).
HLC allows ordering events without relying on a centralized system and avoids using the physical clock of distributed devices.
The snippet also contains an expanded implementation using effect
, which includes configuration using services and tracking errors with the Effect
type.
The algorithm is based on the paper Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases.
The implementation is inspired by multiple sources:
Read more about HLCs: